1 // Copyright (C) 2007-2022 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : StdMeshers_Cartesian_3D.cxx
25 #include "StdMeshers_Cartesian_3D.hxx"
26 #include "StdMeshers_CartesianParameters3D.hxx"
28 #include "ObjectPool.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_VolumeTool.hxx"
31 #include "SMESHDS_Mesh.hxx"
32 #include "SMESH_Block.hxx"
33 #include "SMESH_Comment.hxx"
34 #include "SMESH_ControlsDef.hxx"
35 #include "SMESH_Mesh.hxx"
36 #include "SMESH_MeshAlgos.hxx"
37 #include "SMESH_MeshEditor.hxx"
38 #include "SMESH_MesherHelper.hxx"
39 #include "SMESH_subMesh.hxx"
40 #include "SMESH_subMeshEventListener.hxx"
41 #include "StdMeshers_FaceSide.hxx"
43 #include <utilities.h>
44 #include <Utils_ExceptHandlers.hxx>
46 #include <GEOMUtils.hxx>
48 #include <BRepAdaptor_Curve.hxx>
49 #include <BRepAdaptor_Surface.hxx>
50 #include <BRepBndLib.hxx>
51 #include <BRepBuilderAPI_Copy.hxx>
52 #include <BRepBuilderAPI_MakeFace.hxx>
53 #include <BRepTools.hxx>
54 #include <BRepTopAdaptor_FClass2d.hxx>
55 #include <BRep_Builder.hxx>
56 #include <BRep_Tool.hxx>
57 #include <Bnd_B3d.hxx>
58 #include <Bnd_Box.hxx>
60 #include <GCPnts_UniformDeflection.hxx>
61 #include <Geom2d_BSplineCurve.hxx>
62 #include <Geom2d_BezierCurve.hxx>
63 #include <Geom2d_TrimmedCurve.hxx>
64 #include <GeomAPI_ProjectPointOnSurf.hxx>
65 #include <GeomLib.hxx>
66 #include <Geom_BSplineCurve.hxx>
67 #include <Geom_BSplineSurface.hxx>
68 #include <Geom_BezierCurve.hxx>
69 #include <Geom_BezierSurface.hxx>
70 #include <Geom_RectangularTrimmedSurface.hxx>
71 #include <Geom_TrimmedCurve.hxx>
72 #include <IntAna_IntConicQuad.hxx>
73 #include <IntAna_IntLinTorus.hxx>
74 #include <IntAna_Quadric.hxx>
75 #include <IntCurveSurface_TransitionOnCurve.hxx>
76 #include <IntCurvesFace_Intersector.hxx>
77 #include <Poly_Triangulation.hxx>
78 #include <Precision.hxx>
80 #include <TopExp_Explorer.hxx>
81 #include <TopLoc_Location.hxx>
82 #include <TopTools_DataMapOfShapeInteger.hxx>
83 #include <TopTools_IndexedMapOfShape.hxx>
84 #include <TopTools_MapOfShape.hxx>
86 #include <TopoDS_Compound.hxx>
87 #include <TopoDS_Face.hxx>
88 #include <TopoDS_TShape.hxx>
89 #include <gp_Cone.hxx>
90 #include <gp_Cylinder.hxx>
93 #include <gp_Pnt2d.hxx>
94 #include <gp_Sphere.hxx>
95 #include <gp_Torus.hxx>
99 #include <boost/container/flat_map.hpp>
102 // #define _MY_DEBUG_
109 // See https://docs.microsoft.com/en-gb/cpp/porting/modifying-winver-and-win32-winnt?view=vs-2019
110 // Windows 10 = 0x0A00
111 #define WINVER 0x0A00
112 #define _WIN32_WINNT 0x0A00
115 #include <tbb/parallel_for.h>
116 //#include <tbb/enumerable_thread_specific.h>
120 using namespace SMESH;
122 //=============================================================================
126 //=============================================================================
128 StdMeshers_Cartesian_3D::StdMeshers_Cartesian_3D(int hypId, SMESH_Gen * gen)
129 :SMESH_3D_Algo(hypId, gen)
131 _name = "Cartesian_3D";
132 _shapeType = (1 << TopAbs_SOLID); // 1 bit /shape type
133 _compatibleHypothesis.push_back("CartesianParameters3D");
135 _onlyUnaryInput = false; // to mesh all SOLIDs at once
136 _requireDiscreteBoundary = false; // 2D mesh not needed
137 _supportSubmeshes = false; // do not use any existing mesh
140 //=============================================================================
142 * Check presence of a hypothesis
144 //=============================================================================
146 bool StdMeshers_Cartesian_3D::CheckHypothesis (SMESH_Mesh& aMesh,
147 const TopoDS_Shape& aShape,
148 Hypothesis_Status& aStatus)
150 aStatus = SMESH_Hypothesis::HYP_MISSING;
152 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape);
153 list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
154 if ( h == hyps.end())
159 for ( ; h != hyps.end(); ++h )
161 if (( _hyp = dynamic_cast<const StdMeshers_CartesianParameters3D*>( *h )))
163 aStatus = _hyp->IsDefined() ? HYP_OK : HYP_BAD_PARAMETER;
168 return aStatus == HYP_OK;
173 typedef int TGeomID; // IDs of sub-shapes
175 const TGeomID theUndefID = 1e+9;
177 //=============================================================================
178 // Definitions of internal utils
179 // --------------------------------------------------------------------------
181 Trans_TANGENT = IntCurveSurface_Tangent,
182 Trans_IN = IntCurveSurface_In,
183 Trans_OUT = IntCurveSurface_Out,
185 Trans_INTERNAL // for INTERNAL FACE
187 // --------------------------------------------------------------------------
189 * \brief Sub-entities of a FACE neighboring its concave VERTEX.
190 * Help to avoid linking nodes on EDGEs that seem connected
191 * by the concave FACE but the link actually lies outside the FACE
195 TGeomID _concaveFace;
196 TGeomID _edge1, _edge2;
198 ConcaveFace( int f=0, int e1=0, int e2=0, int v1=0, int v2=0 )
199 : _concaveFace(f), _edge1(e1), _edge2(e2), _v1(v1), _v2(v2) {}
200 bool HasEdge( TGeomID edge ) const { return edge == _edge1 || edge == _edge2; }
201 bool HasVertex( TGeomID v ) const { return v == _v1 || v == _v2; }
202 void SetEdge( TGeomID edge ) { ( _edge1 ? _edge2 : _edge1 ) = edge; }
203 void SetVertex( TGeomID v ) { ( _v1 ? _v2 : _v1 ) = v; }
205 typedef NCollection_DataMap< TGeomID, ConcaveFace > TConcaveVertex2Face;
206 // --------------------------------------------------------------------------
208 * \brief Container of IDs of SOLID sub-shapes
210 class Solid // sole SOLID contains all sub-shapes
212 TGeomID _id; // SOLID id
213 bool _hasInternalFaces;
214 TConcaveVertex2Face _concaveVertex; // concave VERTEX -> ConcaveFace
217 virtual bool Contains( TGeomID /*subID*/ ) const { return true; }
218 virtual bool ContainsAny( const vector< TGeomID>& /*subIDs*/ ) const { return true; }
219 virtual TopAbs_Orientation Orientation( const TopoDS_Shape& s ) const { return s.Orientation(); }
220 virtual bool IsOutsideOriented( TGeomID /*faceID*/ ) const { return true; }
221 void SetID( TGeomID id ) { _id = id; }
222 TGeomID ID() const { return _id; }
223 void SetHasInternalFaces( bool has ) { _hasInternalFaces = has; }
224 bool HasInternalFaces() const { return _hasInternalFaces; }
225 void SetConcave( TGeomID V, TGeomID F, TGeomID E1, TGeomID E2, TGeomID V1, TGeomID V2 )
226 { _concaveVertex.Bind( V, ConcaveFace{ F, E1, E2, V1, V2 }); }
227 bool HasConcaveVertex() const { return !_concaveVertex.IsEmpty(); }
228 const ConcaveFace* GetConcave( TGeomID V ) const { return _concaveVertex.Seek( V ); }
230 // --------------------------------------------------------------------------
231 class OneOfSolids : public Solid
233 TColStd_MapOfInteger _subIDs;
234 TopTools_MapOfShape _faces; // keep FACE orientation
235 TColStd_MapOfInteger _outFaceIDs; // FACEs of shape_to_mesh oriented outside the SOLID
237 void Init( const TopoDS_Shape& solid,
238 TopAbs_ShapeEnum subType,
239 const SMESHDS_Mesh* mesh );
240 virtual bool Contains( TGeomID i ) const { return i == ID() || _subIDs.Contains( i ); }
241 virtual bool ContainsAny( const vector< TGeomID>& subIDs ) const
243 for ( size_t i = 0; i < subIDs.size(); ++i ) if ( Contains( subIDs[ i ])) return true;
246 virtual TopAbs_Orientation Orientation( const TopoDS_Shape& face ) const
248 const TopoDS_Shape& sInMap = const_cast< OneOfSolids* >(this)->_faces.Added( face );
249 return sInMap.Orientation();
251 virtual bool IsOutsideOriented( TGeomID faceID ) const
253 return faceID == 0 || _outFaceIDs.Contains( faceID );
256 // --------------------------------------------------------------------------
258 * \brief Hold a vector of TGeomID and clear it at destruction
260 class GeomIDVecHelder
262 typedef std::vector< TGeomID > TVector;
263 const TVector& myVec;
267 GeomIDVecHelder( const TVector& idVec, bool isOwner ): myVec( idVec ), myOwn( isOwner ) {}
268 GeomIDVecHelder( const GeomIDVecHelder& holder ): myVec( holder.myVec ), myOwn( holder.myOwn )
270 const_cast< bool& >( holder.myOwn ) = false;
272 ~GeomIDVecHelder() { if ( myOwn ) const_cast<TVector&>( myVec ).clear(); }
273 size_t size() const { return myVec.size(); }
274 TGeomID operator[]( size_t i ) const { return i < size() ? myVec[i] : theUndefID; }
275 bool operator==( const GeomIDVecHelder& other ) const { return myVec == other.myVec; }
276 bool contain( const TGeomID& id ) const {
277 return std::find( myVec.begin(), myVec.end(), id ) != myVec.end();
279 TGeomID otherThan( const TGeomID& id ) const {
280 for ( const TGeomID& id2 : myVec )
285 TGeomID oneCommon( const GeomIDVecHelder& other ) const {
286 TGeomID common = theUndefID;
287 for ( const TGeomID& id : myVec )
288 if ( other.contain( id ))
290 if ( common != theUndefID )
297 // --------------------------------------------------------------------------
303 TopoDS_Shape _mainShape;
304 vector< vector< TGeomID > > _solidIDsByShapeID;// V/E/F ID -> SOLID IDs
306 map< TGeomID, OneOfSolids > _solidByID;
307 TColStd_MapOfInteger _boundaryFaces; // FACEs on boundary of mesh->ShapeToMesh()
308 TColStd_MapOfInteger _strangeEdges; // EDGEs shared by strange FACEs
309 TGeomID _extIntFaceID; // pseudo FACE - extension of INTERNAL FACE
311 TopTools_DataMapOfShapeInteger _shape2NbNodes; // nb of pre-existing nodes on shapes
313 Controls::ElementsOnShape _edgeClassifier;
314 Controls::ElementsOnShape _vertexClassifier;
316 bool IsOneSolid() const { return _solidByID.size() < 2; }
317 GeomIDVecHelder GetSolidIDsByShapeID( const vector< TGeomID >& shapeIDs ) const;
319 // --------------------------------------------------------------------------
321 * \brief Common data of any intersection between a Grid and a shape
323 struct B_IntersectPoint
325 mutable const SMDS_MeshNode* _node;
326 mutable vector< TGeomID > _faceIDs;
328 B_IntersectPoint(): _node(NULL) {}
329 bool Add( const vector< TGeomID >& fIDs, const SMDS_MeshNode* n=0 ) const;
330 TGeomID HasCommonFace( const B_IntersectPoint * other, TGeomID avoidFace=-1 ) const;
331 size_t GetCommonFaces( const B_IntersectPoint * other, TGeomID * commonFaces ) const;
332 bool IsOnFace( TGeomID faceID ) const;
333 virtual ~B_IntersectPoint() {}
335 // --------------------------------------------------------------------------
337 * \brief Data of intersection between a GridLine and a TopoDS_Face
339 struct F_IntersectPoint : public B_IntersectPoint
343 mutable Transition _transition;
344 mutable size_t _indexOnLine;
346 bool operator< ( const F_IntersectPoint& o ) const { return _paramOnLine < o._paramOnLine; }
348 // --------------------------------------------------------------------------
350 * \brief Data of intersection between GridPlanes and a TopoDS_EDGE
352 struct E_IntersectPoint : public B_IntersectPoint
356 TGeomID _shapeID; // ID of EDGE or VERTEX
358 // --------------------------------------------------------------------------
360 * \brief A line of the grid and its intersections with 2D geometry
365 double _length; // line length
366 multiset< F_IntersectPoint > _intPoints;
368 void RemoveExcessIntPoints( const double tol );
369 TGeomID GetSolidIDBefore( multiset< F_IntersectPoint >::iterator ip,
370 const TGeomID prevID,
371 const Geometry& geom);
373 // --------------------------------------------------------------------------
375 * \brief Planes of the grid used to find intersections of an EDGE with a hexahedron
380 vector< gp_XYZ > _origins; // origin points of all planes in one direction
381 vector< double > _zProjs; // projections of origins to _zNorm
383 // --------------------------------------------------------------------------
385 * \brief Iterator on the parallel grid lines of one direction
391 size_t _iVar1, _iVar2, _iConst;
392 string _name1, _name2, _nameConst;
394 LineIndexer( size_t sz1, size_t sz2, size_t sz3,
395 size_t iv1, size_t iv2, size_t iConst,
396 const string& nv1, const string& nv2, const string& nConst )
398 _size[0] = sz1; _size[1] = sz2; _size[2] = sz3;
399 _curInd[0] = _curInd[1] = _curInd[2] = 0;
400 _iVar1 = iv1; _iVar2 = iv2; _iConst = iConst;
401 _name1 = nv1; _name2 = nv2; _nameConst = nConst;
404 size_t I() const { return _curInd[0]; }
405 size_t J() const { return _curInd[1]; }
406 size_t K() const { return _curInd[2]; }
407 void SetIJK( size_t i, size_t j, size_t k )
409 _curInd[0] = i; _curInd[1] = j; _curInd[2] = k;
413 if ( ++_curInd[_iVar1] == _size[_iVar1] )
414 _curInd[_iVar1] = 0, ++_curInd[_iVar2];
416 bool More() const { return _curInd[_iVar2] < _size[_iVar2]; }
417 size_t LineIndex () const { return _curInd[_iVar1] + _curInd[_iVar2]* _size[_iVar1]; }
418 size_t LineIndex10 () const { return (_curInd[_iVar1] + 1 ) + _curInd[_iVar2]* _size[_iVar1]; }
419 size_t LineIndex01 () const { return _curInd[_iVar1] + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
420 size_t LineIndex11 () const { return (_curInd[_iVar1] + 1 ) + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
421 void SetIndexOnLine (size_t i) { _curInd[ _iConst ] = i; }
422 size_t NbLines() const { return _size[_iVar1] * _size[_iVar2]; }
424 // --------------------------------------------------------------------------
426 * \brief Container of GridLine's
430 vector< double > _coords[3]; // coordinates of grid nodes
431 gp_XYZ _axes [3]; // axis directions
432 vector< GridLine > _lines [3]; // in 3 directions
433 double _tol, _minCellSize;
435 gp_Mat _invB; // inverted basis of _axes
437 // index shift within _nodes of nodes of a cell from the 1st node
440 vector< const SMDS_MeshNode* > _nodes; // mesh nodes at grid nodes
441 vector< const F_IntersectPoint* > _gridIntP; // grid node intersection with geometry
442 ObjectPool< E_IntersectPoint > _edgeIntPool; // intersections with EDGEs
443 ObjectPool< F_IntersectPoint > _extIntPool; // intersections with extended INTERNAL FACEs
444 //list< E_IntersectPoint > _edgeIntP; // intersections with EDGEs
449 bool _toConsiderInternalFaces;
450 bool _toUseThresholdForInternalFaces;
451 double _sizeThreshold;
453 SMESH_MesherHelper* _helper;
455 size_t CellIndex( size_t i, size_t j, size_t k ) const
457 return i + j*(_coords[0].size()-1) + k*(_coords[0].size()-1)*(_coords[1].size()-1);
459 size_t NodeIndex( size_t i, size_t j, size_t k ) const
461 return i + j*_coords[0].size() + k*_coords[0].size()*_coords[1].size();
463 size_t NodeIndexDX() const { return 1; }
464 size_t NodeIndexDY() const { return _coords[0].size(); }
465 size_t NodeIndexDZ() const { return _coords[0].size() * _coords[1].size(); }
467 LineIndexer GetLineIndexer(size_t iDir) const;
469 E_IntersectPoint* Add( const E_IntersectPoint& ip )
471 E_IntersectPoint* eip = _edgeIntPool.getNew();
475 void Remove( E_IntersectPoint* eip ) { _edgeIntPool.destroy( eip ); }
477 TGeomID ShapeID( const TopoDS_Shape& s ) const;
478 const TopoDS_Shape& Shape( TGeomID id ) const;
479 TopAbs_ShapeEnum ShapeType( TGeomID id ) const { return Shape(id).ShapeType(); }
480 void InitGeometry( const TopoDS_Shape& theShape );
481 void InitClassifier( const TopoDS_Shape& mainShape,
482 TopAbs_ShapeEnum shapeType,
483 Controls::ElementsOnShape& classifier );
484 void GetEdgesToImplement( map< TGeomID, vector< TGeomID > > & edge2faceMap,
485 const TopoDS_Shape& shape,
486 const vector< TopoDS_Shape >& faces );
487 void SetSolidFather( const TopoDS_Shape& s, const TopoDS_Shape& theShapeToMesh );
488 bool IsShared( TGeomID faceID ) const;
489 bool IsAnyShared( const std::vector< TGeomID >& faceIDs ) const;
490 bool IsInternal( TGeomID faceID ) const {
491 return ( faceID == PseudoIntExtFaceID() ||
492 Shape( faceID ).Orientation() == TopAbs_INTERNAL ); }
493 bool IsSolid( TGeomID shapeID ) const {
494 if ( _geometry.IsOneSolid() ) return _geometry._soleSolid.ID() == shapeID;
495 else return _geometry._solidByID.count( shapeID ); }
496 bool IsStrangeEdge( TGeomID id ) const { return _geometry._strangeEdges.Contains( id ); }
497 TGeomID PseudoIntExtFaceID() const { return _geometry._extIntFaceID; }
498 Solid* GetSolid( TGeomID solidID = 0 );
499 Solid* GetOneOfSolids( TGeomID solidID );
500 const vector< TGeomID > & GetSolidIDs( TGeomID subShapeID ) const;
501 bool IsCorrectTransition( TGeomID faceID, const Solid* solid );
502 bool IsBoundaryFace( TGeomID face ) const { return _geometry._boundaryFaces.Contains( face ); }
503 void SetOnShape( const SMDS_MeshNode* n, const F_IntersectPoint& ip,
504 TopoDS_Vertex* vertex = nullptr, bool unset = false );
505 void UpdateFacesOfVertex( const B_IntersectPoint& ip, const TopoDS_Vertex& vertex );
506 bool IsToCheckNodePos() const { return !_toAddEdges && _toCreateFaces; }
507 bool IsToRemoveExcessEntities() const { return !_toAddEdges; }
509 void SetCoordinates(const vector<double>& xCoords,
510 const vector<double>& yCoords,
511 const vector<double>& zCoords,
512 const double* axesDirs,
513 const Bnd_Box& bndBox );
514 void ComputeUVW(const gp_XYZ& p, double uvw[3]);
515 void ComputeNodes(SMESH_MesherHelper& helper);
517 // --------------------------------------------------------------------------
519 * \brief Return cells sharing a link
521 struct CellsAroundLink
529 CellsAroundLink( Grid* grid, int iDir ):
531 _dInd{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} },
532 _nbCells{ grid->_coords[0].size() - 1,
533 grid->_coords[1].size() - 1,
534 grid->_coords[2].size() - 1 },
537 const int iDirOther[3][2] = {{ 1,2 },{ 0,2 },{ 0,1 }};
538 _dInd[1][ iDirOther[iDir][0] ] = -1;
539 _dInd[2][ iDirOther[iDir][1] ] = -1;
540 _dInd[3][ iDirOther[iDir][0] ] = -1; _dInd[3][ iDirOther[iDir][1] ] = -1;
542 void Init( int i, int j, int k, int link12 = 0 )
545 _i = i - _dInd[iL][0];
546 _j = j - _dInd[iL][1];
547 _k = k - _dInd[iL][2];
549 bool GetCell( int iL, int& i, int& j, int& k, int& cellIndex, int& linkIndex )
551 i = _i + _dInd[iL][0];
552 j = _j + _dInd[iL][1];
553 k = _k + _dInd[iL][2];
554 if ( i < 0 || i >= (int)_nbCells[0] ||
555 j < 0 || j >= (int)_nbCells[1] ||
556 k < 0 || k >= (int)_nbCells[2] )
558 cellIndex = _grid->CellIndex( i,j,k );
559 linkIndex = iL + _iDir * 4;
563 // --------------------------------------------------------------------------
565 * \brief Intersector of TopoDS_Face with all GridLine's
567 struct FaceGridIntersector
573 IntCurvesFace_Intersector* _surfaceInt;
574 vector< std::pair< GridLine*, F_IntersectPoint > > _intersections;
576 FaceGridIntersector(): _grid(0), _surfaceInt(0) {}
579 void StoreIntersections()
581 for ( size_t i = 0; i < _intersections.size(); ++i )
583 multiset< F_IntersectPoint >::iterator ip =
584 _intersections[i].first->_intPoints.insert( _intersections[i].second );
585 ip->_faceIDs.reserve( 1 );
586 ip->_faceIDs.push_back( _faceID );
589 const Bnd_Box& GetFaceBndBox()
591 GetCurveFaceIntersector();
594 IntCurvesFace_Intersector* GetCurveFaceIntersector()
598 _surfaceInt = new IntCurvesFace_Intersector( _face, Precision::PConfusion() );
599 _bndBox = _surfaceInt->Bounding();
600 if ( _bndBox.IsVoid() )
601 BRepBndLib::Add (_face, _bndBox);
605 bool IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const;
607 // --------------------------------------------------------------------------
609 * \brief Intersector of a surface with a GridLine
611 struct FaceLineIntersector
614 double _u, _v, _w; // params on the face and the line
615 Transition _transition; // transition at intersection (see IntCurveSurface.cdl)
616 Transition _transIn, _transOut; // IN and OUT transitions depending of face orientation
619 gp_Cylinder _cylinder;
623 IntCurvesFace_Intersector* _surfaceInt;
625 vector< F_IntersectPoint > _intPoints;
627 void IntersectWithPlane (const GridLine& gridLine);
628 void IntersectWithCylinder(const GridLine& gridLine);
629 void IntersectWithCone (const GridLine& gridLine);
630 void IntersectWithSphere (const GridLine& gridLine);
631 void IntersectWithTorus (const GridLine& gridLine);
632 void IntersectWithSurface (const GridLine& gridLine);
634 bool UVIsOnFace() const;
635 void addIntPoint(const bool toClassify=true);
636 bool isParamOnLineOK( const double linLength )
638 return -_tol < _w && _w < linLength + _tol;
640 FaceLineIntersector():_surfaceInt(0) {}
641 ~FaceLineIntersector() { if (_surfaceInt ) delete _surfaceInt; _surfaceInt = 0; }
643 // --------------------------------------------------------------------------
645 * \brief Class representing topology of the hexahedron and creating a mesh
646 * volume basing on analysis of hexahedron intersection with geometry
650 // --------------------------------------------------------------------------------
653 enum IsInternalFlag { IS_NOT_INTERNAL, IS_INTERNAL, IS_CUT_BY_INTERNAL_FACE };
654 // --------------------------------------------------------------------------------
655 struct _Node //!< node either at a hexahedron corner or at intersection
657 const SMDS_MeshNode* _node; // mesh node at hexahedron corner
658 const B_IntersectPoint* _intPoint;
659 const _Face* _usedInFace;
660 char _isInternalFlags;
662 _Node(const SMDS_MeshNode* n=0, const B_IntersectPoint* ip=0)
663 :_node(n), _intPoint(ip), _usedInFace(0), _isInternalFlags(0) {}
664 const SMDS_MeshNode* Node() const
665 { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
666 const E_IntersectPoint* EdgeIntPnt() const
667 { return static_cast< const E_IntersectPoint* >( _intPoint ); }
668 const F_IntersectPoint* FaceIntPnt() const
669 { return static_cast< const F_IntersectPoint* >( _intPoint ); }
670 const vector< TGeomID >& faces() const { return _intPoint->_faceIDs; }
671 TGeomID face(size_t i) const { return _intPoint->_faceIDs[ i ]; }
672 void SetInternal( IsInternalFlag intFlag ) { _isInternalFlags |= intFlag; }
673 bool IsCutByInternal() const { return _isInternalFlags & IS_CUT_BY_INTERNAL_FACE; }
674 bool IsUsedInFace( const _Face* polygon = 0 )
676 return polygon ? ( _usedInFace == polygon ) : bool( _usedInFace );
678 TGeomID IsLinked( const B_IntersectPoint* other,
679 TGeomID avoidFace=-1 ) const // returns id of a common face
681 return _intPoint ? _intPoint->HasCommonFace( other, avoidFace ) : 0;
683 bool IsOnFace( TGeomID faceID ) const // returns true if faceID is found
685 return _intPoint ? _intPoint->IsOnFace( faceID ) : false;
687 size_t GetCommonFaces( const B_IntersectPoint * other, TGeomID* common ) const
689 return _intPoint && other ? _intPoint->GetCommonFaces( other, common ) : 0;
693 if ( const SMDS_MeshNode* n = Node() )
694 return SMESH_NodeXYZ( n );
695 if ( const E_IntersectPoint* eip =
696 dynamic_cast< const E_IntersectPoint* >( _intPoint ))
698 return gp_Pnt( 1e100, 0, 0 );
700 TGeomID ShapeID() const
702 if ( const E_IntersectPoint* eip = dynamic_cast< const E_IntersectPoint* >( _intPoint ))
703 return eip->_shapeID;
706 void Add( const E_IntersectPoint* ip )
708 // Possible cases before Add(ip):
709 /// 1) _node != 0 --> _Node at hex corner ( _intPoint == 0 || _intPoint._node == 0 )
710 /// 2) _node == 0 && _intPoint._node != 0 --> link intersected by FACE
711 /// 3) _node == 0 && _intPoint._node == 0 --> _Node at EDGE intersection
713 // If ip is added in cases 1) and 2) _node position must be changed to ip._shapeID
714 // at creation of elements
715 // To recognize this case, set _intPoint._node = Node()
716 const SMDS_MeshNode* node = Node();
721 ip->Add( _intPoint->_faceIDs );
725 _node = _intPoint->_node = node;
728 // --------------------------------------------------------------------------------
729 struct _Link // link connecting two _Node's
732 _Face* _faces[2]; // polygons sharing a link
733 vector< const F_IntersectPoint* > _fIntPoints; // GridLine intersections with FACEs
734 vector< _Node* > _fIntNodes; // _Node's at _fIntPoints
735 vector< _Link > _splits;
736 _Link(): _faces{ 0, 0 } {}
738 // --------------------------------------------------------------------------------
743 _OrientedLink( _Link* link=0, bool reverse=false ): _link(link), _reverse(reverse) {}
744 void Reverse() { _reverse = !_reverse; }
745 size_t NbResultLinks() const { return _link->_splits.size(); }
746 _OrientedLink ResultLink(int i) const
748 return _OrientedLink(&_link->_splits[_reverse ? NbResultLinks()-i-1 : i],_reverse);
750 _Node* FirstNode() const { return _link->_nodes[ _reverse ]; }
751 _Node* LastNode() const { return _link->_nodes[ !_reverse ]; }
752 operator bool() const { return _link; }
753 vector< TGeomID > GetNotUsedFace(const set<TGeomID>& usedIDs ) const // returns supporting FACEs
755 vector< TGeomID > faces;
756 const B_IntersectPoint *ip0, *ip1;
757 if (( ip0 = _link->_nodes[0]->_intPoint ) &&
758 ( ip1 = _link->_nodes[1]->_intPoint ))
760 for ( size_t i = 0; i < ip0->_faceIDs.size(); ++i )
761 if ( ip1->IsOnFace ( ip0->_faceIDs[i] ) &&
762 !usedIDs.count( ip0->_faceIDs[i] ) )
763 faces.push_back( ip0->_faceIDs[i] );
767 bool HasEdgeNodes() const
769 return ( dynamic_cast< const E_IntersectPoint* >( _link->_nodes[0]->_intPoint ) ||
770 dynamic_cast< const E_IntersectPoint* >( _link->_nodes[1]->_intPoint ));
774 return !_link->_faces[0] ? 0 : 1 + bool( _link->_faces[1] );
776 void AddFace( _Face* f )
778 if ( _link->_faces[0] )
780 _link->_faces[1] = f;
784 _link->_faces[0] = f;
785 _link->_faces[1] = 0;
788 void RemoveFace( _Face* f )
790 if ( !_link->_faces[0] ) return;
792 if ( _link->_faces[1] == f )
794 _link->_faces[1] = 0;
796 else if ( _link->_faces[0] == f )
798 _link->_faces[0] = 0;
799 if ( _link->_faces[1] )
801 _link->_faces[0] = _link->_faces[1];
802 _link->_faces[1] = 0;
807 // --------------------------------------------------------------------------------
808 struct _SplitIterator //! set to _hexLinks splits on one side of INTERNAL FACEs
810 struct _Split // data of a link split
812 int _linkID; // hex link ID
814 int _iCheckIteration; // iteration where split is tried as Hexahedron split
815 _Link* _checkedSplit; // split set to hex links
816 bool _isUsed; // used in a volume
818 _Split( _Link & split, int iLink ):
819 _linkID( iLink ), _nodes{ split._nodes[0], split._nodes[1] },
820 _iCheckIteration( 0 ), _isUsed( false )
822 bool IsCheckedOrUsed( bool used ) const { return used ? _isUsed : _iCheckIteration > 0; }
825 std::vector< _Split > _splits;
829 std::vector< _Node* > _freeNodes; // nodes reached while composing a split set
831 _SplitIterator( _Link* hexLinks ):
832 _hexLinks( hexLinks ), _iterationNb(0), _nbChecked(0), _nbUsed(0)
834 _freeNodes.reserve( 12 );
835 _splits.reserve( 24 );
836 for ( int iL = 0; iL < 12; ++iL )
837 for ( size_t iS = 0; iS < _hexLinks[ iL ]._splits.size(); ++iS )
838 _splits.emplace_back( _hexLinks[ iL ]._splits[ iS ], iL );
841 bool More() const { return _nbUsed < _splits.size(); }
844 // --------------------------------------------------------------------------------
847 SMESH_Block::TShapeID _name;
848 vector< _OrientedLink > _links; // links on GridLine's
849 vector< _Link > _polyLinks; // links added to close a polygonal face
850 vector< _Node* > _eIntNodes; // nodes at intersection with EDGEs
852 _Face():_name( SMESH_Block::ID_NONE )
854 bool IsPolyLink( const _OrientedLink& ol )
856 return _polyLinks.empty() ? false :
857 ( &_polyLinks[0] <= ol._link && ol._link <= &_polyLinks.back() );
859 void AddPolyLink(_Node* n0, _Node* n1, _Face* faceToFindEqual=0)
861 if ( faceToFindEqual && faceToFindEqual != this ) {
862 for ( size_t iL = 0; iL < faceToFindEqual->_polyLinks.size(); ++iL )
863 if ( faceToFindEqual->_polyLinks[iL]._nodes[0] == n1 &&
864 faceToFindEqual->_polyLinks[iL]._nodes[1] == n0 )
867 ( _OrientedLink( & faceToFindEqual->_polyLinks[iL], /*reverse=*/true ));
874 _polyLinks.push_back( l );
875 _links.push_back( _OrientedLink( &_polyLinks.back() ));
878 // --------------------------------------------------------------------------------
879 struct _volumeDef // holder of nodes of a volume mesh element
885 const SMDS_MeshNode* _node; // mesh node at hexahedron corner
886 const B_IntersectPoint* _intPoint;
888 _nodeDef(): _node(0), _intPoint(0) {}
889 _nodeDef( _Node* n ): _node( n->_node), _intPoint( n->_intPoint ) {}
890 const SMDS_MeshNode* Node() const
891 { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
892 const E_IntersectPoint* EdgeIntPnt() const
893 { return static_cast< const E_IntersectPoint* >( _intPoint ); }
894 _ptr Ptr() const { return Node() ? (_ptr) Node() : (_ptr) EdgeIntPnt(); }
895 bool operator==(const _nodeDef& other ) const { return Ptr() == other.Ptr(); }
898 vector< _nodeDef > _nodes;
899 vector< int > _quantities;
900 _volumeDef* _next; // to store several _volumeDefs in a chain
903 const SMDS_MeshElement* _volume; // new volume
905 vector< SMESH_Block::TShapeID > _names; // name of side a polygon originates from
907 _volumeDef(): _next(0), _solidID(0), _size(0), _volume(0) {}
908 ~_volumeDef() { delete _next; }
909 _volumeDef( _volumeDef& other ):
910 _next(0), _solidID( other._solidID ), _size( other._size ), _volume( other._volume )
911 { _nodes.swap( other._nodes ); _quantities.swap( other._quantities ); other._volume = 0;
912 _names.swap( other._names ); }
914 size_t size() const { return 1 + ( _next ? _next->size() : 0 ); } // nb _volumeDef in a chain
915 _volumeDef* at(int index)
916 { return index == 0 ? this : ( _next ? _next->at(index-1) : _next ); }
918 void Set( _Node** nodes, int nb )
919 { _nodes.assign( nodes, nodes + nb ); }
921 void SetNext( _volumeDef* vd )
922 { if ( _next ) { _next->SetNext( vd ); } else { _next = vd; }}
924 bool IsEmpty() const { return (( _nodes.empty() ) &&
925 ( !_next || _next->IsEmpty() )); }
926 bool IsPolyhedron() const { return ( !_quantities.empty() ||
927 ( _next && !_next->_quantities.empty() )); }
930 struct _linkDef: public std::pair<_ptr,_ptr> // to join polygons in removeExcessSideDivision()
932 _nodeDef _node1;//, _node2;
933 mutable /*const */_linkDef *_prev, *_next;
936 _linkDef():_prev(0), _next(0) {}
938 void init( const _nodeDef& n1, const _nodeDef& n2, size_t iLoop )
940 _node1 = n1; //_node2 = n2;
944 if ( first > second ) std::swap( first, second );
946 void setNext( _linkDef* next )
954 // topology of a hexahedron
956 _Link _hexLinks [12];
959 // faces resulted from hexahedron intersection
960 vector< _Face > _polygons;
962 // intresections with EDGEs
963 vector< const E_IntersectPoint* > _eIntPoints;
965 // additional nodes created at intersection points
966 vector< _Node > _intNodes;
968 // nodes inside the hexahedron (at VERTEXes) refer to _intNodes
969 vector< _Node* > _vIntNodes;
971 // computed volume elements
972 _volumeDef _volumeDefs;
975 double _sideLength[3];
976 int _nbCornerNodes, _nbFaceIntNodes, _nbBndNodes;
977 int _origNodeInd; // index of _hexNodes[0] node within the _grid
983 Hexahedron(Grid* grid);
984 int MakeElements(SMESH_MesherHelper& helper,
985 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
986 void computeElements( const Solid* solid = 0, int solidIndex = -1 );
989 Hexahedron(const Hexahedron& other, size_t i, size_t j, size_t k, int cellID );
990 void init( size_t i, size_t j, size_t k, const Solid* solid=0 );
991 void init( size_t i );
992 void setIJK( size_t i );
993 bool compute( const Solid* solid, const IsInternalFlag intFlag );
994 size_t getSolids( TGeomID ids[] );
995 bool isCutByInternalFace( IsInternalFlag & maxFlag );
996 void addEdges(SMESH_MesherHelper& helper,
997 vector< Hexahedron* >& intersectedHex,
998 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
999 gp_Pnt findIntPoint( double u1, double proj1, double u2, double proj2,
1000 double proj, BRepAdaptor_Curve& curve,
1001 const gp_XYZ& axis, const gp_XYZ& origin );
1002 int getEntity( const E_IntersectPoint* ip, int* facets, int& sub );
1003 bool addIntersection( const E_IntersectPoint* ip,
1004 vector< Hexahedron* >& hexes,
1005 int ijk[], int dIJK[] );
1006 bool isQuadOnFace( const size_t iQuad );
1007 bool findChain( _Node* n1, _Node* n2, _Face& quad, vector<_Node*>& chainNodes );
1008 bool closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const;
1009 bool findChainOnEdge( const vector< _OrientedLink >& splits,
1010 const _OrientedLink& prevSplit,
1011 const _OrientedLink& avoidSplit,
1012 const std::set< TGeomID > & concaveFaces,
1015 vector<_Node*>& chn);
1016 int addVolumes(SMESH_MesherHelper& helper );
1017 void addFaces( SMESH_MesherHelper& helper,
1018 const vector< const SMDS_MeshElement* > & boundaryVolumes );
1019 void addSegments( SMESH_MesherHelper& helper,
1020 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap );
1021 void getVolumes( vector< const SMDS_MeshElement* > & volumes );
1022 void getBoundaryElems( vector< const SMDS_MeshElement* > & boundaryVolumes );
1023 void removeExcessSideDivision(const vector< Hexahedron* >& allHexa);
1024 void removeExcessNodes(vector< Hexahedron* >& allHexa);
1025 void preventVolumesOverlapping();
1026 TGeomID getAnyFace() const;
1027 void cutByExtendedInternal( std::vector< Hexahedron* >& hexes,
1028 const TColStd_MapOfInteger& intEdgeIDs );
1029 gp_Pnt mostDistantInternalPnt( int hexIndex, const gp_Pnt& p1, const gp_Pnt& p2 );
1030 bool isOutPoint( _Link& link, int iP, SMESH_MesherHelper& helper, const Solid* solid ) const;
1031 void sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID face);
1032 bool isInHole() const;
1033 bool hasStrangeEdge() const;
1034 bool checkPolyhedronSize( bool isCutByInternalFace, double & volSize ) const;
1039 bool debugDumpLink( _Link* link );
1040 _Node* findEqualNode( vector< _Node* >& nodes,
1041 const E_IntersectPoint* ip,
1044 for ( size_t i = 0; i < nodes.size(); ++i )
1045 if ( nodes[i]->EdgeIntPnt() == ip ||
1046 nodes[i]->Point().SquareDistance( ip->_point ) <= tol2 )
1050 bool isCorner( const _Node* node ) const { return ( node >= &_hexNodes[0] &&
1051 node - &_hexNodes[0] < 8 ); }
1052 bool hasEdgesAround( const ConcaveFace* cf ) const;
1053 bool isImplementEdges() const { return _grid->_edgeIntPool.nbElements(); }
1054 bool isOutParam(const double uvw[3]) const;
1056 typedef boost::container::flat_map< TGeomID, size_t > TID2Nb;
1057 static void insertAndIncrement( TGeomID id, TID2Nb& id2nbMap )
1059 TID2Nb::value_type s0( id, 0 );
1060 TID2Nb::iterator id2nb = id2nbMap.insert( s0 ).first;
1063 }; // class Hexahedron
1066 // --------------------------------------------------------------------------
1068 * \brief Hexahedron computing volumes in one thread
1070 struct ParallelHexahedron
1072 vector< Hexahedron* >& _hexVec;
1073 ParallelHexahedron( vector< Hexahedron* >& hv ): _hexVec(hv) {}
1074 void operator() ( const tbb::blocked_range<size_t>& r ) const
1076 for ( size_t i = r.begin(); i != r.end(); ++i )
1077 if ( Hexahedron* hex = _hexVec[ i ] )
1078 hex->computeElements();
1081 // --------------------------------------------------------------------------
1083 * \brief Structure intersecting certain nb of faces with GridLine's in one thread
1085 struct ParallelIntersector
1087 vector< FaceGridIntersector >& _faceVec;
1088 ParallelIntersector( vector< FaceGridIntersector >& faceVec): _faceVec(faceVec){}
1089 void operator() ( const tbb::blocked_range<size_t>& r ) const
1091 for ( size_t i = r.begin(); i != r.end(); ++i )
1092 _faceVec[i].Intersect();
1097 //=============================================================================
1098 // Implementation of internal utils
1099 //=============================================================================
1101 * \brief adjust \a i to have \a val between values[i] and values[i+1]
1103 inline void locateValue( int & i, double val, const vector<double>& values,
1104 int& di, double tol )
1106 //val += values[0]; // input \a val is measured from 0.
1107 if ( i > (int) values.size()-2 )
1108 i = values.size()-2;
1110 while ( i+2 < (int) values.size() && val > values[ i+1 ])
1112 while ( i > 0 && val < values[ i ])
1115 if ( i > 0 && val - values[ i ] < tol )
1117 else if ( i+2 < (int) values.size() && values[ i+1 ] - val < tol )
1122 //=============================================================================
1124 * Return a vector of SOLIDS sharing given shapes
1126 GeomIDVecHelder Geometry::GetSolidIDsByShapeID( const vector< TGeomID >& theShapeIDs ) const
1128 if ( theShapeIDs.size() == 1 )
1129 return GeomIDVecHelder( _solidIDsByShapeID[ theShapeIDs[ 0 ]], /*owner=*/false );
1131 // look for an empty slot in _solidIDsByShapeID
1132 vector< TGeomID > * resultIDs = 0;
1133 for ( const vector< TGeomID >& vec : _solidIDsByShapeID )
1136 resultIDs = const_cast< vector< TGeomID > * >( & vec );
1139 // fill in resultIDs
1140 for ( const TGeomID& id : theShapeIDs )
1141 for ( const TGeomID& solid : _solidIDsByShapeID[ id ])
1143 if ( std::find( resultIDs->begin(), resultIDs->end(), solid ) == resultIDs->end() )
1144 resultIDs->push_back( solid );
1146 return GeomIDVecHelder( *resultIDs, /*owner=*/true );
1148 //=============================================================================
1150 * Remove coincident intersection points
1152 void GridLine::RemoveExcessIntPoints( const double tol )
1154 if ( _intPoints.size() < 2 ) return;
1156 set< Transition > tranSet;
1157 multiset< F_IntersectPoint >::iterator ip1, ip2 = _intPoints.begin();
1158 while ( ip2 != _intPoints.end() )
1162 while ( ip2 != _intPoints.end() && ip2->_paramOnLine - ip1->_paramOnLine <= tol )
1164 tranSet.insert( ip1->_transition );
1165 tranSet.insert( ip2->_transition );
1166 ip2->Add( ip1->_faceIDs );
1167 _intPoints.erase( ip1 );
1170 if ( tranSet.size() > 1 ) // points with different transition coincide
1172 bool isIN = tranSet.count( Trans_IN );
1173 bool isOUT = tranSet.count( Trans_OUT );
1174 if ( isIN && isOUT )
1175 (*ip1)._transition = Trans_TANGENT;
1177 (*ip1)._transition = isIN ? Trans_IN : Trans_OUT;
1181 //================================================================================
1183 * Return ID of SOLID for nodes before the given intersection point
1185 TGeomID GridLine::GetSolidIDBefore( multiset< F_IntersectPoint >::iterator ip,
1186 const TGeomID prevID,
1187 const Geometry& geom )
1189 if ( ip == _intPoints.begin() )
1192 if ( geom.IsOneSolid() )
1195 switch ( ip->_transition ) {
1196 case Trans_IN: isOut = true; break;
1197 case Trans_OUT: isOut = false; break;
1198 case Trans_TANGENT: isOut = ( prevID != 0 ); break;
1201 // singularity point (apex of a cone)
1202 multiset< F_IntersectPoint >::iterator ipBef = ip, ipAft = ++ip;
1203 if ( ipAft == _intPoints.end() )
1208 if ( ipBef->_transition != ipAft->_transition )
1209 isOut = ( ipBef->_transition == Trans_OUT );
1211 isOut = ( ipBef->_transition != Trans_OUT );
1215 case Trans_INTERNAL: isOut = false;
1218 return isOut ? 0 : geom._soleSolid.ID();
1221 GeomIDVecHelder solids = geom.GetSolidIDsByShapeID( ip->_faceIDs );
1224 if ( ip->_transition == Trans_INTERNAL )
1227 GeomIDVecHelder solidsBef = geom.GetSolidIDsByShapeID( ip->_faceIDs );
1229 if ( ip->_transition == Trans_IN ||
1230 ip->_transition == Trans_OUT )
1232 if ( solidsBef.size() == 1 )
1234 if ( solidsBef[0] == prevID )
1235 return ip->_transition == Trans_OUT ? 0 : solidsBef[0];
1237 return solidsBef[0];
1240 if ( solids.size() == 2 )
1242 if ( solids == solidsBef )
1243 return solids.contain( prevID ) ? solids.otherThan( prevID ) : theUndefID; // bos #29212
1245 return solids.oneCommon( solidsBef );
1248 if ( solidsBef.size() == 1 )
1249 return solidsBef[0];
1251 return solids.oneCommon( solidsBef );
1253 //================================================================================
1257 bool B_IntersectPoint::Add( const vector< TGeomID >& fIDs,
1258 const SMDS_MeshNode* n) const
1260 size_t prevNbF = _faceIDs.size();
1262 if ( _faceIDs.empty() )
1265 for ( size_t i = 0; i < fIDs.size(); ++i )
1267 vector< TGeomID >::iterator it =
1268 std::find( _faceIDs.begin(), _faceIDs.end(), fIDs[i] );
1269 if ( it == _faceIDs.end() )
1270 _faceIDs.push_back( fIDs[i] );
1275 return prevNbF < _faceIDs.size();
1277 //================================================================================
1279 * Return ID of a common face if any, else zero
1281 TGeomID B_IntersectPoint::HasCommonFace( const B_IntersectPoint * other, TGeomID avoidFace ) const
1284 for ( size_t i = 0; i < other->_faceIDs.size(); ++i )
1285 if ( avoidFace != other->_faceIDs[i] &&
1286 IsOnFace ( other->_faceIDs[i] ))
1287 return other->_faceIDs[i];
1290 //================================================================================
1292 * Return faces common with other point
1294 size_t B_IntersectPoint::GetCommonFaces( const B_IntersectPoint * other, TGeomID* common ) const
1299 if ( _faceIDs.size() > other->_faceIDs.size() )
1300 return other->GetCommonFaces( this, common );
1301 for ( const TGeomID& face : _faceIDs )
1302 if ( other->IsOnFace( face ))
1303 common[ nbComm++ ] = face;
1306 //================================================================================
1308 * Return \c true if \a faceID in in this->_faceIDs
1310 bool B_IntersectPoint::IsOnFace( TGeomID faceID ) const // returns true if faceID is found
1312 vector< TGeomID >::const_iterator it =
1313 std::find( _faceIDs.begin(), _faceIDs.end(), faceID );
1314 return ( it != _faceIDs.end() );
1316 //================================================================================
1318 * OneOfSolids initialization
1320 void OneOfSolids::Init( const TopoDS_Shape& solid,
1321 TopAbs_ShapeEnum subType,
1322 const SMESHDS_Mesh* mesh )
1324 SetID( mesh->ShapeToIndex( solid ));
1326 if ( subType == TopAbs_FACE )
1327 SetHasInternalFaces( false );
1329 for ( TopExp_Explorer sub( solid, subType ); sub.More(); sub.Next() )
1331 _subIDs.Add( mesh->ShapeToIndex( sub.Current() ));
1332 if ( subType == TopAbs_FACE )
1334 _faces.Add( sub.Current() );
1335 if ( sub.Current().Orientation() == TopAbs_INTERNAL )
1336 SetHasInternalFaces( true );
1338 TGeomID faceID = mesh->ShapeToIndex( sub.Current() );
1339 if ( sub.Current().Orientation() == TopAbs_INTERNAL ||
1340 sub.Current().Orientation() == mesh->IndexToShape( faceID ).Orientation() )
1341 _outFaceIDs.Add( faceID );
1345 //================================================================================
1347 * Return an iterator on GridLine's in a given direction
1349 LineIndexer Grid::GetLineIndexer(size_t iDir) const
1351 const size_t indices[] = { 1,2,0, 0,2,1, 0,1,2 };
1352 const string s [] = { "X", "Y", "Z" };
1353 LineIndexer li( _coords[0].size(), _coords[1].size(), _coords[2].size(),
1354 indices[iDir*3], indices[iDir*3+1], indices[iDir*3+2],
1355 s[indices[iDir*3]], s[indices[iDir*3+1]], s[indices[iDir*3+2]]);
1358 //=============================================================================
1360 * Creates GridLine's of the grid
1362 void Grid::SetCoordinates(const vector<double>& xCoords,
1363 const vector<double>& yCoords,
1364 const vector<double>& zCoords,
1365 const double* axesDirs,
1366 const Bnd_Box& shapeBox)
1368 _coords[0] = xCoords;
1369 _coords[1] = yCoords;
1370 _coords[2] = zCoords;
1372 _axes[0].SetCoord( axesDirs[0],
1375 _axes[1].SetCoord( axesDirs[3],
1378 _axes[2].SetCoord( axesDirs[6],
1381 _axes[0].Normalize();
1382 _axes[1].Normalize();
1383 _axes[2].Normalize();
1385 _invB.SetCols( _axes[0], _axes[1], _axes[2] );
1388 // compute tolerance
1389 _minCellSize = Precision::Infinite();
1390 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1392 for ( size_t i = 1; i < _coords[ iDir ].size(); ++i )
1394 double cellLen = _coords[ iDir ][ i ] - _coords[ iDir ][ i-1 ];
1395 if ( cellLen < _minCellSize )
1396 _minCellSize = cellLen;
1399 if ( _minCellSize < Precision::Confusion() )
1400 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1401 SMESH_Comment("Too small cell size: ") << _minCellSize );
1402 _tol = _minCellSize / 1000.;
1404 // attune grid extremities to shape bounding box
1406 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
1407 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
1408 double* cP[6] = { &_coords[0].front(), &_coords[1].front(), &_coords[2].front(),
1409 &_coords[0].back(), &_coords[1].back(), &_coords[2].back() };
1410 for ( int i = 0; i < 6; ++i )
1411 if ( fabs( sP[i] - *cP[i] ) < _tol )
1412 *cP[i] = sP[i];// + _tol/1000. * ( i < 3 ? +1 : -1 );
1414 for ( int iDir = 0; iDir < 3; ++iDir )
1416 if ( _coords[iDir][0] - sP[iDir] > _tol )
1418 _minCellSize = Min( _minCellSize, _coords[iDir][0] - sP[iDir] );
1419 _coords[iDir].insert( _coords[iDir].begin(), sP[iDir] + _tol/1000.);
1421 if ( sP[iDir+3] - _coords[iDir].back() > _tol )
1423 _minCellSize = Min( _minCellSize, sP[iDir+3] - _coords[iDir].back() );
1424 _coords[iDir].push_back( sP[iDir+3] - _tol/1000.);
1427 _tol = _minCellSize / 1000.;
1429 _origin = ( _coords[0][0] * _axes[0] +
1430 _coords[1][0] * _axes[1] +
1431 _coords[2][0] * _axes[2] );
1434 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1436 LineIndexer li = GetLineIndexer( iDir );
1437 _lines[iDir].resize( li.NbLines() );
1438 double len = _coords[ iDir ].back() - _coords[iDir].front();
1439 for ( ; li.More(); ++li )
1441 GridLine& gl = _lines[iDir][ li.LineIndex() ];
1442 gl._line.SetLocation( _coords[0][li.I()] * _axes[0] +
1443 _coords[1][li.J()] * _axes[1] +
1444 _coords[2][li.K()] * _axes[2] );
1445 gl._line.SetDirection( _axes[ iDir ]);
1450 //================================================================================
1452 * Return local ID of shape
1454 TGeomID Grid::ShapeID( const TopoDS_Shape& s ) const
1456 return _helper->GetMeshDS()->ShapeToIndex( s );
1458 //================================================================================
1460 * Return a shape by its local ID
1462 const TopoDS_Shape& Grid::Shape( TGeomID id ) const
1464 return _helper->GetMeshDS()->IndexToShape( id );
1466 //================================================================================
1468 * Initialize _geometry
1470 void Grid::InitGeometry( const TopoDS_Shape& theShapeToMesh )
1472 SMESH_Mesh* mesh = _helper->GetMesh();
1474 _geometry._mainShape = theShapeToMesh;
1475 _geometry._extIntFaceID = mesh->GetMeshDS()->MaxShapeIndex() * 100;
1476 _geometry._soleSolid.SetID( 0 );
1477 _geometry._soleSolid.SetHasInternalFaces( false );
1479 InitClassifier( theShapeToMesh, TopAbs_VERTEX, _geometry._vertexClassifier );
1480 InitClassifier( theShapeToMesh, TopAbs_EDGE , _geometry._edgeClassifier );
1482 TopExp_Explorer solidExp( theShapeToMesh, TopAbs_SOLID );
1484 bool isSeveralSolids = false;
1485 if ( _toConsiderInternalFaces ) // check nb SOLIDs
1488 isSeveralSolids = solidExp.More();
1489 _toConsiderInternalFaces = isSeveralSolids;
1492 if ( !isSeveralSolids ) // look for an internal FACE
1494 TopExp_Explorer fExp( theShapeToMesh, TopAbs_FACE );
1495 for ( ; fExp.More() && !_toConsiderInternalFaces; fExp.Next() )
1496 _toConsiderInternalFaces = ( fExp.Current().Orientation() == TopAbs_INTERNAL );
1498 _geometry._soleSolid.SetHasInternalFaces( _toConsiderInternalFaces );
1499 _geometry._soleSolid.SetID( ShapeID( solidExp.Current() ));
1501 else // fill Geometry::_solidByID
1503 for ( ; solidExp.More(); solidExp.Next() )
1505 OneOfSolids & solid = _geometry._solidByID[ ShapeID( solidExp.Current() )];
1506 solid.Init( solidExp.Current(), TopAbs_FACE, mesh->GetMeshDS() );
1507 solid.Init( solidExp.Current(), TopAbs_EDGE, mesh->GetMeshDS() );
1508 solid.Init( solidExp.Current(), TopAbs_VERTEX, mesh->GetMeshDS() );
1514 _geometry._soleSolid.SetID( ShapeID( solidExp.Current() ));
1517 if ( !_toCreateFaces )
1519 int nbSolidsGlobal = _helper->Count( mesh->GetShapeToMesh(), TopAbs_SOLID, false );
1520 int nbSolidsLocal = _helper->Count( theShapeToMesh, TopAbs_SOLID, false );
1521 _toCreateFaces = ( nbSolidsLocal < nbSolidsGlobal );
1524 TopTools_IndexedMapOfShape faces;
1525 TopExp::MapShapes( theShapeToMesh, TopAbs_FACE, faces );
1527 // find boundary FACEs on boundary of mesh->ShapeToMesh()
1528 if ( _toCreateFaces )
1529 for ( int i = 1; i <= faces.Size(); ++i )
1530 if ( faces(i).Orientation() != TopAbs_INTERNAL &&
1531 _helper->NbAncestors( faces(i), *mesh, TopAbs_SOLID ) == 1 )
1533 _geometry._boundaryFaces.Add( ShapeID( faces(i) ));
1536 if ( isSeveralSolids )
1537 for ( int i = 1; i <= faces.Size(); ++i )
1539 SetSolidFather( faces(i), theShapeToMesh );
1540 for ( TopExp_Explorer eExp( faces(i), TopAbs_EDGE ); eExp.More(); eExp.Next() )
1542 const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
1543 SetSolidFather( edge, theShapeToMesh );
1544 SetSolidFather( _helper->IthVertex( 0, edge ), theShapeToMesh );
1545 SetSolidFather( _helper->IthVertex( 1, edge ), theShapeToMesh );
1549 // fill in _geometry._shape2NbNodes == find already meshed sub-shapes
1550 _geometry._shape2NbNodes.Clear();
1551 if ( mesh->NbNodes() > 0 )
1553 for ( TopAbs_ShapeEnum type : { TopAbs_FACE, TopAbs_EDGE, TopAbs_VERTEX })
1554 for ( TopExp_Explorer exp( theShapeToMesh, type ); exp.More(); exp.Next() )
1556 if ( _geometry._shape2NbNodes.IsBound( exp.Current() ))
1558 if ( SMESHDS_SubMesh* sm = mesh->GetMeshDS()->MeshElements( exp.Current() ))
1559 if ( sm->NbNodes() > 0 )
1560 _geometry._shape2NbNodes.Bind( exp.Current(), sm->NbNodes() );
1564 // fill in Solid::_concaveVertex
1565 vector< TGeomID > soleSolidID( 1, _geometry._soleSolid.ID() );
1566 for ( int i = 1; i <= faces.Size(); ++i )
1568 const TopoDS_Face& F = TopoDS::Face( faces( i ));
1570 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *mesh, 0, error,
1571 nullptr, nullptr, false );
1572 for ( StdMeshers_FaceSidePtr& wire : wires )
1574 const int nbEdges = wire->NbEdges();
1575 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wire->Edge(0)))
1577 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1579 if ( SMESH_Algo::isDegenerated( wire->Edge( iE1 ))) continue;
1580 int iE2 = ( iE1 + 1 ) % nbEdges;
1581 while ( SMESH_Algo::isDegenerated( wire->Edge( iE2 )))
1582 iE2 = ( iE2 + 1 ) % nbEdges;
1583 TopoDS_Vertex V = wire->FirstVertex( iE2 );
1584 double angle = _helper->GetAngle( wire->Edge( iE1 ),
1585 wire->Edge( iE2 ), F, V );
1586 if ( angle < -5. * M_PI / 180. )
1588 TGeomID faceID = ShapeID( F );
1589 const vector< TGeomID > & solids =
1590 _geometry.IsOneSolid() ? soleSolidID : GetSolidIDs( faceID );
1591 for ( const TGeomID & solidID : solids )
1593 Solid* solid = GetSolid( solidID );
1594 TGeomID V1 = ShapeID( wire->FirstVertex( iE1 ));
1595 TGeomID V2 = ShapeID( wire->LastVertex ( iE2 ));
1596 solid->SetConcave( ShapeID( V ), faceID,
1597 wire->EdgeID( iE1 ), wire->EdgeID( iE2 ), V1, V2 );
1606 //================================================================================
1608 * Store ID of SOLID as father of its child shape ID
1610 void Grid::SetSolidFather( const TopoDS_Shape& s, const TopoDS_Shape& theShapeToMesh )
1612 if ( _geometry._solidIDsByShapeID.empty() )
1613 _geometry._solidIDsByShapeID.resize( _helper->GetMeshDS()->MaxShapeIndex() + 1 );
1615 vector< TGeomID > & solidIDs = _geometry._solidIDsByShapeID[ ShapeID( s )];
1616 if ( !solidIDs.empty() )
1618 solidIDs.reserve(2);
1619 PShapeIteratorPtr solidIt = _helper->GetAncestors( s,
1620 *_helper->GetMesh(),
1623 while ( const TopoDS_Shape* solid = solidIt->next() )
1624 solidIDs.push_back( ShapeID( *solid ));
1626 //================================================================================
1628 * Return IDs of solids given sub-shape belongs to
1630 const vector< TGeomID > & Grid::GetSolidIDs( TGeomID subShapeID ) const
1632 return _geometry._solidIDsByShapeID[ subShapeID ];
1634 //================================================================================
1636 * Check if a sub-shape belongs to several SOLIDs
1638 bool Grid::IsShared( TGeomID shapeID ) const
1640 return !_geometry.IsOneSolid() && ( _geometry._solidIDsByShapeID[ shapeID ].size() > 1 );
1642 //================================================================================
1644 * Check if any of FACEs belongs to several SOLIDs
1646 bool Grid::IsAnyShared( const std::vector< TGeomID >& faceIDs ) const
1648 for ( size_t i = 0; i < faceIDs.size(); ++i )
1649 if ( IsShared( faceIDs[ i ]))
1653 //================================================================================
1655 * Return Solid by ID
1657 Solid* Grid::GetSolid( TGeomID solidID )
1659 if ( !solidID || _geometry.IsOneSolid() || _geometry._solidByID.empty() )
1660 return & _geometry._soleSolid;
1662 return & _geometry._solidByID[ solidID ];
1664 //================================================================================
1666 * Return OneOfSolids by ID
1668 Solid* Grid::GetOneOfSolids( TGeomID solidID )
1670 map< TGeomID, OneOfSolids >::iterator is2s = _geometry._solidByID.find( solidID );
1671 if ( is2s != _geometry._solidByID.end() )
1672 return & is2s->second;
1674 return & _geometry._soleSolid;
1676 //================================================================================
1678 * Check if transition on given FACE is correct for a given SOLID
1680 bool Grid::IsCorrectTransition( TGeomID faceID, const Solid* solid )
1682 if ( _geometry.IsOneSolid() )
1685 const vector< TGeomID >& solidIDs = _geometry._solidIDsByShapeID[ faceID ];
1686 return solidIDs[0] == solid->ID();
1689 //================================================================================
1691 * Assign to geometry a node at FACE intersection
1692 * Return a found supporting VERTEX
1694 void Grid::SetOnShape( const SMDS_MeshNode* n, const F_IntersectPoint& ip,
1695 TopoDS_Vertex* vertex, bool unset )
1698 SMESHDS_Mesh* mesh = _helper->GetMeshDS();
1699 if ( ip._faceIDs.size() == 1 )
1701 mesh->SetNodeOnFace( n, ip._faceIDs[0], ip._u, ip._v );
1703 else if ( _geometry._vertexClassifier.IsSatisfy( n, &s ))
1705 if ( unset ) mesh->UnSetNodeOnShape( n );
1706 mesh->SetNodeOnVertex( n, TopoDS::Vertex( s ));
1708 *vertex = TopoDS::Vertex( s );
1710 else if ( _geometry._edgeClassifier.IsSatisfy( n, &s ))
1712 if ( unset ) mesh->UnSetNodeOnShape( n );
1713 mesh->SetNodeOnEdge( n, TopoDS::Edge( s ));
1715 else if ( ip._faceIDs.size() > 0 )
1717 mesh->SetNodeOnFace( n, ip._faceIDs[0], ip._u, ip._v );
1719 else if ( !unset && _geometry.IsOneSolid() )
1721 mesh->SetNodeInVolume( n, _geometry._soleSolid.ID() );
1724 //================================================================================
1726 * Fill in B_IntersectPoint::_faceIDs with all FACEs sharing a VERTEX
1728 void Grid::UpdateFacesOfVertex( const B_IntersectPoint& ip, const TopoDS_Vertex& vertex )
1730 if ( vertex.IsNull() )
1732 std::vector< int > faceID(1);
1733 PShapeIteratorPtr fIt = _helper->GetAncestors( vertex, *_helper->GetMesh(),
1734 TopAbs_FACE, & _geometry._mainShape );
1735 while ( const TopoDS_Shape* face = fIt->next() )
1737 faceID[ 0 ] = ShapeID( *face );
1741 //================================================================================
1743 * Initialize a classifier
1745 void Grid::InitClassifier( const TopoDS_Shape& mainShape,
1746 TopAbs_ShapeEnum shapeType,
1747 Controls::ElementsOnShape& classifier )
1749 TopTools_IndexedMapOfShape shapes;
1750 TopExp::MapShapes( mainShape, shapeType, shapes );
1752 TopoDS_Compound compound; BRep_Builder builder;
1753 builder.MakeCompound( compound );
1754 for ( int i = 1; i <= shapes.Size(); ++i )
1755 builder.Add( compound, shapes(i) );
1757 classifier.SetMesh( _helper->GetMeshDS() );
1758 //classifier.SetTolerance( _tol ); // _tol is not initialised
1759 classifier.SetShape( compound, SMDSAbs_Node );
1762 //================================================================================
1764 * Return EDGEs with FACEs to implement into the mesh
1766 void Grid::GetEdgesToImplement( map< TGeomID, vector< TGeomID > > & edge2faceIDsMap,
1767 const TopoDS_Shape& shape,
1768 const vector< TopoDS_Shape >& faces )
1770 // check if there are strange EDGEs
1771 TopTools_IndexedMapOfShape faceMap;
1772 TopExp::MapShapes( _helper->GetMesh()->GetShapeToMesh(), TopAbs_FACE, faceMap );
1773 int nbFacesGlobal = faceMap.Size();
1774 faceMap.Clear( false );
1775 TopExp::MapShapes( shape, TopAbs_FACE, faceMap );
1776 int nbFacesLocal = faceMap.Size();
1777 bool hasStrangeEdges = ( nbFacesGlobal > nbFacesLocal );
1778 if ( !_toAddEdges && !hasStrangeEdges )
1779 return; // no FACEs in contact with those meshed by other algo
1781 for ( size_t i = 0; i < faces.size(); ++i )
1783 _helper->SetSubShape( faces[i] );
1784 for ( TopExp_Explorer eExp( faces[i], TopAbs_EDGE ); eExp.More(); eExp.Next() )
1786 const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
1787 if ( hasStrangeEdges )
1789 bool hasStrangeFace = false;
1790 PShapeIteratorPtr faceIt = _helper->GetAncestors( edge, *_helper->GetMesh(), TopAbs_FACE);
1791 while ( const TopoDS_Shape* face = faceIt->next() )
1792 if (( hasStrangeFace = !faceMap.Contains( *face )))
1794 if ( !hasStrangeFace && !_toAddEdges )
1796 _geometry._strangeEdges.Add( ShapeID( edge ));
1797 _geometry._strangeEdges.Add( ShapeID( _helper->IthVertex( 0, edge )));
1798 _geometry._strangeEdges.Add( ShapeID( _helper->IthVertex( 1, edge )));
1800 if ( !SMESH_Algo::isDegenerated( edge ) &&
1801 !_helper->IsRealSeam( edge ))
1803 edge2faceIDsMap[ ShapeID( edge )].push_back( ShapeID( faces[i] ));
1810 //================================================================================
1812 * Computes coordinates of a point in the grid CS
1814 void Grid::ComputeUVW(const gp_XYZ& P, double UVW[3])
1816 gp_XYZ p = P * _invB;
1817 p.Coord( UVW[0], UVW[1], UVW[2] );
1819 //================================================================================
1823 void Grid::ComputeNodes(SMESH_MesherHelper& helper)
1825 // state of each node of the grid relative to the geometry
1826 const size_t nbGridNodes = _coords[0].size() * _coords[1].size() * _coords[2].size();
1827 vector< TGeomID > shapeIDVec( nbGridNodes, theUndefID );
1828 _nodes.resize( nbGridNodes, 0 );
1829 _gridIntP.resize( nbGridNodes, NULL );
1831 SMESHDS_Mesh* mesh = helper.GetMeshDS();
1833 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1835 LineIndexer li = GetLineIndexer( iDir );
1837 // find out a shift of node index while walking along a GridLine in this direction
1838 li.SetIndexOnLine( 0 );
1839 size_t nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1840 li.SetIndexOnLine( 1 );
1841 const size_t nShift = NodeIndex( li.I(), li.J(), li.K() ) - nIndex0;
1843 const vector<double> & coords = _coords[ iDir ];
1844 for ( ; li.More(); ++li ) // loop on lines in iDir
1846 li.SetIndexOnLine( 0 );
1847 nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1849 GridLine& line = _lines[ iDir ][ li.LineIndex() ];
1850 const gp_XYZ lineLoc = line._line.Location().XYZ();
1851 const gp_XYZ lineDir = line._line.Direction().XYZ();
1853 line.RemoveExcessIntPoints( _tol );
1854 multiset< F_IntersectPoint >& intPnts = line._intPoints;
1855 multiset< F_IntersectPoint >::iterator ip = intPnts.begin();
1857 // Create mesh nodes at intersections with geometry
1858 // and set OUT state of nodes between intersections
1860 TGeomID solidID = 0;
1861 const double* nodeCoord = & coords[0];
1862 const double* coord0 = nodeCoord;
1863 const double* coordEnd = coord0 + coords.size();
1864 double nodeParam = 0;
1865 for ( ; ip != intPnts.end(); ++ip )
1867 solidID = line.GetSolidIDBefore( ip, solidID, _geometry );
1869 // set OUT state or just skip IN nodes before ip
1870 if ( nodeParam < ip->_paramOnLine - _tol )
1872 while ( nodeParam < ip->_paramOnLine - _tol )
1874 TGeomID & nodeShapeID = shapeIDVec[ nIndex0 + nShift * ( nodeCoord-coord0 ) ];
1875 nodeShapeID = Min( solidID, nodeShapeID );
1876 if ( ++nodeCoord < coordEnd )
1877 nodeParam = *nodeCoord - *coord0;
1881 if ( nodeCoord == coordEnd ) break;
1883 // create a mesh node on a GridLine at ip if it does not coincide with a grid node
1884 if ( nodeParam > ip->_paramOnLine + _tol )
1886 gp_XYZ xyz = lineLoc + ip->_paramOnLine * lineDir;
1887 ip->_node = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1888 ip->_indexOnLine = nodeCoord-coord0-1;
1890 SetOnShape( ip->_node, *ip, & v );
1891 UpdateFacesOfVertex( *ip, v );
1893 // create a mesh node at ip coincident with a grid node
1896 int nodeIndex = nIndex0 + nShift * ( nodeCoord-coord0 );
1897 if ( !_nodes[ nodeIndex ] )
1899 gp_XYZ xyz = lineLoc + nodeParam * lineDir;
1900 _nodes [ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1901 //_gridIntP[ nodeIndex ] = & * ip;
1902 //SetOnShape( _nodes[ nodeIndex ], *ip );
1904 if ( _gridIntP[ nodeIndex ] )
1905 _gridIntP[ nodeIndex ]->Add( ip->_faceIDs );
1907 _gridIntP[ nodeIndex ] = & * ip;
1908 // ip->_node = _nodes[ nodeIndex ]; -- to differ from ip on links
1909 ip->_indexOnLine = nodeCoord-coord0;
1910 if ( ++nodeCoord < coordEnd )
1911 nodeParam = *nodeCoord - *coord0;
1914 // set OUT state to nodes after the last ip
1915 for ( ; nodeCoord < coordEnd; ++nodeCoord )
1916 shapeIDVec[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = 0;
1920 // Create mesh nodes at !OUT nodes of the grid
1922 for ( size_t z = 0; z < _coords[2].size(); ++z )
1923 for ( size_t y = 0; y < _coords[1].size(); ++y )
1924 for ( size_t x = 0; x < _coords[0].size(); ++x )
1926 size_t nodeIndex = NodeIndex( x, y, z );
1927 if ( !_nodes[ nodeIndex ] &&
1928 0 < shapeIDVec[ nodeIndex ] && shapeIDVec[ nodeIndex ] < theUndefID )
1930 gp_XYZ xyz = ( _coords[0][x] * _axes[0] +
1931 _coords[1][y] * _axes[1] +
1932 _coords[2][z] * _axes[2] );
1933 _nodes[ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1934 mesh->SetNodeInVolume( _nodes[ nodeIndex ], shapeIDVec[ nodeIndex ]);
1936 else if ( _nodes[ nodeIndex ] && _gridIntP[ nodeIndex ] /*&&
1937 !_nodes[ nodeIndex]->GetShapeID()*/ )
1940 SetOnShape( _nodes[ nodeIndex ], *_gridIntP[ nodeIndex ], & v );
1941 UpdateFacesOfVertex( *_gridIntP[ nodeIndex ], v );
1946 // check validity of transitions
1947 const char* trName[] = { "TANGENT", "IN", "OUT", "APEX" };
1948 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1950 LineIndexer li = GetLineIndexer( iDir );
1951 for ( ; li.More(); ++li )
1953 multiset< F_IntersectPoint >& intPnts = _lines[ iDir ][ li.LineIndex() ]._intPoints;
1954 if ( intPnts.empty() ) continue;
1955 if ( intPnts.size() == 1 )
1957 if ( intPnts.begin()->_transition != Trans_TANGENT &&
1958 intPnts.begin()->_transition != Trans_APEX )
1959 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1960 SMESH_Comment("Wrong SOLE transition of GridLine (")
1961 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1962 << ") along " << li._nameConst
1963 << ": " << trName[ intPnts.begin()->_transition] );
1967 if ( intPnts.begin()->_transition == Trans_OUT )
1968 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1969 SMESH_Comment("Wrong START transition of GridLine (")
1970 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1971 << ") along " << li._nameConst
1972 << ": " << trName[ intPnts.begin()->_transition ]);
1973 if ( intPnts.rbegin()->_transition == Trans_IN )
1974 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1975 SMESH_Comment("Wrong END transition of GridLine (")
1976 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1977 << ") along " << li._nameConst
1978 << ": " << trName[ intPnts.rbegin()->_transition ]);
1985 //=============================================================================
1987 * Intersects TopoDS_Face with all GridLine's
1989 void FaceGridIntersector::Intersect()
1991 FaceLineIntersector intersector;
1992 intersector._surfaceInt = GetCurveFaceIntersector();
1993 intersector._tol = _grid->_tol;
1994 intersector._transOut = _face.Orientation() == TopAbs_REVERSED ? Trans_IN : Trans_OUT;
1995 intersector._transIn = _face.Orientation() == TopAbs_REVERSED ? Trans_OUT : Trans_IN;
1997 typedef void (FaceLineIntersector::* PIntFun )(const GridLine& gridLine);
1998 PIntFun interFunction;
2000 bool isDirect = true;
2001 BRepAdaptor_Surface surf( _face );
2002 switch ( surf.GetType() ) {
2004 intersector._plane = surf.Plane();
2005 interFunction = &FaceLineIntersector::IntersectWithPlane;
2006 isDirect = intersector._plane.Direct();
2008 case GeomAbs_Cylinder:
2009 intersector._cylinder = surf.Cylinder();
2010 interFunction = &FaceLineIntersector::IntersectWithCylinder;
2011 isDirect = intersector._cylinder.Direct();
2014 intersector._cone = surf.Cone();
2015 interFunction = &FaceLineIntersector::IntersectWithCone;
2016 //isDirect = intersector._cone.Direct();
2018 case GeomAbs_Sphere:
2019 intersector._sphere = surf.Sphere();
2020 interFunction = &FaceLineIntersector::IntersectWithSphere;
2021 isDirect = intersector._sphere.Direct();
2024 intersector._torus = surf.Torus();
2025 interFunction = &FaceLineIntersector::IntersectWithTorus;
2026 //isDirect = intersector._torus.Direct();
2029 interFunction = &FaceLineIntersector::IntersectWithSurface;
2032 std::swap( intersector._transOut, intersector._transIn );
2034 _intersections.clear();
2035 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
2037 if ( surf.GetType() == GeomAbs_Plane )
2039 // check if all lines in this direction are parallel to a plane
2040 if ( intersector._plane.Axis().IsNormal( _grid->_lines[iDir][0]._line.Position(),
2041 Precision::Angular()))
2043 // find out a transition, that is the same for all lines of a direction
2044 gp_Dir plnNorm = intersector._plane.Axis().Direction();
2045 gp_Dir lineDir = _grid->_lines[iDir][0]._line.Direction();
2046 intersector._transition =
2047 ( plnNorm * lineDir < 0 ) ? intersector._transIn : intersector._transOut;
2049 if ( surf.GetType() == GeomAbs_Cylinder )
2051 // check if all lines in this direction are parallel to a cylinder
2052 if ( intersector._cylinder.Axis().IsParallel( _grid->_lines[iDir][0]._line.Position(),
2053 Precision::Angular()))
2057 // intersect the grid lines with the face
2058 for ( size_t iL = 0; iL < _grid->_lines[iDir].size(); ++iL )
2060 GridLine& gridLine = _grid->_lines[iDir][iL];
2061 if ( _bndBox.IsOut( gridLine._line )) continue;
2063 intersector._intPoints.clear();
2064 (intersector.*interFunction)( gridLine ); // <- intersection with gridLine
2065 for ( size_t i = 0; i < intersector._intPoints.size(); ++i )
2066 _intersections.push_back( make_pair( &gridLine, intersector._intPoints[i] ));
2070 if ( _face.Orientation() == TopAbs_INTERNAL )
2072 for ( size_t i = 0; i < _intersections.size(); ++i )
2073 if ( _intersections[i].second._transition == Trans_IN ||
2074 _intersections[i].second._transition == Trans_OUT )
2076 _intersections[i].second._transition = Trans_INTERNAL;
2081 //================================================================================
2083 * Return true if (_u,_v) is on the face
2085 bool FaceLineIntersector::UVIsOnFace() const
2087 TopAbs_State state = _surfaceInt->ClassifyUVPoint(gp_Pnt2d( _u,_v ));
2088 return ( state == TopAbs_IN || state == TopAbs_ON );
2090 //================================================================================
2092 * Store an intersection if it is IN or ON the face
2094 void FaceLineIntersector::addIntPoint(const bool toClassify)
2096 if ( !toClassify || UVIsOnFace() )
2099 p._paramOnLine = _w;
2102 p._transition = _transition;
2103 _intPoints.push_back( p );
2106 //================================================================================
2108 * Intersect a line with a plane
2110 void FaceLineIntersector::IntersectWithPlane(const GridLine& gridLine)
2112 IntAna_IntConicQuad linPlane( gridLine._line, _plane, Precision::Angular());
2113 _w = linPlane.ParamOnConic(1);
2114 if ( isParamOnLineOK( gridLine._length ))
2116 ElSLib::Parameters(_plane, linPlane.Point(1) ,_u,_v);
2120 //================================================================================
2122 * Intersect a line with a cylinder
2124 void FaceLineIntersector::IntersectWithCylinder(const GridLine& gridLine)
2126 IntAna_IntConicQuad linCylinder( gridLine._line, _cylinder );
2127 if ( linCylinder.IsDone() && linCylinder.NbPoints() > 0 )
2129 _w = linCylinder.ParamOnConic(1);
2130 if ( linCylinder.NbPoints() == 1 )
2131 _transition = Trans_TANGENT;
2133 _transition = _w < linCylinder.ParamOnConic(2) ? _transIn : _transOut;
2134 if ( isParamOnLineOK( gridLine._length ))
2136 ElSLib::Parameters(_cylinder, linCylinder.Point(1) ,_u,_v);
2139 if ( linCylinder.NbPoints() > 1 )
2141 _w = linCylinder.ParamOnConic(2);
2142 if ( isParamOnLineOK( gridLine._length ))
2144 ElSLib::Parameters(_cylinder, linCylinder.Point(2) ,_u,_v);
2145 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
2151 //================================================================================
2153 * Intersect a line with a cone
2155 void FaceLineIntersector::IntersectWithCone (const GridLine& gridLine)
2157 IntAna_IntConicQuad linCone(gridLine._line,_cone);
2158 if ( !linCone.IsDone() ) return;
2160 gp_Vec du, dv, norm;
2161 for ( int i = 1; i <= linCone.NbPoints(); ++i )
2163 _w = linCone.ParamOnConic( i );
2164 if ( !isParamOnLineOK( gridLine._length )) continue;
2165 ElSLib::Parameters(_cone, linCone.Point(i) ,_u,_v);
2168 ElSLib::D1( _u, _v, _cone, P, du, dv );
2170 double normSize2 = norm.SquareMagnitude();
2171 if ( normSize2 > Precision::Angular() * Precision::Angular() )
2173 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
2174 cos /= sqrt( normSize2 );
2175 if ( cos < -Precision::Angular() )
2176 _transition = _transIn;
2177 else if ( cos > Precision::Angular() )
2178 _transition = _transOut;
2180 _transition = Trans_TANGENT;
2184 _transition = Trans_APEX;
2186 addIntPoint( /*toClassify=*/false);
2190 //================================================================================
2192 * Intersect a line with a sphere
2194 void FaceLineIntersector::IntersectWithSphere (const GridLine& gridLine)
2196 IntAna_IntConicQuad linSphere(gridLine._line,_sphere);
2197 if ( linSphere.IsDone() && linSphere.NbPoints() > 0 )
2199 _w = linSphere.ParamOnConic(1);
2200 if ( linSphere.NbPoints() == 1 )
2201 _transition = Trans_TANGENT;
2203 _transition = _w < linSphere.ParamOnConic(2) ? _transIn : _transOut;
2204 if ( isParamOnLineOK( gridLine._length ))
2206 ElSLib::Parameters(_sphere, linSphere.Point(1) ,_u,_v);
2209 if ( linSphere.NbPoints() > 1 )
2211 _w = linSphere.ParamOnConic(2);
2212 if ( isParamOnLineOK( gridLine._length ))
2214 ElSLib::Parameters(_sphere, linSphere.Point(2) ,_u,_v);
2215 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
2221 //================================================================================
2223 * Intersect a line with a torus
2225 void FaceLineIntersector::IntersectWithTorus (const GridLine& gridLine)
2227 IntAna_IntLinTorus linTorus(gridLine._line,_torus);
2228 if ( !linTorus.IsDone()) return;
2230 gp_Vec du, dv, norm;
2231 for ( int i = 1; i <= linTorus.NbPoints(); ++i )
2233 _w = linTorus.ParamOnLine( i );
2234 if ( !isParamOnLineOK( gridLine._length )) continue;
2235 linTorus.ParamOnTorus( i, _u,_v );
2238 ElSLib::D1( _u, _v, _torus, P, du, dv );
2240 double normSize = norm.Magnitude();
2241 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
2243 if ( cos < -Precision::Angular() )
2244 _transition = _transIn;
2245 else if ( cos > Precision::Angular() )
2246 _transition = _transOut;
2248 _transition = Trans_TANGENT;
2249 addIntPoint( /*toClassify=*/false);
2253 //================================================================================
2255 * Intersect a line with a non-analytical surface
2257 void FaceLineIntersector::IntersectWithSurface (const GridLine& gridLine)
2259 _surfaceInt->Perform( gridLine._line, 0.0, gridLine._length );
2260 if ( !_surfaceInt->IsDone() ) return;
2261 for ( int i = 1; i <= _surfaceInt->NbPnt(); ++i )
2263 _transition = Transition( _surfaceInt->Transition( i ) );
2264 _w = _surfaceInt->WParameter( i );
2265 addIntPoint(/*toClassify=*/false);
2268 //================================================================================
2270 * check if its face can be safely intersected in a thread
2272 bool FaceGridIntersector::IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const
2277 TopLoc_Location loc;
2278 Handle(Geom_Surface) surf = BRep_Tool::Surface( _face, loc );
2279 Handle(Geom_RectangularTrimmedSurface) ts =
2280 Handle(Geom_RectangularTrimmedSurface)::DownCast( surf );
2281 while( !ts.IsNull() ) {
2282 surf = ts->BasisSurface();
2283 ts = Handle(Geom_RectangularTrimmedSurface)::DownCast(surf);
2285 if ( surf->IsKind( STANDARD_TYPE(Geom_BSplineSurface )) ||
2286 surf->IsKind( STANDARD_TYPE(Geom_BezierSurface )))
2287 if ( !noSafeTShapes.insert( _face.TShape().get() ).second )
2291 TopExp_Explorer exp( _face, TopAbs_EDGE );
2292 for ( ; exp.More(); exp.Next() )
2294 bool edgeIsSafe = true;
2295 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
2298 Handle(Geom_Curve) c = BRep_Tool::Curve( e, loc, f, l);
2301 Handle(Geom_TrimmedCurve) tc = Handle(Geom_TrimmedCurve)::DownCast(c);
2302 while( !tc.IsNull() ) {
2303 c = tc->BasisCurve();
2304 tc = Handle(Geom_TrimmedCurve)::DownCast(c);
2306 if ( c->IsKind( STANDARD_TYPE(Geom_BSplineCurve )) ||
2307 c->IsKind( STANDARD_TYPE(Geom_BezierCurve )))
2314 Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( e, surf, loc, f, l);
2317 Handle(Geom2d_TrimmedCurve) tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
2318 while( !tc.IsNull() ) {
2319 c2 = tc->BasisCurve();
2320 tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
2322 if ( c2->IsKind( STANDARD_TYPE(Geom2d_BSplineCurve )) ||
2323 c2->IsKind( STANDARD_TYPE(Geom2d_BezierCurve )))
2327 if ( !edgeIsSafe && !noSafeTShapes.insert( e.TShape().get() ).second )
2332 //================================================================================
2334 * \brief Creates topology of the hexahedron
2336 Hexahedron::Hexahedron(Grid* grid)
2337 : _grid( grid ), _nbFaceIntNodes(0), _hasTooSmall( false )
2339 _polygons.reserve(100); // to avoid reallocation;
2341 //set nodes shift within grid->_nodes from the node 000
2342 size_t dx = _grid->NodeIndexDX();
2343 size_t dy = _grid->NodeIndexDY();
2344 size_t dz = _grid->NodeIndexDZ();
2346 size_t i100 = i000 + dx;
2347 size_t i010 = i000 + dy;
2348 size_t i110 = i010 + dx;
2349 size_t i001 = i000 + dz;
2350 size_t i101 = i100 + dz;
2351 size_t i011 = i010 + dz;
2352 size_t i111 = i110 + dz;
2353 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V000 )] = i000;
2354 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V100 )] = i100;
2355 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V010 )] = i010;
2356 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V110 )] = i110;
2357 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V001 )] = i001;
2358 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V101 )] = i101;
2359 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V011 )] = i011;
2360 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V111 )] = i111;
2362 vector< int > idVec;
2363 // set nodes to links
2364 for ( int linkID = SMESH_Block::ID_Ex00; linkID <= SMESH_Block::ID_E11z; ++linkID )
2366 SMESH_Block::GetEdgeVertexIDs( linkID, idVec );
2367 _Link& link = _hexLinks[ SMESH_Block::ShapeIndex( linkID )];
2368 link._nodes[0] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[0] )];
2369 link._nodes[1] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[1] )];
2372 // set links to faces
2373 int interlace[4] = { 0, 3, 1, 2 }; // to walk by links around a face: { u0, 1v, u1, 0v }
2374 for ( int faceID = SMESH_Block::ID_Fxy0; faceID <= SMESH_Block::ID_F1yz; ++faceID )
2376 _Face& quad = _hexQuads[ SMESH_Block::ShapeIndex( faceID )];
2377 quad._name = (SMESH_Block::TShapeID) faceID;
2379 SMESH_Block::GetFaceEdgesIDs( faceID, idVec );
2380 bool revFace = ( faceID == SMESH_Block::ID_Fxy0 ||
2381 faceID == SMESH_Block::ID_Fx1z ||
2382 faceID == SMESH_Block::ID_F0yz );
2383 quad._links.resize(4);
2384 vector<_OrientedLink>::iterator frwLinkIt = quad._links.begin();
2385 vector<_OrientedLink>::reverse_iterator revLinkIt = quad._links.rbegin();
2386 for ( int i = 0; i < 4; ++i )
2388 bool revLink = revFace;
2389 if ( i > 1 ) // reverse links u1 and v0
2391 _OrientedLink& link = revFace ? *revLinkIt++ : *frwLinkIt++;
2392 link = _OrientedLink( & _hexLinks[ SMESH_Block::ShapeIndex( idVec[interlace[i]] )],
2397 //================================================================================
2399 * \brief Copy constructor
2401 Hexahedron::Hexahedron( const Hexahedron& other, size_t i, size_t j, size_t k, int cellID )
2402 :_grid( other._grid ), _nbFaceIntNodes(0), _i( i ), _j( j ), _k( k ), _hasTooSmall( false )
2404 _polygons.reserve(100); // to avoid reallocation;
2407 for ( int i = 0; i < 12; ++i )
2409 const _Link& srcLink = other._hexLinks[ i ];
2410 _Link& tgtLink = this->_hexLinks[ i ];
2411 tgtLink._nodes[0] = _hexNodes + ( srcLink._nodes[0] - other._hexNodes );
2412 tgtLink._nodes[1] = _hexNodes + ( srcLink._nodes[1] - other._hexNodes );
2415 for ( int i = 0; i < 6; ++i )
2417 const _Face& srcQuad = other._hexQuads[ i ];
2418 _Face& tgtQuad = this->_hexQuads[ i ];
2419 tgtQuad._name = srcQuad._name;
2420 tgtQuad._links.resize(4);
2421 for ( int j = 0; j < 4; ++j )
2423 const _OrientedLink& srcLink = srcQuad._links[ j ];
2424 _OrientedLink& tgtLink = tgtQuad._links[ j ];
2425 tgtLink._reverse = srcLink._reverse;
2426 tgtLink._link = _hexLinks + ( srcLink._link - other._hexLinks );
2430 if (SALOME::VerbosityActivated())
2434 //================================================================================
2436 * \brief Return IDs of SOLIDs interfering with this Hexahedron
2438 size_t Hexahedron::getSolids( TGeomID ids[] )
2440 if ( _grid->_geometry.IsOneSolid() )
2442 ids[0] = _grid->GetSolid()->ID();
2445 // count intersection points belonging to each SOLID
2447 id2NbPoints.reserve( 3 );
2449 _origNodeInd = _grid->NodeIndex( _i,_j,_k );
2450 for ( int iN = 0; iN < 8; ++iN )
2452 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
2453 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
2455 if ( _hexNodes[iN]._intPoint ) // intersection with a FACE
2457 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2459 const vector< TGeomID > & solidIDs =
2460 _grid->GetSolidIDs( _hexNodes[iN]._intPoint->_faceIDs[iF] );
2461 for ( size_t i = 0; i < solidIDs.size(); ++i )
2462 insertAndIncrement( solidIDs[i], id2NbPoints );
2465 else if ( _hexNodes[iN]._node ) // node inside a SOLID
2467 insertAndIncrement( _hexNodes[iN]._node->GetShapeID(), id2NbPoints );
2471 for ( int iL = 0; iL < 12; ++iL )
2473 const _Link& link = _hexLinks[ iL ];
2474 for ( size_t iP = 0; iP < link._fIntPoints.size(); ++iP )
2476 for ( size_t iF = 0; iF < link._fIntPoints[iP]->_faceIDs.size(); ++iF )
2478 const vector< TGeomID > & solidIDs =
2479 _grid->GetSolidIDs( link._fIntPoints[iP]->_faceIDs[iF] );
2480 for ( size_t i = 0; i < solidIDs.size(); ++i )
2481 insertAndIncrement( solidIDs[i], id2NbPoints );
2486 for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
2488 const vector< TGeomID > & solidIDs = _grid->GetSolidIDs( _eIntPoints[iP]->_shapeID );
2489 for ( size_t i = 0; i < solidIDs.size(); ++i )
2490 insertAndIncrement( solidIDs[i], id2NbPoints );
2493 size_t nbSolids = 0;
2494 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2495 if ( id2nb->second >= 3 )
2496 ids[ nbSolids++ ] = id2nb->first;
2501 //================================================================================
2503 * \brief Count cuts by INTERNAL FACEs and set _Node::_isInternalFlags
2505 bool Hexahedron::isCutByInternalFace( IsInternalFlag & maxFlag )
2508 id2NbPoints.reserve( 3 );
2510 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2511 for ( size_t iF = 0; iF < _intNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2513 if ( _grid->IsInternal( _intNodes[iN]._intPoint->_faceIDs[iF]))
2514 insertAndIncrement( _intNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2516 for ( size_t iN = 0; iN < 8; ++iN )
2517 if ( _hexNodes[iN]._intPoint )
2518 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2520 if ( _grid->IsInternal( _hexNodes[iN]._intPoint->_faceIDs[iF]))
2521 insertAndIncrement( _hexNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2524 maxFlag = IS_NOT_INTERNAL;
2525 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2527 TGeomID intFace = id2nb->first;
2528 IsInternalFlag intFlag = ( id2nb->second >= 3 ? IS_CUT_BY_INTERNAL_FACE : IS_INTERNAL );
2529 if ( intFlag > maxFlag )
2532 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2533 if ( _intNodes[iN].IsOnFace( intFace ))
2534 _intNodes[iN].SetInternal( intFlag );
2536 for ( size_t iN = 0; iN < 8; ++iN )
2537 if ( _hexNodes[iN].IsOnFace( intFace ))
2538 _hexNodes[iN].SetInternal( intFlag );
2544 //================================================================================
2546 * \brief Return any FACE interfering with this Hexahedron
2548 TGeomID Hexahedron::getAnyFace() const
2551 id2NbPoints.reserve( 3 );
2553 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2554 for ( size_t iF = 0; iF < _intNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2555 insertAndIncrement( _intNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2557 for ( size_t iN = 0; iN < 8; ++iN )
2558 if ( _hexNodes[iN]._intPoint )
2559 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2560 insertAndIncrement( _hexNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2562 for ( unsigned int minNb = 3; minNb > 0; --minNb )
2563 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2564 if ( id2nb->second >= minNb )
2565 return id2nb->first;
2570 //================================================================================
2572 * \brief Initializes IJK by Hexahedron index
2574 void Hexahedron::setIJK( size_t iCell )
2576 size_t iNbCell = _grid->_coords[0].size() - 1;
2577 size_t jNbCell = _grid->_coords[1].size() - 1;
2578 _i = iCell % iNbCell;
2579 _j = ( iCell % ( iNbCell * jNbCell )) / iNbCell;
2580 _k = iCell / iNbCell / jNbCell;
2583 //================================================================================
2585 * \brief Initializes its data by given grid cell (countered from zero)
2587 void Hexahedron::init( size_t iCell )
2593 //================================================================================
2595 * \brief Initializes its data by given grid cell nodes and intersections
2597 void Hexahedron::init( size_t i, size_t j, size_t k, const Solid* solid )
2599 _i = i; _j = j; _k = k;
2601 bool isCompute = solid;
2603 solid = _grid->GetSolid();
2605 // set nodes of grid to nodes of the hexahedron and
2606 // count nodes at hexahedron corners located IN and ON geometry
2607 _nbCornerNodes = _nbBndNodes = 0;
2608 _origNodeInd = _grid->NodeIndex( i,j,k );
2609 for ( int iN = 0; iN < 8; ++iN )
2611 _hexNodes[iN]._isInternalFlags = 0;
2613 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
2614 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
2616 if ( _hexNodes[iN]._node && !solid->Contains( _hexNodes[iN]._node->GetShapeID() ))
2617 _hexNodes[iN]._node = 0;
2618 if ( _hexNodes[iN]._intPoint && !solid->ContainsAny( _hexNodes[iN]._intPoint->_faceIDs ))
2619 _hexNodes[iN]._intPoint = 0;
2621 _nbCornerNodes += bool( _hexNodes[iN]._node );
2622 _nbBndNodes += bool( _hexNodes[iN]._intPoint );
2624 _sideLength[0] = _grid->_coords[0][i+1] - _grid->_coords[0][i];
2625 _sideLength[1] = _grid->_coords[1][j+1] - _grid->_coords[1][j];
2626 _sideLength[2] = _grid->_coords[2][k+1] - _grid->_coords[2][k];
2634 if ( _nbFaceIntNodes + _eIntPoints.size() > 0 &&
2635 _nbFaceIntNodes + _eIntPoints.size() + _nbCornerNodes > 3)
2637 _intNodes.reserve( 3 * _nbBndNodes + _nbFaceIntNodes + _eIntPoints.size() );
2639 // this method can be called in parallel, so use own helper
2640 SMESH_MesherHelper helper( *_grid->_helper->GetMesh() );
2642 // Create sub-links (_Link::_splits) by splitting links with _Link::_fIntPoints
2643 // ---------------------------------------------------------------
2645 for ( int iLink = 0; iLink < 12; ++iLink )
2647 _Link& link = _hexLinks[ iLink ];
2648 link._fIntNodes.clear();
2649 link._fIntNodes.reserve( link._fIntPoints.size() );
2650 for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
2651 if ( solid->ContainsAny( link._fIntPoints[i]->_faceIDs ))
2653 _intNodes.push_back( _Node( 0, link._fIntPoints[i] ));
2654 link._fIntNodes.push_back( & _intNodes.back() );
2657 link._splits.clear();
2658 split._nodes[ 0 ] = link._nodes[0];
2659 bool isOut = ( ! link._nodes[0]->Node() );
2660 bool checkTransition;
2661 for ( size_t i = 0; i < link._fIntNodes.size(); ++i )
2663 const bool isGridNode = ( ! link._fIntNodes[i]->Node() );
2664 if ( !isGridNode ) // intersection non-coincident with a grid node
2666 if ( split._nodes[ 0 ]->Node() && !isOut )
2668 split._nodes[ 1 ] = link._fIntNodes[i];
2669 link._splits.push_back( split );
2671 split._nodes[ 0 ] = link._fIntNodes[i];
2672 checkTransition = true;
2674 else // FACE intersection coincident with a grid node (at link ends)
2676 checkTransition = ( i == 0 && link._nodes[0]->Node() );
2678 if ( checkTransition )
2680 const vector< TGeomID >& faceIDs = link._fIntNodes[i]->_intPoint->_faceIDs;
2681 if ( _grid->IsInternal( faceIDs.back() ))
2683 else if ( faceIDs.size() > 1 || _eIntPoints.size() > 0 )
2684 isOut = isOutPoint( link, i, helper, solid );
2687 bool okTransi = _grid->IsCorrectTransition( faceIDs[0], solid );
2688 switch ( link._fIntNodes[i]->FaceIntPnt()->_transition ) {
2689 case Trans_OUT: isOut = okTransi; break;
2690 case Trans_IN : isOut = !okTransi; break;
2692 isOut = isOutPoint( link, i, helper, solid );
2697 if ( link._nodes[ 1 ]->Node() && split._nodes[ 0 ]->Node() && !isOut )
2699 split._nodes[ 1 ] = link._nodes[1];
2700 link._splits.push_back( split );
2704 // Create _Node's at intersections with EDGEs.
2705 // --------------------------------------------
2706 // 1) add this->_eIntPoints to _Face::_eIntNodes
2707 // 2) fill _intNodes and _vIntNodes
2709 const double tol2 = _grid->_tol * _grid->_tol;
2710 int facets[3], nbFacets, subEntity;
2712 for ( int iF = 0; iF < 6; ++iF )
2713 _hexQuads[ iF ]._eIntNodes.clear();
2715 for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
2717 if ( !solid->ContainsAny( _eIntPoints[iP]->_faceIDs ))
2719 nbFacets = getEntity( _eIntPoints[iP], facets, subEntity );
2720 _Node* equalNode = 0;
2721 switch( nbFacets ) {
2722 case 1: // in a _Face
2724 _Face& quad = _hexQuads[ facets[0] - SMESH_Block::ID_FirstF ];
2725 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2727 equalNode->Add( _eIntPoints[ iP ] );
2730 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2731 quad._eIntNodes.push_back( & _intNodes.back() );
2735 case 2: // on a _Link
2737 _Link& link = _hexLinks[ subEntity - SMESH_Block::ID_FirstE ];
2738 if ( link._splits.size() > 0 )
2740 equalNode = findEqualNode( link._fIntNodes, _eIntPoints[ iP ], tol2 );
2742 equalNode->Add( _eIntPoints[ iP ] );
2743 else if ( link._splits.size() == 1 &&
2744 link._splits[0]._nodes[0] &&
2745 link._splits[0]._nodes[1] )
2746 link._splits.clear(); // hex edge is divided by _eIntPoints[iP]
2751 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2752 bool newNodeUsed = false;
2753 for ( int iF = 0; iF < 2; ++iF )
2755 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
2756 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2758 equalNode->Add( _eIntPoints[ iP ] );
2761 quad._eIntNodes.push_back( & _intNodes.back() );
2766 _intNodes.pop_back();
2770 case 3: // at a corner
2772 _Node& node = _hexNodes[ subEntity - SMESH_Block::ID_FirstV ];
2775 if ( node._intPoint )
2776 node._intPoint->Add( _eIntPoints[ iP ]->_faceIDs, _eIntPoints[ iP ]->_node );
2780 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2781 for ( int iF = 0; iF < 3; ++iF )
2783 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
2784 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2786 equalNode->Add( _eIntPoints[ iP ] );
2789 quad._eIntNodes.push_back( & _intNodes.back() );
2795 } // switch( nbFacets )
2797 if ( nbFacets == 0 ||
2798 _grid->ShapeType( _eIntPoints[ iP ]->_shapeID ) == TopAbs_VERTEX )
2800 equalNode = findEqualNode( _vIntNodes, _eIntPoints[ iP ], tol2 );
2802 equalNode->Add( _eIntPoints[ iP ] );
2804 else if ( nbFacets == 0 ) {
2805 if ( _intNodes.empty() || _intNodes.back().EdgeIntPnt() != _eIntPoints[ iP ])
2806 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2807 _vIntNodes.push_back( & _intNodes.back() );
2810 } // loop on _eIntPoints
2813 else if (( 3 < _nbCornerNodes && _nbCornerNodes < 8 ) || // _nbFaceIntNodes == 0
2814 ( !_grid->_geometry.IsOneSolid() ))
2817 // create sub-links (_splits) of whole links
2818 for ( int iLink = 0; iLink < 12; ++iLink )
2820 _Link& link = _hexLinks[ iLink ];
2821 link._splits.clear();
2822 if ( link._nodes[ 0 ]->Node() && link._nodes[ 1 ]->Node() )
2824 split._nodes[ 0 ] = link._nodes[0];
2825 split._nodes[ 1 ] = link._nodes[1];
2826 link._splits.push_back( split );
2832 } // init( _i, _j, _k )
2834 //================================================================================
2836 * \brief Compute mesh volumes resulted from intersection of the Hexahedron
2838 void Hexahedron::computeElements( const Solid* solid, int solidIndex )
2842 solid = _grid->GetSolid();
2843 if ( !_grid->_geometry.IsOneSolid() )
2845 TGeomID solidIDs[20] = { 0 };
2846 size_t nbSolids = getSolids( solidIDs );
2849 for ( size_t i = 0; i < nbSolids; ++i )
2851 solid = _grid->GetSolid( solidIDs[i] );
2852 computeElements( solid, i );
2853 if ( !_volumeDefs._nodes.empty() && i < nbSolids - 1 )
2854 _volumeDefs.SetNext( new _volumeDef( _volumeDefs ));
2858 solid = _grid->GetSolid( solidIDs[0] );
2862 init( _i, _j, _k, solid ); // get nodes and intersections from grid nodes and split links
2864 int nbIntersections = _nbFaceIntNodes + _eIntPoints.size();
2865 if ( _nbCornerNodes + nbIntersections < 4 )
2868 if ( _nbBndNodes == _nbCornerNodes && nbIntersections == 0 && isInHole() )
2869 return; // cell is in a hole
2871 IsInternalFlag intFlag = IS_NOT_INTERNAL;
2872 if ( solid->HasInternalFaces() && this->isCutByInternalFace( intFlag ))
2874 for ( _SplitIterator it( _hexLinks ); it.More(); it.Next() )
2876 if ( compute( solid, intFlag ))
2877 _volumeDefs.SetNext( new _volumeDef( _volumeDefs ));
2882 if ( solidIndex >= 0 )
2883 intFlag = IS_CUT_BY_INTERNAL_FACE;
2885 compute( solid, intFlag );
2889 //================================================================================
2891 * \brief Compute mesh volumes resulted from intersection of the Hexahedron
2893 bool Hexahedron::compute( const Solid* solid, const IsInternalFlag intFlag )
2896 _polygons.reserve( 20 );
2898 for ( int iN = 0; iN < 8; ++iN )
2899 _hexNodes[iN]._usedInFace = 0;
2901 if ( intFlag & IS_CUT_BY_INTERNAL_FACE && !_grid->_toAddEdges ) // Issue #19913
2902 preventVolumesOverlapping();
2904 std::set< TGeomID > concaveFaces; // to avoid connecting nodes laying on them
2906 if ( solid->HasConcaveVertex() )
2908 for ( const E_IntersectPoint* ip : _eIntPoints )
2910 if ( const ConcaveFace* cf = solid->GetConcave( ip->_shapeID ))
2911 if ( this->hasEdgesAround( cf ))
2912 concaveFaces.insert( cf->_concaveFace );
2914 if ( concaveFaces.empty() || concaveFaces.size() * 3 < _eIntPoints.size() )
2915 for ( const _Node& hexNode: _hexNodes )
2917 if ( hexNode._node && hexNode._intPoint && hexNode._intPoint->_faceIDs.size() >= 3 )
2918 if ( const ConcaveFace* cf = solid->GetConcave( hexNode._node->GetShapeID() ))
2919 if ( this->hasEdgesAround( cf ))
2920 concaveFaces.insert( cf->_concaveFace );
2924 // Create polygons from quadrangles
2925 // --------------------------------
2927 vector< _OrientedLink > splits;
2928 vector<_Node*> chainNodes;
2929 _Face* coplanarPolyg;
2931 const bool hasEdgeIntersections = !_eIntPoints.empty();
2932 const bool toCheckSideDivision = isImplementEdges() || intFlag & IS_CUT_BY_INTERNAL_FACE;
2934 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
2936 _Face& quad = _hexQuads[ iF ] ;
2938 _polygons.resize( _polygons.size() + 1 );
2939 _Face* polygon = &_polygons.back();
2940 polygon->_polyLinks.reserve( 20 );
2941 polygon->_name = quad._name;
2944 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
2945 for ( size_t iS = 0; iS < quad._links[ iE ].NbResultLinks(); ++iS )
2946 splits.push_back( quad._links[ iE ].ResultLink( iS ));
2948 if ( splits.size() == 4 &&
2949 isQuadOnFace( iF )) // check if a quad on FACE is not split
2951 polygon->_links.swap( splits );
2952 continue; // goto the next quad
2955 // add splits of links to a polygon and add _polyLinks to make
2956 // polygon's boundary closed
2958 int nbSplits = splits.size();
2959 if (( nbSplits == 1 ) &&
2960 ( quad._eIntNodes.empty() ||
2961 splits[0].FirstNode()->IsLinked( splits[0].LastNode()->_intPoint )))
2962 //( quad._eIntNodes.empty() || _nbCornerNodes + nbIntersections > 6 ))
2965 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2966 if ( quad._eIntNodes[ iP ]->IsUsedInFace( polygon ))
2967 quad._eIntNodes[ iP ]->_usedInFace = 0;
2969 size_t nbUsedEdgeNodes = 0;
2970 _Face* prevPolyg = 0; // polygon previously created from this quad
2972 while ( nbSplits > 0 )
2975 while ( !splits[ iS ] )
2978 if ( !polygon->_links.empty() )
2980 _polygons.resize( _polygons.size() + 1 );
2981 polygon = &_polygons.back();
2982 polygon->_polyLinks.reserve( 20 );
2983 polygon->_name = quad._name;
2985 polygon->_links.push_back( splits[ iS ] );
2986 splits[ iS++ ]._link = 0;
2989 _Node* nFirst = polygon->_links.back().FirstNode();
2990 _Node *n1,*n2 = polygon->_links.back().LastNode();
2991 for ( ; nFirst != n2 && iS < splits.size(); ++iS )
2993 _OrientedLink& split = splits[ iS ];
2994 if ( !split ) continue;
2996 n1 = split.FirstNode();
2999 (( n1->_intPoint->_faceIDs.size() > 1 && toCheckSideDivision ) ||
3000 ( n1->_isInternalFlags )))
3002 // n1 is at intersection with EDGE
3003 if ( findChainOnEdge( splits, polygon->_links.back(), split, concaveFaces,
3004 iS, quad, chainNodes ))
3006 for ( size_t i = 1; i < chainNodes.size(); ++i )
3007 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
3008 if ( chainNodes.back() != n1 ) // not a partial cut by INTERNAL FACE
3010 prevPolyg = polygon;
3011 n2 = chainNodes.back();
3016 else if ( n1 != n2 )
3018 // try to connect to intersections with EDGEs
3019 if ( quad._eIntNodes.size() > nbUsedEdgeNodes &&
3020 findChain( n2, n1, quad, chainNodes ))
3022 for ( size_t i = 1; i < chainNodes.size(); ++i )
3024 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i] );
3025 nbUsedEdgeNodes += ( chainNodes[i]->IsUsedInFace( polygon ));
3027 if ( chainNodes.back() != n1 )
3029 n2 = chainNodes.back();
3034 // try to connect to a split ending on the same FACE
3037 _OrientedLink foundSplit;
3038 for ( size_t i = iS; i < splits.size() && !foundSplit; ++i )
3039 if (( foundSplit = splits[ i ]) &&
3040 ( n2->IsLinked( foundSplit.FirstNode()->_intPoint )))
3046 foundSplit._link = 0;
3050 if ( n2 != foundSplit.FirstNode() )
3052 polygon->AddPolyLink( n2, foundSplit.FirstNode() );
3053 n2 = foundSplit.FirstNode();
3059 if ( n2->IsLinked( nFirst->_intPoint ))
3061 polygon->AddPolyLink( n2, n1, prevPolyg );
3064 } // if ( n1 != n2 )
3066 polygon->_links.push_back( split );
3069 n2 = polygon->_links.back().LastNode();
3073 if ( nFirst != n2 ) // close a polygon
3075 if ( !findChain( n2, nFirst, quad, chainNodes ))
3077 if ( !closePolygon( polygon, chainNodes ))
3078 if ( !isImplementEdges() )
3079 chainNodes.push_back( nFirst );
3081 for ( size_t i = 1; i < chainNodes.size(); ++i )
3083 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
3084 nbUsedEdgeNodes += bool( chainNodes[i]->IsUsedInFace( polygon ));
3088 if ( polygon->_links.size() < 3 && nbSplits > 0 )
3090 polygon->_polyLinks.clear();
3091 polygon->_links.clear();
3093 } // while ( nbSplits > 0 )
3095 if ( polygon->_links.size() < 3 )
3097 _polygons.pop_back();
3099 } // loop on 6 hexahedron sides
3101 // Create polygons closing holes in a polyhedron
3102 // ----------------------------------------------
3104 // clear _usedInFace
3105 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
3106 _intNodes[ iN ]._usedInFace = 0;
3108 // add polygons to their links and mark used nodes
3109 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3111 _Face& polygon = _polygons[ iP ];
3112 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3114 polygon._links[ iL ].AddFace( &polygon );
3115 polygon._links[ iL ].FirstNode()->_usedInFace = &polygon;
3119 vector< _OrientedLink* > freeLinks;
3120 freeLinks.reserve(20);
3121 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3123 _Face& polygon = _polygons[ iP ];
3124 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3125 if ( polygon._links[ iL ].NbFaces() < 2 )
3126 freeLinks.push_back( & polygon._links[ iL ]);
3128 int nbFreeLinks = freeLinks.size();
3129 if ( nbFreeLinks == 1 ) return false;
3131 // put not used intersection nodes to _vIntNodes
3132 int nbVertexNodes = 0; // nb not used vertex nodes
3134 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
3135 nbVertexNodes += ( !_vIntNodes[ iN ]->IsUsedInFace() );
3137 const double tol = 1e-3 * Min( Min( _sideLength[0], _sideLength[1] ), _sideLength[0] );
3138 for ( size_t iN = _nbFaceIntNodes; iN < _intNodes.size(); ++iN )
3140 if ( _intNodes[ iN ].IsUsedInFace() ) continue;
3141 if ( dynamic_cast< const F_IntersectPoint* >( _intNodes[ iN ]._intPoint )) continue;
3143 findEqualNode( _vIntNodes, _intNodes[ iN ].EdgeIntPnt(), tol*tol );
3146 _vIntNodes.push_back( &_intNodes[ iN ]);
3152 std::set<TGeomID> usedFaceIDs;
3153 std::vector< TGeomID > faces;
3154 TGeomID curFace = 0;
3155 const size_t nbQuadPolygons = _polygons.size();
3156 E_IntersectPoint ipTmp;
3157 std::map< TGeomID, std::vector< const B_IntersectPoint* > > tmpAddedFace; // face added to _intPoint
3159 // create polygons by making closed chains of free links
3160 size_t iPolygon = _polygons.size();
3161 while ( nbFreeLinks > 0 )
3163 if ( iPolygon == _polygons.size() )
3165 _polygons.resize( _polygons.size() + 1 );
3166 _polygons[ iPolygon ]._polyLinks.reserve( 20 );
3167 _polygons[ iPolygon ]._links.reserve( 20 );
3169 _Face& polygon = _polygons[ iPolygon ];
3171 _OrientedLink* curLink = 0;
3173 if (( !hasEdgeIntersections ) ||
3174 ( nbFreeLinks < 4 && nbVertexNodes == 0 ))
3176 // get a remaining link to start from
3177 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3178 if (( curLink = freeLinks[ iL ] ))
3179 freeLinks[ iL ] = 0;
3180 polygon._links.push_back( *curLink );
3184 // find all links connected to curLink
3185 curNode = curLink->FirstNode();
3187 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3188 if ( freeLinks[ iL ] && freeLinks[ iL ]->LastNode() == curNode )
3190 curLink = freeLinks[ iL ];
3191 freeLinks[ iL ] = 0;
3193 polygon._links.push_back( *curLink );
3195 } while ( curLink );
3197 else // there are intersections with EDGEs
3199 // get a remaining link to start from, one lying on minimal nb of FACEs
3201 typedef pair< TGeomID, int > TFaceOfLink;
3202 TFaceOfLink faceOfLink( -1, -1 );
3203 TFaceOfLink facesOfLink[3] = { faceOfLink, faceOfLink, faceOfLink };
3204 for ( size_t iL = 0; iL < freeLinks.size(); ++iL )
3205 if ( freeLinks[ iL ] )
3207 faces = freeLinks[ iL ]->GetNotUsedFace( usedFaceIDs );
3208 if ( faces.size() == 1 )
3210 faceOfLink = TFaceOfLink( faces[0], iL );
3211 if ( !freeLinks[ iL ]->HasEdgeNodes() )
3213 facesOfLink[0] = faceOfLink;
3215 else if ( facesOfLink[0].first < 0 )
3217 faceOfLink = TFaceOfLink(( faces.empty() ? -1 : faces[0]), iL );
3218 facesOfLink[ 1 + faces.empty() ] = faceOfLink;
3221 for ( int i = 0; faceOfLink.first < 0 && i < 3; ++i )
3222 faceOfLink = facesOfLink[i];
3224 if ( faceOfLink.first < 0 ) // all faces used
3226 for ( size_t iL = 0; iL < freeLinks.size() && faceOfLink.first < 1; ++iL )
3227 if (( curLink = freeLinks[ iL ]))
3230 curLink->FirstNode()->IsLinked( curLink->LastNode()->_intPoint );
3231 faceOfLink.second = iL;
3233 usedFaceIDs.clear();
3235 curFace = faceOfLink.first;
3236 curLink = freeLinks[ faceOfLink.second ];
3237 freeLinks[ faceOfLink.second ] = 0;
3239 usedFaceIDs.insert( curFace );
3240 polygon._links.push_back( *curLink );
3243 // find all links lying on a curFace
3246 // go forward from curLink
3247 curNode = curLink->LastNode();
3249 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3250 if ( freeLinks[ iL ] &&
3251 freeLinks[ iL ]->FirstNode() == curNode &&
3252 freeLinks[ iL ]->LastNode()->IsOnFace( curFace ))
3254 curLink = freeLinks[ iL ];
3255 freeLinks[ iL ] = 0;
3256 polygon._links.push_back( *curLink );
3259 } while ( curLink );
3261 std::reverse( polygon._links.begin(), polygon._links.end() );
3263 curLink = & polygon._links.back();
3266 // go backward from curLink
3267 curNode = curLink->FirstNode();
3269 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3270 if ( freeLinks[ iL ] &&
3271 freeLinks[ iL ]->LastNode() == curNode &&
3272 freeLinks[ iL ]->FirstNode()->IsOnFace( curFace ))
3274 curLink = freeLinks[ iL ];
3275 freeLinks[ iL ] = 0;
3276 polygon._links.push_back( *curLink );
3279 } while ( curLink );
3281 curNode = polygon._links.back().FirstNode();
3283 if ( polygon._links[0].LastNode() != curNode )
3285 if ( nbVertexNodes > 0 )
3287 // add links with _vIntNodes if not already used
3289 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
3290 if ( !_vIntNodes[ iN ]->IsUsedInFace() &&
3291 _vIntNodes[ iN ]->IsOnFace( curFace ))
3293 _vIntNodes[ iN ]->_usedInFace = &polygon;
3294 chainNodes.push_back( _vIntNodes[ iN ] );
3296 if ( chainNodes.size() > 1 &&
3297 curFace != _grid->PseudoIntExtFaceID() ) /////// TODO
3299 sortVertexNodes( chainNodes, curNode, curFace );
3301 for ( size_t i = 0; i < chainNodes.size(); ++i )
3303 polygon.AddPolyLink( chainNodes[ i ], curNode );
3304 curNode = chainNodes[ i ];
3305 freeLinks.push_back( &polygon._links.back() );
3308 nbVertexNodes -= chainNodes.size();
3310 // if ( polygon._links.size() > 1 )
3312 polygon.AddPolyLink( polygon._links[0].LastNode(), curNode );
3313 freeLinks.push_back( &polygon._links.back() );
3317 } // if there are intersections with EDGEs
3319 if ( polygon._links.size() < 2 ||
3320 polygon._links[0].LastNode() != polygon._links.back().FirstNode() )
3323 break; // closed polygon not found -> invalid polyhedron
3326 if ( polygon._links.size() == 2 )
3328 if ( freeLinks.back() == &polygon._links.back() )
3330 freeLinks.pop_back();
3333 if ( polygon._links.front().NbFaces() > 0 )
3334 polygon._links.back().AddFace( polygon._links.front()._link->_faces[0] );
3335 if ( polygon._links.back().NbFaces() > 0 )
3336 polygon._links.front().AddFace( polygon._links.back()._link->_faces[0] );
3338 if ( iPolygon == _polygons.size()-1 )
3339 _polygons.pop_back();
3341 else // polygon._links.size() >= 2
3343 // add polygon to its links
3344 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3346 polygon._links[ iL ].AddFace( &polygon );
3347 polygon._links[ iL ].Reverse();
3349 if ( /*hasEdgeIntersections &&*/ iPolygon == _polygons.size() - 1 )
3351 // check that a polygon does not lie on a hexa side
3353 for ( size_t iL = 0; iL < polygon._links.size() && !coplanarPolyg; ++iL )
3355 if ( polygon._links[ iL ].NbFaces() < 2 )
3356 continue; // it's a just added free link
3357 // look for a polygon made on a hexa side and sharing
3358 // two or more haxa links
3360 coplanarPolyg = polygon._links[ iL ]._link->_faces[0];
3361 for ( iL2 = iL + 1; iL2 < polygon._links.size(); ++iL2 )
3362 if ( polygon._links[ iL2 ]._link->_faces[0] == coplanarPolyg &&
3363 !coplanarPolyg->IsPolyLink( polygon._links[ iL ]) &&
3364 !coplanarPolyg->IsPolyLink( polygon._links[ iL2 ]) &&
3365 coplanarPolyg < & _polygons[ nbQuadPolygons ])
3367 if ( iL2 == polygon._links.size() )
3370 if ( coplanarPolyg ) // coplanar polygon found
3372 freeLinks.resize( freeLinks.size() - polygon._polyLinks.size() );
3373 nbFreeLinks -= polygon._polyLinks.size();
3375 // an E_IntersectPoint used to mark nodes of coplanarPolyg
3376 // as lying on curFace while they are not at intersection with geometry
3377 ipTmp._faceIDs.resize(1);
3378 ipTmp._faceIDs[0] = curFace;
3380 // fill freeLinks with links not shared by coplanarPolyg and polygon
3381 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3382 if ( polygon._links[ iL ]._link->_faces[1] &&
3383 polygon._links[ iL ]._link->_faces[0] != coplanarPolyg )
3385 _Face* p = polygon._links[ iL ]._link->_faces[0];
3386 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
3387 if ( p->_links[ iL2 ]._link == polygon._links[ iL ]._link )
3389 freeLinks.push_back( & p->_links[ iL2 ] );
3391 freeLinks.back()->RemoveFace( &polygon );
3395 for ( size_t iL = 0; iL < coplanarPolyg->_links.size(); ++iL )
3396 if ( coplanarPolyg->_links[ iL ]._link->_faces[1] &&
3397 coplanarPolyg->_links[ iL ]._link->_faces[1] != &polygon )
3399 _Face* p = coplanarPolyg->_links[ iL ]._link->_faces[0];
3400 if ( p == coplanarPolyg )
3401 p = coplanarPolyg->_links[ iL ]._link->_faces[1];
3402 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
3403 if ( p->_links[ iL2 ]._link == coplanarPolyg->_links[ iL ]._link )
3405 // set links of coplanarPolyg in place of used freeLinks
3406 // to re-create coplanarPolyg next
3408 for ( ; iL3 < freeLinks.size() && freeLinks[ iL3 ]; ++iL3 );
3409 if ( iL3 < freeLinks.size() )
3410 freeLinks[ iL3 ] = ( & p->_links[ iL2 ] );
3412 freeLinks.push_back( & p->_links[ iL2 ] );
3414 freeLinks[ iL3 ]->RemoveFace( coplanarPolyg );
3415 // mark nodes of coplanarPolyg as lying on curFace
3416 for ( int iN = 0; iN < 2; ++iN )
3418 _Node* n = freeLinks[ iL3 ]->_link->_nodes[ iN ];
3420 if ( n->_intPoint ) added = n->_intPoint->Add( ipTmp._faceIDs );
3421 else n->_intPoint = &ipTmp;
3423 tmpAddedFace[ ipTmp._faceIDs[0] ].push_back( n->_intPoint );
3428 // set coplanarPolyg to be re-created next
3429 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3430 if ( coplanarPolyg == & _polygons[ iP ] )
3433 _polygons[ iPolygon ]._links.clear();
3434 _polygons[ iPolygon ]._polyLinks.clear();
3437 _polygons.pop_back();
3438 usedFaceIDs.erase( curFace );
3440 } // if ( coplanarPolyg )
3441 } // if ( hasEdgeIntersections ) - search for coplanarPolyg
3443 iPolygon = _polygons.size();
3445 } // end of case ( polygon._links.size() > 2 )
3446 } // while ( nbFreeLinks > 0 )
3448 for ( auto & face_ip : tmpAddedFace )
3450 curFace = face_ip.first;
3451 for ( const B_IntersectPoint* ip : face_ip.second )
3453 auto it = std::find( ip->_faceIDs.begin(), ip->_faceIDs.end(), curFace );
3454 if ( it != ip->_faceIDs.end() )
3455 ip->_faceIDs.erase( it );
3459 if ( _polygons.size() < 3 )
3462 // check volume size
3464 _hasTooSmall = ! checkPolyhedronSize( intFlag & IS_CUT_BY_INTERNAL_FACE, volSize );
3466 for ( size_t i = 0; i < 8; ++i )
3467 if ( _hexNodes[ i ]._intPoint == &ipTmp )
3468 _hexNodes[ i ]._intPoint = 0;
3471 return false; // too small volume
3474 // Try to find out names of no-name polygons (issue # 19887)
3475 if ( _grid->IsToRemoveExcessEntities() && _polygons.back()._name == SMESH_Block::ID_NONE )
3478 0.5 * ( _grid->_coords[0][_i] + _grid->_coords[0][_i+1] ) * _grid->_axes[0] +
3479 0.5 * ( _grid->_coords[1][_j] + _grid->_coords[1][_j+1] ) * _grid->_axes[1] +
3480 0.5 * ( _grid->_coords[2][_k] + _grid->_coords[2][_k+1] ) * _grid->_axes[2];
3481 for ( size_t i = _polygons.size() - 1; _polygons[i]._name == SMESH_Block::ID_NONE; --i )
3483 _Face& face = _polygons[ i ];
3486 for ( size_t iL = 0; iL < face._links.size(); ++iL )
3488 _Node* n = face._links[ iL ].FirstNode();
3489 gp_XYZ p = SMESH_NodeXYZ( n->Node() );
3490 _grid->ComputeUVW( p, uvw.ChangeCoord().ChangeData() );
3493 gp_Pnt pMin = bb.CornerMin();
3494 if ( bb.IsXThin( _grid->_tol ))
3495 face._name = pMin.X() < uvwCenter.X() ? SMESH_Block::ID_F0yz : SMESH_Block::ID_F1yz;
3496 else if ( bb.IsYThin( _grid->_tol ))
3497 face._name = pMin.Y() < uvwCenter.Y() ? SMESH_Block::ID_Fx0z : SMESH_Block::ID_Fx1z;
3498 else if ( bb.IsZThin( _grid->_tol ))
3499 face._name = pMin.Z() < uvwCenter.Z() ? SMESH_Block::ID_Fxy0 : SMESH_Block::ID_Fxy1;
3503 _volumeDefs._nodes.clear();
3504 _volumeDefs._quantities.clear();
3505 _volumeDefs._names.clear();
3507 // create a classic cell if possible
3510 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
3511 nbPolygons += (_polygons[ iF ]._links.size() > 2 );
3513 //const int nbNodes = _nbCornerNodes + nbIntersections;
3515 for ( size_t i = 0; i < 8; ++i )
3516 nbNodes += _hexNodes[ i ].IsUsedInFace();
3517 for ( size_t i = 0; i < _intNodes.size(); ++i )
3518 nbNodes += _intNodes[ i ].IsUsedInFace();
3520 bool isClassicElem = false;
3521 if ( nbNodes == 8 && nbPolygons == 6 ) isClassicElem = addHexa();
3522 else if ( nbNodes == 4 && nbPolygons == 4 ) isClassicElem = addTetra();
3523 else if ( nbNodes == 6 && nbPolygons == 5 ) isClassicElem = addPenta();
3524 else if ( nbNodes == 5 && nbPolygons == 5 ) isClassicElem = addPyra ();
3525 if ( !isClassicElem )
3527 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
3529 const size_t nbLinks = _polygons[ iF ]._links.size();
3530 if ( nbLinks < 3 ) continue;
3531 _volumeDefs._quantities.push_back( nbLinks );
3532 _volumeDefs._names.push_back( _polygons[ iF ]._name );
3533 for ( size_t iL = 0; iL < nbLinks; ++iL )
3534 _volumeDefs._nodes.push_back( _polygons[ iF ]._links[ iL ].FirstNode() );
3537 _volumeDefs._solidID = solid->ID();
3538 _volumeDefs._size = volSize;
3540 return !_volumeDefs._nodes.empty();
3542 //================================================================================
3544 * \brief Create elements in the mesh
3546 int Hexahedron::MakeElements(SMESH_MesherHelper& helper,
3547 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
3549 SMESHDS_Mesh* mesh = helper.GetMeshDS();
3551 CellsAroundLink c( _grid, 0 );
3552 const size_t nbGridCells = c._nbCells[0] * c._nbCells[1] * c._nbCells[2];
3553 vector< Hexahedron* > allHexa( nbGridCells, 0 );
3556 // set intersection nodes from GridLine's to links of allHexa
3557 int i,j,k, cellIndex, iLink;
3558 for ( int iDir = 0; iDir < 3; ++iDir )
3560 // loop on GridLine's parallel to iDir
3561 LineIndexer lineInd = _grid->GetLineIndexer( iDir );
3562 CellsAroundLink fourCells( _grid, iDir );
3563 for ( ; lineInd.More(); ++lineInd )
3565 GridLine& line = _grid->_lines[ iDir ][ lineInd.LineIndex() ];
3566 multiset< F_IntersectPoint >::const_iterator ip = line._intPoints.begin();
3567 for ( ; ip != line._intPoints.end(); ++ip )
3569 // if ( !ip->_node ) continue; // intersection at a grid node
3570 lineInd.SetIndexOnLine( ip->_indexOnLine );
3571 fourCells.Init( lineInd.I(), lineInd.J(), lineInd.K() );
3572 for ( int iL = 0; iL < 4; ++iL ) // loop on 4 cells sharing a link
3574 if ( !fourCells.GetCell( iL, i,j,k, cellIndex, iLink ))
3576 Hexahedron *& hex = allHexa[ cellIndex ];
3579 hex = new Hexahedron( *this, i, j, k, cellIndex );
3582 hex->_hexLinks[iLink]._fIntPoints.push_back( &(*ip) );
3583 hex->_nbFaceIntNodes += bool( ip->_node );
3589 // implement geom edges into the mesh
3590 addEdges( helper, allHexa, edge2faceIDsMap );
3592 // add not split hexahedra to the mesh
3594 TGeomID solidIDs[20];
3595 vector< Hexahedron* > intHexa; intHexa.reserve( nbIntHex );
3596 vector< const SMDS_MeshElement* > boundaryVolumes; boundaryVolumes.reserve( nbIntHex * 1.1 );
3597 for ( size_t i = 0; i < allHexa.size(); ++i )
3599 // initialize this by not cut allHexa[ i ]
3600 Hexahedron * & hex = allHexa[ i ];
3601 if ( hex ) // split hexahedron
3603 intHexa.push_back( hex );
3604 if ( hex->_nbFaceIntNodes > 0 ||
3605 hex->_eIntPoints.size() > 0 ||
3606 hex->getSolids( solidIDs ) > 1 )
3607 continue; // treat intersected hex later in parallel
3608 this->init( hex->_i, hex->_j, hex->_k );
3612 this->init( i ); // == init(i,j,k)
3614 if (( _nbCornerNodes == 8 ) &&
3615 ( _nbBndNodes < _nbCornerNodes || !isInHole() ))
3617 // order of _hexNodes is defined by enum SMESH_Block::TShapeID
3618 SMDS_MeshElement* el =
3619 mesh->AddVolume( _hexNodes[0].Node(), _hexNodes[2].Node(),
3620 _hexNodes[3].Node(), _hexNodes[1].Node(),
3621 _hexNodes[4].Node(), _hexNodes[6].Node(),
3622 _hexNodes[7].Node(), _hexNodes[5].Node() );
3623 TGeomID solidID = 0;
3624 if ( _nbBndNodes < _nbCornerNodes )
3626 for ( int iN = 0; iN < 8 && !solidID; ++iN )
3627 if ( !_hexNodes[iN]._intPoint ) // no intersection
3628 solidID = _hexNodes[iN].Node()->GetShapeID();
3632 getSolids( solidIDs );
3633 solidID = solidIDs[0];
3635 mesh->SetMeshElementOnShape( el, solidID );
3639 if ( _grid->_toCreateFaces && _nbBndNodes >= 3 )
3641 boundaryVolumes.push_back( el );
3642 el->setIsMarked( true );
3645 else if ( _nbCornerNodes > 3 && !hex )
3647 // all intersections of hex with geometry are at grid nodes
3648 hex = new Hexahedron( *this, _i, _j, _k, i );
3649 intHexa.push_back( hex );
3653 // compute definitions of volumes resulted from hexadron intersection
3655 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, intHexa.size() ),
3656 ParallelHexahedron( intHexa ),
3657 tbb::simple_partitioner()); // computeElements() is called here
3659 for ( size_t i = 0; i < intHexa.size(); ++i )
3660 if ( Hexahedron * hex = intHexa[ i ] )
3661 hex->computeElements();
3664 // simplify polyhedrons
3665 if ( _grid->IsToRemoveExcessEntities() )
3667 for ( size_t i = 0; i < intHexa.size(); ++i )
3668 if ( Hexahedron * hex = intHexa[ i ] )
3669 hex->removeExcessSideDivision( allHexa );
3671 for ( size_t i = 0; i < intHexa.size(); ++i )
3672 if ( Hexahedron * hex = intHexa[ i ] )
3673 hex->removeExcessNodes( allHexa );
3677 for ( size_t i = 0; i < intHexa.size(); ++i )
3678 if ( Hexahedron * hex = intHexa[ i ] )
3679 nbAdded += hex->addVolumes( helper );
3681 // fill boundaryVolumes with volumes neighboring too small skipped volumes
3682 if ( _grid->_toCreateFaces )
3684 for ( size_t i = 0; i < intHexa.size(); ++i )
3685 if ( Hexahedron * hex = intHexa[ i ] )
3686 hex->getBoundaryElems( boundaryVolumes );
3689 // merge nodes on outer sub-shapes with pre-existing ones
3690 TopTools_DataMapIteratorOfDataMapOfShapeInteger s2nIt( _grid->_geometry._shape2NbNodes );
3691 for ( ; s2nIt.More(); s2nIt.Next() )
3692 if ( s2nIt.Value() > 0 )
3693 if ( SMESHDS_SubMesh* sm = mesh->MeshElements( s2nIt.Key() ))
3695 TIDSortedNodeSet smNodes( SMDS_MeshElement::iterator( sm->GetNodes() ),
3696 SMDS_MeshElement::iterator() );
3697 SMESH_MeshEditor::TListOfListOfNodes equalNodes;
3698 SMESH_MeshEditor editor( helper.GetMesh() );
3699 editor.FindCoincidentNodes( smNodes, 10 * _grid->_tol, equalNodes,
3700 /*SeparateCornersAndMedium =*/ false);
3701 if ((int) equalNodes.size() <= s2nIt.Value() )
3702 editor.MergeNodes( equalNodes );
3705 // create boundary mesh faces
3706 addFaces( helper, boundaryVolumes );
3708 // create mesh edges
3709 addSegments( helper, edge2faceIDsMap );
3711 for ( size_t i = 0; i < allHexa.size(); ++i )
3713 delete allHexa[ i ];
3718 //================================================================================
3720 * \brief Implements geom edges into the mesh
3722 void Hexahedron::addEdges(SMESH_MesherHelper& helper,
3723 vector< Hexahedron* >& hexes,
3724 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
3726 if ( edge2faceIDsMap.empty() ) return;
3728 // Prepare planes for intersecting with EDGEs
3731 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ ) // iDirZ gives normal direction to planes
3733 GridPlanes& planes = pln[ iDirZ ];
3734 int iDirX = ( iDirZ + 1 ) % 3;
3735 int iDirY = ( iDirZ + 2 ) % 3;
3736 planes._zNorm = ( _grid->_axes[ iDirX ] ^ _grid->_axes[ iDirY ] ).Normalized();
3737 planes._zProjs.resize ( _grid->_coords[ iDirZ ].size() );
3738 planes._zProjs [0] = 0;
3739 const double zFactor = _grid->_axes[ iDirZ ] * planes._zNorm;
3740 const vector< double > & u = _grid->_coords[ iDirZ ];
3741 for ( size_t i = 1; i < planes._zProjs.size(); ++i )
3743 planes._zProjs [i] = zFactor * ( u[i] - u[0] );
3747 const double deflection = _grid->_minCellSize / 20.;
3748 const double tol = _grid->_tol;
3749 E_IntersectPoint ip;
3751 TColStd_MapOfInteger intEdgeIDs; // IDs of not shared INTERNAL EDGES
3753 // Intersect EDGEs with the planes
3754 map< TGeomID, vector< TGeomID > >::const_iterator e2fIt = edge2faceIDsMap.begin();
3755 for ( ; e2fIt != edge2faceIDsMap.end(); ++e2fIt )
3757 const TGeomID edgeID = e2fIt->first;
3758 const TopoDS_Edge & E = TopoDS::Edge( _grid->Shape( edgeID ));
3759 BRepAdaptor_Curve curve( E );
3760 TopoDS_Vertex v1 = helper.IthVertex( 0, E, false );
3761 TopoDS_Vertex v2 = helper.IthVertex( 1, E, false );
3763 ip._faceIDs = e2fIt->second;
3764 ip._shapeID = edgeID;
3766 bool isInternal = ( ip._faceIDs.size() == 1 && _grid->IsInternal( edgeID ));
3769 intEdgeIDs.Add( edgeID );
3770 intEdgeIDs.Add( _grid->ShapeID( v1 ));
3771 intEdgeIDs.Add( _grid->ShapeID( v2 ));
3774 // discretize the EDGE
3775 GCPnts_UniformDeflection discret( curve, deflection, true );
3776 if ( !discret.IsDone() || discret.NbPoints() < 2 )
3779 // perform intersection
3780 E_IntersectPoint* eip, *vip = 0;
3781 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ )
3783 GridPlanes& planes = pln[ iDirZ ];
3784 int iDirX = ( iDirZ + 1 ) % 3;
3785 int iDirY = ( iDirZ + 2 ) % 3;
3786 double xLen = _grid->_coords[ iDirX ].back() - _grid->_coords[ iDirX ][0];
3787 double yLen = _grid->_coords[ iDirY ].back() - _grid->_coords[ iDirY ][0];
3788 double zLen = _grid->_coords[ iDirZ ].back() - _grid->_coords[ iDirZ ][0];
3789 int dIJK[3], d000[3] = { 0,0,0 };
3790 double o[3] = { _grid->_coords[0][0],
3791 _grid->_coords[1][0],
3792 _grid->_coords[2][0] };
3794 // locate the 1st point of a segment within the grid
3795 gp_XYZ p1 = discret.Value( 1 ).XYZ();
3796 double u1 = discret.Parameter( 1 );
3797 double zProj1 = planes._zNorm * ( p1 - _grid->_origin );
3799 _grid->ComputeUVW( p1, ip._uvw );
3800 int iX1 = int(( ip._uvw[iDirX] - o[iDirX]) / xLen * (_grid->_coords[ iDirX ].size() - 1));
3801 int iY1 = int(( ip._uvw[iDirY] - o[iDirY]) / yLen * (_grid->_coords[ iDirY ].size() - 1));
3802 int iZ1 = int(( ip._uvw[iDirZ] - o[iDirZ]) / zLen * (_grid->_coords[ iDirZ ].size() - 1));
3803 locateValue( iX1, ip._uvw[iDirX], _grid->_coords[ iDirX ], dIJK[ iDirX ], tol );
3804 locateValue( iY1, ip._uvw[iDirY], _grid->_coords[ iDirY ], dIJK[ iDirY ], tol );
3805 locateValue( iZ1, ip._uvw[iDirZ], _grid->_coords[ iDirZ ], dIJK[ iDirZ ], tol );
3807 int ijk[3]; // grid index where a segment intersects a plane
3812 // add the 1st vertex point to a hexahedron
3816 ip._shapeID = _grid->ShapeID( v1 );
3817 vip = _grid->Add( ip );
3818 _grid->UpdateFacesOfVertex( *vip, v1 );
3820 vip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3821 if ( !addIntersection( vip, hexes, ijk, d000 ))
3822 _grid->Remove( vip );
3823 ip._shapeID = edgeID;
3825 for ( int iP = 2; iP <= discret.NbPoints(); ++iP )
3827 // locate the 2nd point of a segment within the grid
3828 gp_XYZ p2 = discret.Value( iP ).XYZ();
3829 double u2 = discret.Parameter( iP );
3830 double zProj2 = planes._zNorm * ( p2 - _grid->_origin );
3832 if ( Abs( zProj2 - zProj1 ) > std::numeric_limits<double>::min() )
3834 locateValue( iZ2, zProj2, planes._zProjs, dIJK[ iDirZ ], tol );
3836 // treat intersections with planes between 2 end points of a segment
3837 int dZ = ( iZ1 <= iZ2 ) ? +1 : -1;
3838 int iZ = iZ1 + ( iZ1 < iZ2 );
3839 for ( int i = 0, nb = Abs( iZ1 - iZ2 ); i < nb; ++i, iZ += dZ )
3841 ip._point = findIntPoint( u1, zProj1, u2, zProj2,
3842 planes._zProjs[ iZ ],
3843 curve, planes._zNorm, _grid->_origin );
3844 _grid->ComputeUVW( ip._point.XYZ(), ip._uvw );
3845 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
3846 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
3849 // add ip to hex "above" the plane
3850 eip = _grid->Add( ip );
3852 eip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3854 bool added = addIntersection( eip, hexes, ijk, dIJK);
3856 // add ip to hex "below" the plane
3857 ijk[ iDirZ ] = iZ-1;
3858 if ( !addIntersection( eip, hexes, ijk, dIJK ) &&
3860 _grid->Remove( eip );
3868 // add the 2nd vertex point to a hexahedron
3872 ip._shapeID = _grid->ShapeID( v2 );
3873 _grid->ComputeUVW( p1, ip._uvw );
3874 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
3875 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
3877 bool sameV = ( v1.IsSame( v2 ));
3880 vip = _grid->Add( ip );
3881 _grid->UpdateFacesOfVertex( *vip, v2 );
3883 vip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3885 if ( !addIntersection( vip, hexes, ijk, d000 ) && !sameV )
3886 _grid->Remove( vip );
3887 ip._shapeID = edgeID;
3889 } // loop on 3 grid directions
3893 if ( intEdgeIDs.Size() > 0 )
3894 cutByExtendedInternal( hexes, intEdgeIDs );
3899 //================================================================================
3901 * \brief Fully cut hexes that are partially cut by INTERNAL FACE.
3902 * Cut them by extended INTERNAL FACE.
3904 void Hexahedron::cutByExtendedInternal( std::vector< Hexahedron* >& hexes,
3905 const TColStd_MapOfInteger& intEdgeIDs )
3907 IntAna_IntConicQuad intersection;
3908 SMESHDS_Mesh* meshDS = _grid->_helper->GetMeshDS();
3909 const double tol2 = _grid->_tol * _grid->_tol;
3911 for ( size_t iH = 0; iH < hexes.size(); ++iH )
3913 Hexahedron* hex = hexes[ iH ];
3914 if ( !hex || hex->_eIntPoints.size() < 2 )
3916 if ( !intEdgeIDs.Contains( hex->_eIntPoints.back()->_shapeID ))
3919 // get 3 points on INTERNAL FACE to construct a cutting plane
3920 gp_Pnt p1 = hex->_eIntPoints[0]->_point;
3921 gp_Pnt p2 = hex->_eIntPoints[1]->_point;
3922 gp_Pnt p3 = hex->mostDistantInternalPnt( iH, p1, p2 );
3924 gp_Vec norm = gp_Vec( p1, p2 ) ^ gp_Vec( p1, p3 );
3927 pln = gp_Pln( p1, norm );
3934 TGeomID intFaceID = hex->_eIntPoints.back()->_faceIDs.front(); // FACE being "extended"
3935 TGeomID solidID = _grid->GetSolid( intFaceID )->ID();
3937 // cut links by the plane
3938 //bool isCut = false;
3939 for ( int iLink = 0; iLink < 12; ++iLink )
3941 _Link& link = hex->_hexLinks[ iLink ];
3942 if ( !link._fIntPoints.empty() )
3944 // if ( link._fIntPoints[0]->_faceIDs.back() == _grid->PseudoIntExtFaceID() )
3946 continue; // already cut link
3948 if ( !link._nodes[0]->Node() ||
3949 !link._nodes[1]->Node() )
3950 continue; // outside link
3952 if ( link._nodes[0]->IsOnFace( intFaceID ))
3954 if ( link._nodes[0]->_intPoint->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
3955 if ( p1.SquareDistance( link._nodes[0]->Point() ) < tol2 ||
3956 p2.SquareDistance( link._nodes[0]->Point() ) < tol2 )
3957 link._nodes[0]->_intPoint->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3958 continue; // link is cut by FACE being "extended"
3960 if ( link._nodes[1]->IsOnFace( intFaceID ))
3962 if ( link._nodes[1]->_intPoint->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
3963 if ( p1.SquareDistance( link._nodes[1]->Point() ) < tol2 ||
3964 p2.SquareDistance( link._nodes[1]->Point() ) < tol2 )
3965 link._nodes[1]->_intPoint->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3966 continue; // link is cut by FACE being "extended"
3968 gp_Pnt p4 = link._nodes[0]->Point();
3969 gp_Pnt p5 = link._nodes[1]->Point();
3970 gp_Lin line( p4, gp_Vec( p4, p5 ));
3972 intersection.Perform( line, pln );
3973 if ( !intersection.IsDone() ||
3974 intersection.IsInQuadric() ||
3975 intersection.IsParallel() ||
3976 intersection.NbPoints() < 1 )
3979 double u = intersection.ParamOnConic(1);
3980 if ( u + _grid->_tol < 0 )
3982 int iDir = iLink / 4;
3983 int index = (&hex->_i)[iDir];
3984 double linkLen = _grid->_coords[iDir][index+1] - _grid->_coords[iDir][index];
3985 if ( u - _grid->_tol > linkLen )
3988 if ( u < _grid->_tol ||
3989 u > linkLen - _grid->_tol ) // intersection at grid node
3991 int i = ! ( u < _grid->_tol ); // [0,1]
3992 int iN = link._nodes[ i ] - hex->_hexNodes; // [0-7]
3994 const F_IntersectPoint * & ip = _grid->_gridIntP[ hex->_origNodeInd +
3995 _grid->_nodeShift[iN] ];
3998 ip = _grid->_extIntPool.getNew();
3999 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4000 //ip->_transition = Trans_INTERNAL;
4002 else if ( ip->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
4004 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4006 hex->_nbFaceIntNodes++;
4011 const gp_Pnt& p = intersection.Point( 1 );
4012 F_IntersectPoint* ip = _grid->_extIntPool.getNew();
4013 ip->_node = meshDS->AddNode( p.X(), p.Y(), p.Z() );
4014 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4015 ip->_transition = Trans_INTERNAL;
4016 meshDS->SetNodeInVolume( ip->_node, solidID );
4018 CellsAroundLink fourCells( _grid, iDir );
4019 fourCells.Init( hex->_i, hex->_j, hex->_k, iLink );
4020 int i,j,k, cellIndex;
4021 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing the link
4023 if ( !fourCells.GetCell( iC, i,j,k, cellIndex, iLink ))
4025 Hexahedron * h = hexes[ cellIndex ];
4027 h = hexes[ cellIndex ] = new Hexahedron( *this, i, j, k, cellIndex );
4028 h->_hexLinks[iLink]._fIntPoints.push_back( ip );
4029 h->_nbFaceIntNodes++;
4036 // for ( size_t i = 0; i < hex->_eIntPoints.size(); ++i )
4038 // if ( _grid->IsInternal( hex->_eIntPoints[i]->_shapeID ) &&
4039 // ! hex->_eIntPoints[i]->IsOnFace( _grid->PseudoIntExtFaceID() ))
4040 // hex->_eIntPoints[i]->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4044 } // loop on all hexes
4048 //================================================================================
4050 * \brief Return intersection point on INTERNAL FACE most distant from given ones
4052 gp_Pnt Hexahedron::mostDistantInternalPnt( int hexIndex, const gp_Pnt& p1, const gp_Pnt& p2 )
4054 gp_Pnt resultPnt = p1;
4056 double maxDist2 = 0;
4057 for ( int iLink = 0; iLink < 12; ++iLink ) // check links
4059 _Link& link = _hexLinks[ iLink ];
4060 for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
4061 if ( _grid->PseudoIntExtFaceID() != link._fIntPoints[i]->_faceIDs[0] &&
4062 _grid->IsInternal( link._fIntPoints[i]->_faceIDs[0] ) &&
4063 link._fIntPoints[i]->_node )
4065 gp_Pnt p = SMESH_NodeXYZ( link._fIntPoints[i]->_node );
4066 double d = p1.SquareDistance( p );
4074 d = p2.SquareDistance( p );
4084 _origNodeInd = _grid->NodeIndex( _i,_j,_k );
4086 for ( size_t iN = 0; iN < 8; ++iN ) // check corners
4088 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
4089 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
4090 if ( _hexNodes[iN]._intPoint )
4091 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
4093 if ( _grid->IsInternal( _hexNodes[iN]._intPoint->_faceIDs[iF]))
4095 gp_Pnt p = SMESH_NodeXYZ( _hexNodes[iN]._node );
4096 double d = p1.SquareDistance( p );
4104 d = p2.SquareDistance( p );
4114 if ( maxDist2 < _grid->_tol * _grid->_tol )
4120 //================================================================================
4122 * \brief Finds intersection of a curve with a plane
4123 * \param [in] u1 - parameter of one curve point
4124 * \param [in] proj1 - projection of the curve point to the plane normal
4125 * \param [in] u2 - parameter of another curve point
4126 * \param [in] proj2 - projection of the other curve point to the plane normal
4127 * \param [in] proj - projection of a point where the curve intersects the plane
4128 * \param [in] curve - the curve
4129 * \param [in] axis - the plane normal
4130 * \param [in] origin - the plane origin
4131 * \return gp_Pnt - the found intersection point
4133 gp_Pnt Hexahedron::findIntPoint( double u1, double proj1,
4134 double u2, double proj2,
4136 BRepAdaptor_Curve& curve,
4138 const gp_XYZ& origin)
4140 double r = (( proj - proj1 ) / ( proj2 - proj1 ));
4141 double u = u1 * ( 1 - r ) + u2 * r;
4142 gp_Pnt p = curve.Value( u );
4143 double newProj = axis * ( p.XYZ() - origin );
4144 if ( Abs( proj - newProj ) > _grid->_tol / 10. )
4147 return findIntPoint( u2, proj2, u, newProj, proj, curve, axis, origin );
4149 return findIntPoint( u1, proj2, u, newProj, proj, curve, axis, origin );
4154 //================================================================================
4156 * \brief Returns indices of a hexahedron sub-entities holding a point
4157 * \param [in] ip - intersection point
4158 * \param [out] facets - 0-3 facets holding a point
4159 * \param [out] sub - index of a vertex or an edge holding a point
4160 * \return int - number of facets holding a point
4162 int Hexahedron::getEntity( const E_IntersectPoint* ip, int* facets, int& sub )
4164 enum { X = 1, Y = 2, Z = 4 }; // == 001, 010, 100
4166 int vertex = 0, edgeMask = 0;
4168 if ( Abs( _grid->_coords[0][ _i ] - ip->_uvw[0] ) < _grid->_tol ) {
4169 facets[ nbFacets++ ] = SMESH_Block::ID_F0yz;
4172 else if ( Abs( _grid->_coords[0][ _i+1 ] - ip->_uvw[0] ) < _grid->_tol ) {
4173 facets[ nbFacets++ ] = SMESH_Block::ID_F1yz;
4177 if ( Abs( _grid->_coords[1][ _j ] - ip->_uvw[1] ) < _grid->_tol ) {
4178 facets[ nbFacets++ ] = SMESH_Block::ID_Fx0z;
4181 else if ( Abs( _grid->_coords[1][ _j+1 ] - ip->_uvw[1] ) < _grid->_tol ) {
4182 facets[ nbFacets++ ] = SMESH_Block::ID_Fx1z;
4186 if ( Abs( _grid->_coords[2][ _k ] - ip->_uvw[2] ) < _grid->_tol ) {
4187 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy0;
4190 else if ( Abs( _grid->_coords[2][ _k+1 ] - ip->_uvw[2] ) < _grid->_tol ) {
4191 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy1;
4198 case 0: sub = 0; break;
4199 case 1: sub = facets[0]; break;
4201 const int edge [3][8] = {
4202 { SMESH_Block::ID_E00z, SMESH_Block::ID_E10z,
4203 SMESH_Block::ID_E01z, SMESH_Block::ID_E11z },
4204 { SMESH_Block::ID_E0y0, SMESH_Block::ID_E1y0, 0, 0,
4205 SMESH_Block::ID_E0y1, SMESH_Block::ID_E1y1 },
4206 { SMESH_Block::ID_Ex00, 0, SMESH_Block::ID_Ex10, 0,
4207 SMESH_Block::ID_Ex01, 0, SMESH_Block::ID_Ex11 }
4209 switch ( edgeMask ) {
4210 case X | Y: sub = edge[ 0 ][ vertex ]; break;
4211 case X | Z: sub = edge[ 1 ][ vertex ]; break;
4212 default: sub = edge[ 2 ][ vertex ];
4218 sub = vertex + SMESH_Block::ID_FirstV;
4223 //================================================================================
4225 * \brief Adds intersection with an EDGE
4227 bool Hexahedron::addIntersection( const E_IntersectPoint* ip,
4228 vector< Hexahedron* >& hexes,
4229 int ijk[], int dIJK[] )
4233 size_t hexIndex[4] = {
4234 _grid->CellIndex( ijk[0], ijk[1], ijk[2] ),
4235 dIJK[0] ? _grid->CellIndex( ijk[0]+dIJK[0], ijk[1], ijk[2] ) : -1,
4236 dIJK[1] ? _grid->CellIndex( ijk[0], ijk[1]+dIJK[1], ijk[2] ) : -1,
4237 dIJK[2] ? _grid->CellIndex( ijk[0], ijk[1], ijk[2]+dIJK[2] ) : -1
4239 for ( int i = 0; i < 4; ++i )
4241 if ( hexIndex[i] < hexes.size() && hexes[ hexIndex[i] ] )
4243 Hexahedron* h = hexes[ hexIndex[i] ];
4244 h->_eIntPoints.reserve(2);
4245 h->_eIntPoints.push_back( ip );
4248 // check if ip is really inside the hex
4249 if (SALOME::VerbosityActivated() && h->isOutParam( ip->_uvw ))
4250 throw SALOME_Exception("ip outside a hex");
4255 //================================================================================
4257 * \brief Check if a hexahedron facet lies on a FACE
4258 * Also return true if the facet does not interfere with any FACE
4260 bool Hexahedron::isQuadOnFace( const size_t iQuad )
4262 _Face& quad = _hexQuads[ iQuad ] ;
4264 int nbGridNodesInt = 0; // nb FACE intersections at grid nodes
4265 int nbNoGeomNodes = 0;
4266 for ( int iE = 0; iE < 4; ++iE )
4268 nbNoGeomNodes = ( !quad._links[ iE ].FirstNode()->_intPoint &&
4269 quad._links[ iE ].NbResultLinks() == 1 );
4271 ( quad._links[ iE ].FirstNode()->_intPoint &&
4272 quad._links[ iE ].NbResultLinks() == 1 &&
4273 quad._links[ iE ].ResultLink( 0 ).FirstNode() == quad._links[ iE ].FirstNode() &&
4274 quad._links[ iE ].ResultLink( 0 ).LastNode() == quad._links[ iE ].LastNode() );
4276 if ( nbNoGeomNodes == 4 )
4279 if ( nbGridNodesInt == 4 ) // all quad nodes are at FACE intersection
4281 size_t iEmin = 0, minNbFaces = 1000;
4282 for ( int iE = 0; iE < 4; ++iE ) // look for a node with min nb FACEs
4284 size_t nbFaces = quad._links[ iE ].FirstNode()->faces().size();
4285 if ( minNbFaces > nbFaces )
4288 minNbFaces = nbFaces;
4291 // check if there is a FACE passing through all 4 nodes
4292 for ( const TGeomID& faceID : quad._links[ iEmin ].FirstNode()->faces() )
4294 bool allNodesAtFace = true;
4295 for ( size_t iE = 0; iE < 4 && allNodesAtFace; ++iE )
4296 allNodesAtFace = ( iE == iEmin ||
4297 quad._links[ iE ].FirstNode()->IsOnFace( faceID ));
4298 if ( allNodesAtFace ) // quad if on faceID
4304 //================================================================================
4306 * \brief Finds nodes at a path from one node to another via intersections with EDGEs
4308 bool Hexahedron::findChain( _Node* n1,
4311 vector<_Node*>& chn )
4314 chn.push_back( n1 );
4315 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4316 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
4317 n1->IsLinked( quad._eIntNodes[ iP ]->_intPoint ) &&
4318 n2->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
4320 chn.push_back( quad._eIntNodes[ iP ]);
4321 chn.push_back( n2 );
4322 quad._eIntNodes[ iP ]->_usedInFace = &quad;
4329 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4330 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
4331 chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
4333 chn.push_back( quad._eIntNodes[ iP ]);
4334 found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
4337 } while ( found && ! chn.back()->IsLinked( n2->_intPoint ) );
4339 if ( chn.back() != n2 && chn.back()->IsLinked( n2->_intPoint ))
4340 chn.push_back( n2 );
4342 return chn.size() > 1;
4344 //================================================================================
4346 * \brief Try to heal a polygon whose ends are not connected
4348 bool Hexahedron::closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const
4350 int i = -1, nbLinks = polygon->_links.size();
4353 vector< _OrientedLink > newLinks;
4354 // find a node lying on the same FACE as the last one
4355 _Node* node = polygon->_links.back().LastNode();
4356 TGeomID avoidFace = node->IsLinked( polygon->_links.back().FirstNode()->_intPoint );
4357 for ( i = nbLinks - 2; i >= 0; --i )
4358 if ( node->IsLinked( polygon->_links[i].FirstNode()->_intPoint, avoidFace ))
4362 for ( ; i < nbLinks; ++i )
4363 newLinks.push_back( polygon->_links[i] );
4367 // find a node lying on the same FACE as the first one
4368 node = polygon->_links[0].FirstNode();
4369 avoidFace = node->IsLinked( polygon->_links[0].LastNode()->_intPoint );
4370 for ( i = 1; i < nbLinks; ++i )
4371 if ( node->IsLinked( polygon->_links[i].LastNode()->_intPoint, avoidFace ))
4374 for ( nbLinks = i + 1, i = 0; i < nbLinks; ++i )
4375 newLinks.push_back( polygon->_links[i] );
4377 if ( newLinks.size() > 1 )
4379 polygon->_links.swap( newLinks );
4381 chainNodes.push_back( polygon->_links.back().LastNode() );
4382 chainNodes.push_back( polygon->_links[0].FirstNode() );
4387 //================================================================================
4389 * \brief Finds nodes on the same EDGE as the first node of avoidSplit.
4391 * This function is for
4392 * 1) a case where an EDGE lies on a quad which lies on a FACE
4393 * so that a part of quad in ON and another part is IN
4394 * 2) INTERNAL FACE passes through the 1st node of avoidSplit
4396 bool Hexahedron::findChainOnEdge( const vector< _OrientedLink >& splits,
4397 const _OrientedLink& prevSplit,
4398 const _OrientedLink& avoidSplit,
4399 const std::set< TGeomID > & concaveFaces,
4402 vector<_Node*>& chn )
4404 _Node* pn1 = prevSplit.FirstNode();
4405 _Node* pn2 = prevSplit.LastNode(); // pn2 is on EDGE, if not on INTERNAL FACE
4406 _Node* an3 = avoidSplit.LastNode();
4407 TGeomID avoidFace = pn1->IsLinked( pn2->_intPoint ); // FACE under the quad
4408 if ( avoidFace < 1 && pn1->_intPoint )
4413 if ( !quad._eIntNodes.empty() ) // connect pn2 with EDGE intersections
4415 chn.push_back( pn2 );
4420 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4421 if (( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad )) &&
4422 ( chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint, avoidFace )) &&
4423 ( !avoidFace || quad._eIntNodes[ iP ]->IsOnFace( avoidFace )))
4425 chn.push_back( quad._eIntNodes[ iP ]);
4426 found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
4433 _Node* n = 0, *stopNode = avoidSplit.LastNode();
4435 if ( pn2 == prevSplit.LastNode() && // pn2 is at avoidSplit.FirstNode()
4436 !isCorner( stopNode )) // stopNode is in the middle of a _hexLinks
4438 // move stopNode to a _hexNodes
4439 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
4440 for ( size_t iL = 0; iL < quad._links[ iE ].NbResultLinks(); ++iL )
4442 const _Link* sideSplit = & quad._links[ iE ]._link->_splits[ iL ];
4443 if ( sideSplit == avoidSplit._link )
4445 if ( quad._links[ iE ].LastNode()->Node() )
4446 stopNode = quad._links[ iE ].LastNode();
4453 // connect pn2 (probably new, at _eIntNodes) with a split
4457 TGeomID commonFaces[20];
4458 _Node* nPrev = nullptr;
4459 for ( i = splits.size()-1; i >= 0; --i )
4465 for ( int is1st = 0; is1st < 2; ++is1st )
4467 _Node* nConn = is1st ? splits[i].FirstNode() : splits[i].LastNode();
4468 if ( nConn == nPrev )
4475 if (( stop = ( nConn == stopNode )))
4477 // find a FACE connecting nConn with pn2 but not with an3
4478 if (( nConn != pn1 ) &&
4479 ( nConn->_intPoint && !nConn->_intPoint->_faceIDs.empty() ) &&
4480 ( nbCommon = nConn->GetCommonFaces( pn2->_intPoint, commonFaces )))
4482 bool a3Coonect = true;
4483 for ( size_t iF = 0; iF < nbCommon && a3Coonect; ++iF )
4484 a3Coonect = an3->IsOnFace( commonFaces[ iF ]) || concaveFaces.count( commonFaces[ iF ]);
4493 if ( nbCommon > 1 ) // nConn is linked with pn2 by an EDGE
4509 if ( n && n != stopNode )
4512 chn.push_back( pn2 );
4517 else if ( !chn.empty() && chn.back()->_isInternalFlags )
4519 // INTERNAL FACE partially cuts the quad
4520 for ( int ip = chn.size() - 2; ip >= 0; --ip )
4521 chn.push_back( chn[ ip ]);
4526 //================================================================================
4528 * \brief Checks transition at the ginen intersection node of a link
4530 bool Hexahedron::isOutPoint( _Link& link, int iP,
4531 SMESH_MesherHelper& helper, const Solid* solid ) const
4535 if ( link._fIntNodes[iP]->faces().size() == 1 &&
4536 _grid->IsInternal( link._fIntNodes[iP]->face(0) ))
4539 const bool moreIntPoints = ( iP+1 < (int) link._fIntNodes.size() );
4542 _Node* n1 = link._fIntNodes[ iP ];
4544 n1 = link._nodes[0];
4545 _Node* n2 = moreIntPoints ? link._fIntNodes[ iP+1 ] : 0;
4546 if ( !n2 || !n2->Node() )
4547 n2 = link._nodes[1];
4551 // get all FACEs under n1 and n2
4552 set< TGeomID > faceIDs;
4553 if ( moreIntPoints ) faceIDs.insert( link._fIntNodes[iP+1]->faces().begin(),
4554 link._fIntNodes[iP+1]->faces().end() );
4555 if ( n2->_intPoint ) faceIDs.insert( n2->_intPoint->_faceIDs.begin(),
4556 n2->_intPoint->_faceIDs.end() );
4557 if ( faceIDs.empty() )
4558 return false; // n2 is inside
4559 if ( n1->_intPoint ) faceIDs.insert( n1->_intPoint->_faceIDs.begin(),
4560 n1->_intPoint->_faceIDs.end() );
4561 faceIDs.insert( link._fIntNodes[iP]->faces().begin(),
4562 link._fIntNodes[iP]->faces().end() );
4564 // get a point between 2 nodes
4565 gp_Pnt p1 = n1->Point();
4566 gp_Pnt p2 = n2->Point();
4567 gp_Pnt pOnLink = 0.8 * p1.XYZ() + 0.2 * p2.XYZ();
4569 TopLoc_Location loc;
4571 set< TGeomID >::iterator faceID = faceIDs.begin();
4572 for ( ; faceID != faceIDs.end(); ++faceID )
4574 // project pOnLink on a FACE
4575 if ( *faceID < 1 || !solid->Contains( *faceID )) continue;
4576 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( *faceID ));
4577 GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( face, loc, 0.1*_grid->_tol );
4578 gp_Pnt testPnt = pOnLink.Transformed( loc.Transformation().Inverted() );
4579 proj.Perform( testPnt );
4580 if ( proj.IsDone() && proj.NbPoints() > 0 )
4583 proj.LowerDistanceParameters( u,v );
4585 if ( proj.LowerDistance() <= 0.1 * _grid->_tol )
4591 // find isOut by normals
4593 if ( GeomLib::NormEstim( BRep_Tool::Surface( face, loc ),
4598 if ( solid->Orientation( face ) == TopAbs_REVERSED )
4600 gp_Vec v( proj.NearestPoint(), testPnt );
4601 isOut = ( v * normal > 0 );
4606 // classify a projection
4607 if ( !n1->IsOnFace( *faceID ) || !n2->IsOnFace( *faceID ))
4609 BRepTopAdaptor_FClass2d cls( face, Precision::Confusion() );
4610 TopAbs_State state = cls.Perform( gp_Pnt2d( u,v ));
4611 if ( state == TopAbs_OUT )
4623 //================================================================================
4625 * \brief Sort nodes on a FACE
4627 void Hexahedron::sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID faceID)
4629 if ( nodes.size() > 20 ) return;
4631 // get shapes under nodes
4632 TGeomID nShapeIds[20], *nShapeIdsEnd = &nShapeIds[0] + nodes.size();
4633 for ( size_t i = 0; i < nodes.size(); ++i )
4634 if ( !( nShapeIds[i] = nodes[i]->ShapeID() ))
4637 // get shapes of the FACE
4638 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( faceID ));
4639 list< TopoDS_Edge > edges;
4640 list< int > nbEdges;
4641 int nbW = SMESH_Block::GetOrderedEdges (face, edges, nbEdges);
4643 // select a WIRE - remove EDGEs of irrelevant WIREs from edges
4644 list< TopoDS_Edge >::iterator e = edges.begin(), eEnd = e;
4645 list< int >::iterator nE = nbEdges.begin();
4646 for ( ; nbW > 0; ++nE, --nbW )
4648 std::advance( eEnd, *nE );
4649 for ( ; e != eEnd; ++e )
4650 for ( int i = 0; i < 2; ++i )
4653 _grid->ShapeID( *e ) :
4654 _grid->ShapeID( SMESH_MesherHelper::IthVertex( 0, *e ));
4656 ( std::find( &nShapeIds[0], nShapeIdsEnd, id ) != nShapeIdsEnd ))
4658 edges.erase( eEnd, edges.end() ); // remove rest wires
4659 e = eEnd = edges.end();
4666 edges.erase( edges.begin(), eEnd ); // remove a current irrelevant wire
4669 // rotate edges to have the first one at least partially out of the hexa
4670 list< TopoDS_Edge >::iterator e = edges.begin(), eMidOut = edges.end();
4671 for ( ; e != edges.end(); ++e )
4673 if ( !_grid->ShapeID( *e ))
4678 for ( int i = 0; i < 2 && !isOut; ++i )
4682 TopoDS_Vertex v = SMESH_MesherHelper::IthVertex( 0, *e );
4683 p = BRep_Tool::Pnt( v );
4685 else if ( eMidOut == edges.end() )
4687 TopLoc_Location loc;
4688 Handle(Geom_Curve) c = BRep_Tool::Curve( *e, loc, f, l);
4689 if ( c.IsNull() ) break;
4690 p = c->Value( 0.5 * ( f + l )).Transformed( loc );
4697 _grid->ComputeUVW( p.XYZ(), uvw );
4698 if ( isOutParam( uvw ))
4709 if ( e != edges.end() )
4710 edges.splice( edges.end(), edges, edges.begin(), e );
4711 else if ( eMidOut != edges.end() )
4712 edges.splice( edges.end(), edges, edges.begin(), eMidOut );
4714 // sort nodes according to the order of edges
4715 _Node* orderNodes [20];
4716 //TGeomID orderShapeIDs[20];
4718 TGeomID id, *pID = 0;
4719 for ( e = edges.begin(); e != edges.end(); ++e )
4721 if (( id = _grid->ShapeID( SMESH_MesherHelper::IthVertex( 0, *e ))) &&
4722 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
4724 //orderShapeIDs[ nbN ] = id;
4725 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
4728 if (( id = _grid->ShapeID( *e )) &&
4729 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
4731 //orderShapeIDs[ nbN ] = id;
4732 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
4736 if ( nbN != nodes.size() )
4739 bool reverse = ( orderNodes[0 ]->Point().SquareDistance( curNode->Point() ) >
4740 orderNodes[nbN-1]->Point().SquareDistance( curNode->Point() ));
4742 for ( size_t i = 0; i < nodes.size(); ++i )
4743 nodes[ i ] = orderNodes[ reverse ? nbN-1-i : i ];
4746 //================================================================================
4748 * \brief Adds computed elements to the mesh
4750 int Hexahedron::addVolumes( SMESH_MesherHelper& helper )
4752 F_IntersectPoint noIntPnt;
4753 const bool toCheckNodePos = _grid->IsToCheckNodePos();
4756 // add elements resulted from hexahedron intersection
4757 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4759 vector< const SMDS_MeshNode* > nodes( volDef->_nodes.size() );
4760 for ( size_t iN = 0; iN < nodes.size(); ++iN )
4762 if ( !( nodes[iN] = volDef->_nodes[iN].Node() ))
4764 if ( const E_IntersectPoint* eip = volDef->_nodes[iN].EdgeIntPnt() )
4766 nodes[iN] = volDef->_nodes[iN]._intPoint->_node =
4767 helper.AddNode( eip->_point.X(),
4770 if ( _grid->ShapeType( eip->_shapeID ) == TopAbs_VERTEX )
4771 helper.GetMeshDS()->SetNodeOnVertex( nodes[iN], eip->_shapeID );
4773 helper.GetMeshDS()->SetNodeOnEdge( nodes[iN], eip->_shapeID );
4776 throw SALOME_Exception("Bug: no node at intersection point");
4778 else if ( volDef->_nodes[iN]._intPoint &&
4779 volDef->_nodes[iN]._intPoint->_node == volDef->_nodes[iN]._node )
4781 // Update position of node at EDGE intersection;
4782 // see comment to _Node::Add( E_IntersectPoint )
4783 SMESHDS_Mesh* mesh = helper.GetMeshDS();
4784 TGeomID shapeID = volDef->_nodes[iN].EdgeIntPnt()->_shapeID;
4785 mesh->UnSetNodeOnShape( nodes[iN] );
4786 if ( _grid->ShapeType( shapeID ) == TopAbs_VERTEX )
4787 mesh->SetNodeOnVertex( nodes[iN], shapeID );
4789 mesh->SetNodeOnEdge( nodes[iN], shapeID );
4791 else if ( toCheckNodePos &&
4792 !nodes[iN]->isMarked() &&
4793 _grid->ShapeType( nodes[iN]->GetShapeID() ) == TopAbs_FACE )
4795 _grid->SetOnShape( nodes[iN], noIntPnt, /*v=*/nullptr,/*unset=*/true );
4796 nodes[iN]->setIsMarked( true );
4798 } // loop to get nodes
4800 const SMDS_MeshElement* v = 0;
4801 if ( !volDef->_quantities.empty() )
4803 v = helper.AddPolyhedralVolume( nodes, volDef->_quantities );
4804 volDef->_size = SMDS_VolumeTool( v ).GetSize();
4805 if ( volDef->_size < 0 ) // invalid polyhedron
4807 if ( ! SMESH_MeshEditor( helper.GetMesh() ).Reorient( v ) || // try to fix
4808 SMDS_VolumeTool( v ).GetSize() < 0 )
4810 helper.GetMeshDS()->RemoveFreeElement( v, /*sm=*/nullptr, /*fromGroups=*/false );
4812 //_hasTooSmall = true;
4814 if (SALOME::VerbosityActivated())
4816 std::cout << "Remove INVALID polyhedron, _cellID = " << _cellID
4817 << " ijk = ( " << _i << " " << _j << " " << _k << " ) "
4818 << " solid " << volDef->_solidID << std::endl;
4825 switch ( nodes.size() )
4827 case 8: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],
4828 nodes[4],nodes[5],nodes[6],nodes[7] );
4830 case 4: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3] );
4832 case 6: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4],nodes[5] );
4834 case 5: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4] );
4838 volDef->_volume = v;
4839 nbAdded += bool( v );
4841 } // loop on _volumeDefs chain
4843 // avoid creating overlapping volumes (bos #24052)
4846 double sumSize = 0, maxSize = 0;
4847 _volumeDef* maxSizeDef = nullptr;
4848 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4850 if ( !volDef->_volume )
4852 sumSize += volDef->_size;
4853 if ( volDef->_size > maxSize )
4855 maxSize = volDef->_size;
4856 maxSizeDef = volDef;
4859 if ( sumSize > _sideLength[0] * _sideLength[1] * _sideLength[2] * 1.05 )
4861 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4862 if ( volDef != maxSizeDef && volDef->_volume )
4864 helper.GetMeshDS()->RemoveFreeElement( volDef->_volume, /*sm=*/nullptr,
4865 /*fromGroups=*/false );
4866 volDef->_volume = nullptr;
4867 //volDef->_nodes.clear();
4873 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4875 if ( volDef->_volume )
4877 helper.GetMeshDS()->SetMeshElementOnShape( volDef->_volume, volDef->_solidID );
4883 //================================================================================
4885 * \brief Return true if the element is in a hole
4887 bool Hexahedron::isInHole() const
4889 if ( !_vIntNodes.empty() )
4892 const size_t ijk[3] = { _i, _j, _k };
4893 F_IntersectPoint curIntPnt;
4895 // consider a cell to be in a hole if all links in any direction
4896 // comes OUT of geometry
4897 for ( int iDir = 0; iDir < 3; ++iDir )
4899 const vector<double>& coords = _grid->_coords[ iDir ];
4900 LineIndexer li = _grid->GetLineIndexer( iDir );
4901 li.SetIJK( _i,_j,_k );
4902 size_t lineIndex[4] = { li.LineIndex (),
4906 bool allLinksOut = true, hasLinks = false;
4907 for ( int iL = 0; iL < 4 && allLinksOut; ++iL ) // loop on 4 links parallel to iDir
4909 const _Link& link = _hexLinks[ iL + 4*iDir ];
4910 // check transition of the first node of a link
4911 const F_IntersectPoint* firstIntPnt = 0;
4912 if ( link._nodes[0]->Node() ) // 1st node is a hexa corner
4914 curIntPnt._paramOnLine = coords[ ijk[ iDir ]] - coords[0] + _grid->_tol;
4915 const GridLine& line = _grid->_lines[ iDir ][ lineIndex[ iL ]];
4916 if ( !line._intPoints.empty() )
4918 multiset< F_IntersectPoint >::const_iterator ip =
4919 line._intPoints.upper_bound( curIntPnt );
4921 firstIntPnt = &(*ip);
4924 else if ( !link._fIntPoints.empty() )
4926 firstIntPnt = link._fIntPoints[0];
4932 allLinksOut = ( firstIntPnt->_transition == Trans_OUT &&
4933 !_grid->IsShared( firstIntPnt->_faceIDs[0] ));
4936 if ( hasLinks && allLinksOut )
4942 //================================================================================
4944 * \brief Check if a polyherdon has an edge lying on EDGE shared by strange FACE
4945 * that will be meshed by other algo
4947 bool Hexahedron::hasStrangeEdge() const
4949 if ( _eIntPoints.size() < 2 )
4952 TopTools_MapOfShape edges;
4953 for ( size_t i = 0; i < _eIntPoints.size(); ++i )
4955 if ( !_grid->IsStrangeEdge( _eIntPoints[i]->_shapeID ))
4957 const TopoDS_Shape& s = _grid->Shape( _eIntPoints[i]->_shapeID );
4958 if ( s.ShapeType() == TopAbs_EDGE )
4960 if ( ! edges.Add( s ))
4961 return true; // an EDGE encounters twice
4965 PShapeIteratorPtr edgeIt = _grid->_helper->GetAncestors( s,
4966 *_grid->_helper->GetMesh(),
4968 while ( const TopoDS_Shape* edge = edgeIt->next() )
4969 if ( ! edges.Add( *edge ))
4970 return true; // an EDGE encounters twice
4976 //================================================================================
4978 * \brief Return true if a polyhedron passes _sizeThreshold criterion
4980 bool Hexahedron::checkPolyhedronSize( bool cutByInternalFace, double & volume) const
4984 if ( cutByInternalFace && !_grid->_toUseThresholdForInternalFaces )
4986 // check if any polygon fully lies on shared/internal FACEs
4987 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
4989 const _Face& polygon = _polygons[iP];
4990 if ( polygon._links.empty() )
4992 bool allNodesInternal = true;
4993 for ( size_t iL = 0; iL < polygon._links.size() && allNodesInternal; ++iL )
4995 _Node* n = polygon._links[ iL ].FirstNode();
4996 allNodesInternal = (( n->IsCutByInternal() ) ||
4997 ( n->_intPoint && _grid->IsAnyShared( n->_intPoint->_faceIDs )));
4999 if ( allNodesInternal )
5003 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
5005 const _Face& polygon = _polygons[iP];
5006 if ( polygon._links.empty() )
5008 gp_XYZ area (0,0,0);
5009 gp_XYZ p1 = polygon._links[ 0 ].FirstNode()->Point().XYZ();
5010 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
5012 gp_XYZ p2 = polygon._links[ iL ].LastNode()->Point().XYZ();
5016 volume += p1 * area;
5020 if ( this->hasStrangeEdge() && volume > 1e-13 )
5023 double initVolume = _sideLength[0] * _sideLength[1] * _sideLength[2];
5025 return volume > initVolume / _grid->_sizeThreshold;
5027 //================================================================================
5029 * \brief Tries to create a hexahedron
5031 bool Hexahedron::addHexa()
5033 int nbQuad = 0, iQuad = -1;
5034 for ( size_t i = 0; i < _polygons.size(); ++i )
5036 if ( _polygons[i]._links.empty() )
5038 if ( _polygons[i]._links.size() != 4 )
5049 for ( int iL = 0; iL < 4; ++iL )
5052 nodes[iL] = _polygons[iQuad]._links[iL].FirstNode();
5055 // find a top node above the base node
5056 _Link* link = _polygons[iQuad]._links[iL]._link;
5057 if ( !link->_faces[0] || !link->_faces[1] )
5058 return debugDumpLink( link );
5059 // a quadrangle sharing <link> with _polygons[iQuad]
5060 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[iQuad] )];
5061 for ( int i = 0; i < 4; ++i )
5062 if ( quad->_links[i]._link == link )
5064 // 1st node of a link opposite to <link> in <quad>
5065 nodes[iL+4] = quad->_links[(i+2)%4].FirstNode();
5071 _volumeDefs.Set( &nodes[0], 8 );
5075 //================================================================================
5077 * \brief Tries to create a tetrahedron
5079 bool Hexahedron::addTetra()
5082 for ( size_t i = 0; i < _polygons.size() && iTria < 0; ++i )
5083 if ( _polygons[i]._links.size() == 3 )
5089 nodes[0] = _polygons[iTria]._links[0].FirstNode();
5090 nodes[1] = _polygons[iTria]._links[1].FirstNode();
5091 nodes[2] = _polygons[iTria]._links[2].FirstNode();
5093 _Link* link = _polygons[iTria]._links[0]._link;
5094 if ( !link->_faces[0] || !link->_faces[1] )
5095 return debugDumpLink( link );
5097 // a triangle sharing <link> with _polygons[0]
5098 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[iTria] )];
5099 for ( int i = 0; i < 3; ++i )
5100 if ( tria->_links[i]._link == link )
5102 nodes[3] = tria->_links[(i+1)%3].LastNode();
5103 _volumeDefs.Set( &nodes[0], 4 );
5109 //================================================================================
5111 * \brief Tries to create a pentahedron
5113 bool Hexahedron::addPenta()
5115 // find a base triangular face
5117 for ( int iF = 0; iF < 5 && iTri < 0; ++iF )
5118 if ( _polygons[ iF ]._links.size() == 3 )
5120 if ( iTri < 0 ) return false;
5125 for ( int iL = 0; iL < 3; ++iL )
5128 nodes[iL] = _polygons[ iTri ]._links[iL].FirstNode();
5131 // find a top node above the base node
5132 _Link* link = _polygons[ iTri ]._links[iL]._link;
5133 if ( !link->_faces[0] || !link->_faces[1] )
5134 return debugDumpLink( link );
5135 // a quadrangle sharing <link> with a base triangle
5136 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[ iTri ] )];
5137 if ( quad->_links.size() != 4 ) return false;
5138 for ( int i = 0; i < 4; ++i )
5139 if ( quad->_links[i]._link == link )
5141 // 1st node of a link opposite to <link> in <quad>
5142 nodes[iL+3] = quad->_links[(i+2)%4].FirstNode();
5148 _volumeDefs.Set( &nodes[0], 6 );
5150 return ( nbN == 6 );
5152 //================================================================================
5154 * \brief Tries to create a pyramid
5156 bool Hexahedron::addPyra()
5158 // find a base quadrangle
5160 for ( int iF = 0; iF < 5 && iQuad < 0; ++iF )
5161 if ( _polygons[ iF ]._links.size() == 4 )
5163 if ( iQuad < 0 ) return false;
5167 nodes[0] = _polygons[iQuad]._links[0].FirstNode();
5168 nodes[1] = _polygons[iQuad]._links[1].FirstNode();
5169 nodes[2] = _polygons[iQuad]._links[2].FirstNode();
5170 nodes[3] = _polygons[iQuad]._links[3].FirstNode();
5172 _Link* link = _polygons[iQuad]._links[0]._link;
5173 if ( !link->_faces[0] || !link->_faces[1] )
5174 return debugDumpLink( link );
5176 // a triangle sharing <link> with a base quadrangle
5177 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[ iQuad ] )];
5178 if ( tria->_links.size() != 3 ) return false;
5179 for ( int i = 0; i < 3; ++i )
5180 if ( tria->_links[i]._link == link )
5182 nodes[4] = tria->_links[(i+1)%3].LastNode();
5183 _volumeDefs.Set( &nodes[0], 5 );
5189 //================================================================================
5191 * \brief Return true if there are _eIntPoints at EDGEs forming a concave corner
5193 bool Hexahedron::hasEdgesAround( const ConcaveFace* cf ) const
5196 ConcaveFace foundGeomHolder;
5197 for ( const E_IntersectPoint* ip : _eIntPoints )
5199 if ( cf->HasEdge( ip->_shapeID ))
5201 if ( ++nbEdges == 2 )
5203 foundGeomHolder.SetEdge( ip->_shapeID );
5205 else if ( ip->_faceIDs.size() >= 3 )
5207 const TGeomID & vID = ip->_shapeID;
5208 if ( cf->HasVertex( vID ) && !foundGeomHolder.HasVertex( vID ))
5210 if ( ++nbEdges == 2 )
5212 foundGeomHolder.SetVertex( vID );
5217 for ( const _Node& hexNode: _hexNodes )
5219 if ( !hexNode._node || !hexNode._intPoint )
5221 const B_IntersectPoint* ip = hexNode._intPoint;
5222 if ( ip->_faceIDs.size() == 2 ) // EDGE
5224 TGeomID edgeID = hexNode._node->GetShapeID();
5225 if ( cf->HasEdge( edgeID ) && !foundGeomHolder.HasEdge( edgeID ))
5227 foundGeomHolder.SetEdge( edgeID );
5228 if ( ++nbEdges == 2 )
5232 else if ( ip->_faceIDs.size() >= 3 ) // VERTEX
5234 TGeomID vID = hexNode._node->GetShapeID();
5235 if ( cf->HasVertex( vID ) && !foundGeomHolder.HasVertex( vID ))
5237 if ( ++nbEdges == 2 )
5239 foundGeomHolder.SetVertex( vID );
5246 //================================================================================
5248 * \brief Dump a link and return \c false
5250 bool Hexahedron::debugDumpLink( Hexahedron::_Link* link )
5252 if (SALOME::VerbosityActivated())
5254 gp_Pnt p1 = link->_nodes[0]->Point(), p2 = link->_nodes[1]->Point();
5255 cout << "BUG: not shared link. IKJ = ( "<< _i << " " << _j << " " << _k << " )" << endl
5256 << "n1 (" << p1.X() << ", "<< p1.Y() << ", "<< p1.Z() << " )" << endl
5257 << "n2 (" << p2.X() << ", "<< p2.Y() << ", "<< p2.Z() << " )" << endl;
5262 //================================================================================
5264 * \brief Classify a point by grid parameters
5266 bool Hexahedron::isOutParam(const double uvw[3]) const
5268 return (( _grid->_coords[0][ _i ] - _grid->_tol > uvw[0] ) ||
5269 ( _grid->_coords[0][ _i+1 ] + _grid->_tol < uvw[0] ) ||
5270 ( _grid->_coords[1][ _j ] - _grid->_tol > uvw[1] ) ||
5271 ( _grid->_coords[1][ _j+1 ] + _grid->_tol < uvw[1] ) ||
5272 ( _grid->_coords[2][ _k ] - _grid->_tol > uvw[2] ) ||
5273 ( _grid->_coords[2][ _k+1 ] + _grid->_tol < uvw[2] ));
5275 //================================================================================
5277 * \brief Find existing triangulation of a polygon
5279 int findExistingTriangulation( const SMDS_MeshElement* polygon,
5280 //const SMDS_Mesh* mesh,
5281 std::vector< const SMDS_MeshNode* >& nodes )
5285 std::vector<const SMDS_MeshNode *> twoNodes(2);
5286 std::vector<const SMDS_MeshElement *> foundFaces; foundFaces.reserve(10);
5287 std::set< const SMDS_MeshElement * > avoidFaces; avoidFaces.insert( polygon );
5289 const int nbPolyNodes = polygon->NbCornerNodes();
5290 twoNodes[1] = polygon->GetNode( nbPolyNodes - 1 );
5291 for ( int iN = 0; iN < nbPolyNodes; ++iN ) // loop on border links of polygon
5293 twoNodes[0] = polygon->GetNode( iN );
5295 int nbFaces = SMDS_Mesh::GetElementsByNodes( twoNodes, foundFaces, SMDSAbs_Face );
5297 for ( int iF = 0; iF < nbFaces; ++iF ) // keep faces lying over polygon
5299 if ( avoidFaces.count( foundFaces[ iF ]))
5301 int i, nbFaceNodes = foundFaces[ iF ]->NbCornerNodes();
5302 for ( i = 0; i < nbFaceNodes; ++i )
5304 const SMDS_MeshNode* n = foundFaces[ iF ]->GetNode( i );
5305 bool isCommonNode = ( n == twoNodes[0] ||
5307 polygon->GetNodeIndex( n ) >= 0 );
5308 if ( !isCommonNode )
5311 if ( i == nbFaceNodes ) // all nodes of foundFaces[iF] are shared with polygon
5312 if ( nbOkFaces++ != iF )
5313 foundFaces[ nbOkFaces-1 ] = foundFaces[ iF ];
5315 if ( nbOkFaces > 0 )
5317 int iFaceSelected = 0;
5318 if ( nbOkFaces > 1 ) // select a face with minimal distance from polygon
5320 double minDist = Precision::Infinite();
5321 for ( int iF = 0; iF < nbOkFaces; ++iF )
5323 int i, nbFaceNodes = foundFaces[ iF ]->NbCornerNodes();
5324 gp_XYZ gc = SMESH_NodeXYZ( foundFaces[ iF ]->GetNode( 0 ));
5325 for ( i = 1; i < nbFaceNodes; ++i )
5326 gc += SMESH_NodeXYZ( foundFaces[ iF ]->GetNode( i ));
5329 double dist = SMESH_MeshAlgos::GetDistance( polygon, gc );
5330 if ( dist < minDist )
5337 if ( foundFaces[ iFaceSelected ]->NbCornerNodes() != 3 )
5339 nodes.insert( nodes.end(),
5340 foundFaces[ iFaceSelected ]->begin_nodes(),
5341 foundFaces[ iFaceSelected ]->end_nodes());
5342 if ( !SMESH_MeshAlgos::IsRightOrder( foundFaces[ iFaceSelected ],
5343 twoNodes[0], twoNodes[1] ))
5345 // reverse just added nodes
5346 std::reverse( nodes.end() - 3, nodes.end() );
5348 avoidFaces.insert( foundFaces[ iFaceSelected ]);
5352 twoNodes[1] = twoNodes[0];
5354 } // loop on polygon nodes
5358 //================================================================================
5360 * \brief Divide a polygon into triangles and modify accordingly an adjacent polyhedron
5362 void splitPolygon( const SMDS_MeshElement* polygon,
5363 SMDS_VolumeTool & volume,
5364 const int facetIndex,
5365 const TGeomID faceID,
5366 const TGeomID solidID,
5367 SMESH_MeshEditor::ElemFeatures& face,
5368 SMESH_MeshEditor& editor,
5369 const bool reinitVolume)
5371 SMESH_MeshAlgos::Triangulate divider(/*optimize=*/false);
5372 bool triangulationExist = false;
5373 int nbTrias = findExistingTriangulation( polygon, face.myNodes );
5375 triangulationExist = true;
5377 nbTrias = divider.GetTriangles( polygon, face.myNodes );
5378 face.myNodes.resize( nbTrias * 3 );
5380 SMESH_MeshEditor::ElemFeatures newVolumeDef;
5381 newVolumeDef.Init( volume.Element() );
5382 newVolumeDef.SetID( volume.Element()->GetID() );
5384 newVolumeDef.myPolyhedQuantities.reserve( volume.NbFaces() + nbTrias );
5385 newVolumeDef.myNodes.reserve( volume.NbNodes() + nbTrias * 3 );
5387 SMESHDS_Mesh* meshDS = editor.GetMeshDS();
5388 SMDS_MeshElement* newTriangle;
5389 for ( int iF = 0, nF = volume.NbFaces(); iF < nF; iF++ )
5391 if ( iF == facetIndex )
5393 newVolumeDef.myPolyhedQuantities.push_back( 3 );
5394 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(),
5395 face.myNodes.begin(),
5396 face.myNodes.begin() + 3 );
5397 meshDS->RemoveFreeElement( polygon, 0, false );
5398 if ( !triangulationExist )
5400 newTriangle = meshDS->AddFace( face.myNodes[0], face.myNodes[1], face.myNodes[2] );
5401 meshDS->SetMeshElementOnShape( newTriangle, faceID );
5406 const SMDS_MeshNode** nn = volume.GetFaceNodes( iF );
5407 const size_t nbFaceNodes = volume.NbFaceNodes ( iF );
5408 newVolumeDef.myPolyhedQuantities.push_back( nbFaceNodes );
5409 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(), nn, nn + nbFaceNodes );
5413 for ( size_t iN = 3; iN < face.myNodes.size(); iN += 3 )
5415 newVolumeDef.myPolyhedQuantities.push_back( 3 );
5416 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(),
5417 face.myNodes.begin() + iN,
5418 face.myNodes.begin() + iN + 3 );
5419 if ( !triangulationExist )
5421 newTriangle = meshDS->AddFace( face.myNodes[iN], face.myNodes[iN+1], face.myNodes[iN+2] );
5422 meshDS->SetMeshElementOnShape( newTriangle, faceID );
5426 meshDS->RemoveFreeElement( volume.Element(), 0, false );
5427 SMDS_MeshElement* newVolume = editor.AddElement( newVolumeDef.myNodes, newVolumeDef );
5428 meshDS->SetMeshElementOnShape( newVolume, solidID );
5433 volume.Set( newVolume );
5437 //================================================================================
5439 * \brief Look for a FACE supporting all given nodes made on EDGEs and VERTEXes
5441 TGeomID findCommonFace( const std::vector< const SMDS_MeshNode* > & nn,
5442 const SMESH_Mesh* mesh )
5445 TGeomID shapeIDs[20];
5446 for ( size_t iN = 0; iN < nn.size(); ++iN )
5447 shapeIDs[ iN ] = nn[ iN ]->GetShapeID();
5449 SMESH_subMesh* sm = mesh->GetSubMeshContaining( shapeIDs[ 0 ]);
5450 for ( const SMESH_subMesh * smFace : sm->GetAncestors() )
5452 if ( smFace->GetSubShape().ShapeType() != TopAbs_FACE )
5455 faceID = smFace->GetId();
5457 for ( size_t iN = 1; iN < nn.size() && faceID; ++iN )
5459 if ( !smFace->DependsOn( shapeIDs[ iN ]))
5467 //================================================================================
5469 * \brief Create mesh faces at free facets
5471 void Hexahedron::addFaces( SMESH_MesherHelper& helper,
5472 const vector< const SMDS_MeshElement* > & boundaryVolumes )
5474 if ( !_grid->_toCreateFaces )
5477 SMDS_VolumeTool vTool;
5478 vector<int> bndFacets;
5479 SMESH_MeshEditor editor( helper.GetMesh() );
5480 SMESH_MeshEditor::ElemFeatures face( SMDSAbs_Face );
5481 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
5483 // check if there are internal or shared FACEs
5484 bool hasInternal = ( !_grid->_geometry.IsOneSolid() ||
5485 _grid->_geometry._soleSolid.HasInternalFaces() );
5487 for ( size_t iV = 0; iV < boundaryVolumes.size(); ++iV )
5489 if ( !vTool.Set( boundaryVolumes[ iV ]))
5492 TGeomID solidID = vTool.Element()->GetShapeID();
5493 Solid * solid = _grid->GetOneOfSolids( solidID );
5495 // find boundary facets
5498 for ( int iF = 0, n = vTool.NbFaces(); iF < n; iF++ )
5500 const SMDS_MeshElement* otherVol;
5501 bool isBoundary = vTool.IsFreeFace( iF, &otherVol );
5504 bndFacets.push_back( iF );
5506 else if (( hasInternal ) ||
5507 ( !_grid->IsSolid( otherVol->GetShapeID() )))
5509 // check if all nodes are on internal/shared FACEs
5511 const SMDS_MeshNode** nn = vTool.GetFaceNodes( iF );
5512 const size_t nbFaceNodes = vTool.NbFaceNodes ( iF );
5513 for ( size_t iN = 0; iN < nbFaceNodes && isBoundary; ++iN )
5514 isBoundary = ( nn[ iN ]->GetShapeID() != solidID );
5516 bndFacets.push_back( -( iF+1 )); // !!! minus ==> to check the FACE
5519 if ( bndFacets.empty() )
5524 if ( !vTool.IsPoly() )
5525 vTool.SetExternalNormal();
5526 for ( size_t i = 0; i < bndFacets.size(); ++i ) // loop on boundary facets
5528 const bool isBoundary = ( bndFacets[i] >= 0 );
5529 const int iFacet = isBoundary ? bndFacets[i] : -bndFacets[i]-1;
5530 const SMDS_MeshNode** nn = vTool.GetFaceNodes( iFacet );
5531 const size_t nbFaceNodes = vTool.NbFaceNodes ( iFacet );
5532 face.myNodes.assign( nn, nn + nbFaceNodes );
5535 const SMDS_MeshElement* existFace = 0, *newFace = 0;
5537 if (( existFace = meshDS->FindElement( face.myNodes, SMDSAbs_Face )))
5539 if ( existFace->isMarked() )
5540 continue; // created by this method
5541 faceID = existFace->GetShapeID();
5545 // look for a supporting FACE
5546 for ( size_t iN = 0; iN < nbFaceNodes && !faceID; ++iN ) // look for a node on FACE
5548 if ( nn[ iN ]->GetPosition()->GetDim() == 2 )
5549 faceID = nn[ iN ]->GetShapeID();
5552 faceID = findCommonFace( face.myNodes, helper.GetMesh() );
5554 bool toCheckFace = faceID && (( !isBoundary ) ||
5555 ( hasInternal && _grid->_toUseThresholdForInternalFaces ));
5556 if ( toCheckFace ) // check if all nodes are on the found FACE
5558 SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMeshContaining( faceID );
5559 for ( size_t iN = 0; iN < nbFaceNodes && faceID; ++iN )
5561 TGeomID subID = nn[ iN ]->GetShapeID();
5562 if ( subID != faceID && !faceSM->DependsOn( subID ))
5565 // if ( !faceID && !isBoundary )
5568 if ( !faceID && !isBoundary )
5572 // orient a new face according to supporting FACE orientation in shape_to_mesh
5573 if ( !isBoundary && !solid->IsOutsideOriented( faceID ))
5576 editor.Reorient( existFace );
5578 std::reverse( face.myNodes.begin(), face.myNodes.end() );
5581 if ( ! ( newFace = existFace ))
5583 face.SetPoly( nbFaceNodes > 4 );
5584 newFace = editor.AddElement( face.myNodes, face );
5587 newFace->setIsMarked( true ); // to distinguish from face created in getBoundaryElems()
5590 if ( faceID && _grid->IsBoundaryFace( faceID )) // face is not shared
5592 // set newFace to the found FACE provided that it fully lies on the FACE
5593 for ( size_t iN = 0; iN < nbFaceNodes && faceID; ++iN )
5594 if ( nn[iN]->GetShapeID() == solidID )
5597 meshDS->UnSetMeshElementOnShape( existFace, _grid->Shape( faceID ));
5602 if ( faceID && nbFaceNodes > 4 &&
5603 !_grid->IsInternal( faceID ) &&
5604 !_grid->IsShared( faceID ) &&
5605 !_grid->IsBoundaryFace( faceID ))
5607 // split a polygon that will be used by other 3D algorithm
5609 splitPolygon( newFace, vTool, iFacet, faceID, solidID,
5610 face, editor, i+1 < bndFacets.size() );
5615 meshDS->SetMeshElementOnShape( newFace, faceID );
5617 meshDS->SetMeshElementOnShape( newFace, solidID );
5619 } // loop on bndFacets
5620 } // loop on boundaryVolumes
5623 // Orient coherently mesh faces on INTERNAL FACEs
5627 TopExp_Explorer faceExp( _grid->_geometry._mainShape, TopAbs_FACE );
5628 for ( ; faceExp.More(); faceExp.Next() )
5630 if ( faceExp.Current().Orientation() != TopAbs_INTERNAL )
5633 SMESHDS_SubMesh* sm = meshDS->MeshElements( faceExp.Current() );
5634 if ( !sm ) continue;
5636 TIDSortedElemSet facesToOrient;
5637 for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
5638 facesToOrient.insert( facesToOrient.end(), fIt->next() );
5639 if ( facesToOrient.size() < 2 )
5642 gp_Dir direction(1,0,0);
5643 TIDSortedElemSet refFaces;
5644 editor.Reorient2D( facesToOrient, direction, refFaces, /*allowNonManifold=*/true );
5650 //================================================================================
5652 * \brief Create mesh segments.
5654 void Hexahedron::addSegments( SMESH_MesherHelper& helper,
5655 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap )
5657 SMESHDS_Mesh* mesh = helper.GetMeshDS();
5659 std::vector<const SMDS_MeshNode*> nodes;
5660 std::vector<const SMDS_MeshElement *> elems;
5661 map< TGeomID, vector< TGeomID > >::const_iterator e2ff = edge2faceIDsMap.begin();
5662 for ( ; e2ff != edge2faceIDsMap.end(); ++e2ff )
5664 const TopoDS_Edge& edge = TopoDS::Edge( _grid->Shape( e2ff->first ));
5665 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( e2ff->second[0] ));
5666 StdMeshers_FaceSide side( face, edge, helper.GetMesh(), /*isFwd=*/true, /*skipMed=*/true );
5667 nodes = side.GetOrderedNodes();
5670 if ( nodes.size() == 2 )
5671 // check that there is an element connecting two nodes
5672 if ( !mesh->GetElementsByNodes( nodes, elems ))
5675 for ( size_t i = 1; i < nodes.size(); i++ )
5677 if ( mesh->FindEdge( nodes[i-1], nodes[i] ))
5679 SMDS_MeshElement* segment = mesh->AddEdge( nodes[i-1], nodes[i] );
5680 mesh->SetMeshElementOnShape( segment, e2ff->first );
5686 //================================================================================
5688 * \brief Return created volumes and volumes that can have free facet because of
5689 * skipped small volume. Also create mesh faces on free facets
5690 * of adjacent not-cut volumes if the result volume is too small.
5692 void Hexahedron::getBoundaryElems( vector< const SMDS_MeshElement* > & boundaryElems )
5694 if ( _hasTooSmall /*|| _volumeDefs.IsEmpty()*/ )
5696 // create faces around a missing small volume
5698 SMESH_MeshEditor editor( _grid->_helper->GetMesh() );
5699 SMESH_MeshEditor::ElemFeatures polygon( SMDSAbs_Face );
5700 SMESHDS_Mesh* meshDS = _grid->_helper->GetMeshDS();
5701 std::vector<const SMDS_MeshElement *> adjVolumes(2);
5702 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
5704 const size_t nbLinks = _polygons[ iF ]._links.size();
5705 if ( nbLinks != 4 ) continue;
5706 polygon.myNodes.resize( nbLinks );
5707 polygon.myNodes.back() = 0;
5708 for ( size_t iL = 0, iN = nbLinks - 1; iL < nbLinks; ++iL, --iN )
5709 if ( ! ( polygon.myNodes[iN] = _polygons[ iF ]._links[ iL ].FirstNode()->Node() ))
5711 if ( !polygon.myNodes.back() )
5714 meshDS->GetElementsByNodes( polygon.myNodes, adjVolumes, SMDSAbs_Volume );
5715 if ( adjVolumes.size() != 1 )
5717 if ( !adjVolumes[0]->isMarked() )
5719 boundaryElems.push_back( adjVolumes[0] );
5720 adjVolumes[0]->setIsMarked( true );
5723 bool sameShape = true;
5724 TGeomID shapeID = polygon.myNodes[0]->GetShapeID();
5725 for ( size_t i = 1; i < polygon.myNodes.size() && sameShape; ++i )
5726 sameShape = ( shapeID == polygon.myNodes[i]->GetShapeID() );
5728 if ( !sameShape || !_grid->IsSolid( shapeID ))
5729 continue; // some of shapes must be FACE
5733 faceID = getAnyFace();
5736 if ( _grid->IsInternal( faceID ) ||
5737 _grid->IsShared( faceID ) //||
5738 //_grid->IsBoundaryFace( faceID ) -- commented for #19887
5740 break; // create only if a new face will be used by other 3D algo
5743 Solid * solid = _grid->GetOneOfSolids( adjVolumes[0]->GetShapeID() );
5744 if ( !solid->IsOutsideOriented( faceID ))
5745 std::reverse( polygon.myNodes.begin(), polygon.myNodes.end() );
5747 //polygon.SetPoly( polygon.myNodes.size() > 4 );
5748 const SMDS_MeshElement* newFace = editor.AddElement( polygon.myNodes, polygon );
5749 meshDS->SetMeshElementOnShape( newFace, faceID );
5753 // return created volumes
5754 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
5756 if ( volDef ->_volume &&
5757 !volDef->_volume->IsNull() &&
5758 !volDef->_volume->isMarked() )
5760 volDef->_volume->setIsMarked( true );
5761 boundaryElems.push_back( volDef->_volume );
5763 if ( _grid->IsToCheckNodePos() ) // un-mark nodes marked in addVolumes()
5764 for ( size_t iN = 0; iN < volDef->_nodes.size(); ++iN )
5765 volDef->_nodes[iN].Node()->setIsMarked( false );
5770 //================================================================================
5772 * \brief Remove edges and nodes dividing a hexa side in the case if an adjacent
5773 * volume also sharing the dividing edge is missing due to its small side.
5776 //================================================================================
5778 void Hexahedron::removeExcessSideDivision(const vector< Hexahedron* >& allHexa)
5780 if ( ! _volumeDefs.IsPolyhedron() )
5781 return; // not a polyhedron
5783 // look for a divided side adjacent to a small hexahedron
5785 int di[6] = { 0, 0, 0, 0,-1, 1 };
5786 int dj[6] = { 0, 0,-1, 1, 0, 0 };
5787 int dk[6] = {-1, 1, 0, 0, 0, 0 };
5789 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
5791 size_t neighborIndex = _grid->CellIndex( _i + di[iF],
5794 if ( neighborIndex >= allHexa.size() ||
5795 !allHexa[ neighborIndex ] ||
5796 !allHexa[ neighborIndex ]->_hasTooSmall )
5799 // check if a side is divided into several polygons
5800 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
5802 int nbPolygons = 0, nbNodes = 0;
5803 for ( size_t i = 0; i < volDef->_names.size(); ++i )
5804 if ( volDef->_names[ i ] == _hexQuads[ iF ]._name )
5807 nbNodes += volDef->_quantities[ i ];
5809 if ( nbPolygons < 2 )
5812 // construct loops from polygons
5813 typedef _volumeDef::_linkDef TLinkDef;
5814 std::vector< TLinkDef* > loops;
5815 std::vector< TLinkDef > links( nbNodes );
5816 for ( size_t i = 0, iN = 0, iLoop = 0; iLoop < volDef->_quantities.size(); ++iLoop )
5818 size_t nbLinks = volDef->_quantities[ iLoop ];
5819 if ( volDef->_names[ iLoop ] != _hexQuads[ iF ]._name )
5824 loops.push_back( & links[i] );
5825 for ( size_t n = 0; n < nbLinks-1; ++n, ++i, ++iN )
5827 links[i].init( volDef->_nodes[iN], volDef->_nodes[iN+1], iLoop );
5828 links[i].setNext( &links[i+1] );
5830 links[i].init( volDef->_nodes[iN], volDef->_nodes[iN-nbLinks+1], iLoop );
5831 links[i].setNext( &links[i-nbLinks+1] );
5835 // look for equal links in different loops and join such loops
5836 bool loopsJoined = false;
5837 std::set< TLinkDef > linkSet;
5838 for ( size_t iLoop = 0; iLoop < loops.size(); ++iLoop )
5841 for ( TLinkDef* l = loops[ iLoop ]; l != beg; l = l->_next ) // walk around the iLoop
5843 std::pair< std::set< TLinkDef >::iterator, bool > it2new = linkSet.insert( *l );
5844 if ( !it2new.second ) // equal found, join loops
5846 const TLinkDef* equal = &(*it2new.first);
5847 if ( equal->_loopIndex == l->_loopIndex )
5852 for ( size_t i = iLoop - 1; i < loops.size(); --i )
5853 if ( loops[ i ] && loops[ i ]->_loopIndex == equal->_loopIndex )
5856 // exclude l and equal and join two loops
5857 if ( l->_prev != equal )
5858 l->_prev->setNext( equal->_next );
5859 if ( equal->_prev != l )
5860 equal->_prev->setNext( l->_next );
5862 if ( volDef->_quantities[ l->_loopIndex ] > 0 )
5863 volDef->_quantities[ l->_loopIndex ] *= -1;
5864 if ( volDef->_quantities[ equal->_loopIndex ] > 0 )
5865 volDef->_quantities[ equal->_loopIndex ] *= -1;
5867 if ( loops[ iLoop ] == l )
5868 loops[ iLoop ] = l->_prev->_next;
5870 beg = loops[ iLoop ];
5876 // set unchanged polygons
5877 std::vector< int > newQuantities;
5878 std::vector< _volumeDef::_nodeDef > newNodes;
5879 vector< SMESH_Block::TShapeID > newNames;
5880 newQuantities.reserve( volDef->_quantities.size() );
5881 newNodes.reserve ( volDef->_nodes.size() );
5882 newNames.reserve ( volDef->_names.size() );
5883 for ( size_t i = 0, iLoop = 0; iLoop < volDef->_quantities.size(); ++iLoop )
5885 if ( volDef->_quantities[ iLoop ] < 0 )
5887 i -= volDef->_quantities[ iLoop ];
5890 newQuantities.push_back( volDef->_quantities[ iLoop ]);
5891 newNodes.insert( newNodes.end(),
5892 volDef->_nodes.begin() + i,
5893 volDef->_nodes.begin() + i + newQuantities.back() );
5894 newNames.push_back( volDef->_names[ iLoop ]);
5895 i += volDef->_quantities[ iLoop ];
5899 for ( size_t iLoop = 0; iLoop < loops.size(); ++iLoop )
5901 if ( !loops[ iLoop ] )
5903 newQuantities.push_back( 0 );
5905 for ( TLinkDef* l = loops[ iLoop ]; l != beg; l = l->_next, ++newQuantities.back() )
5907 newNodes.push_back( l->_node1 );
5908 beg = loops[ iLoop ];
5910 newNames.push_back( _hexQuads[ iF ]._name );
5912 volDef->_quantities.swap( newQuantities );
5913 volDef->_nodes.swap( newNodes );
5914 volDef->_names.swap( newNames );
5916 } // loop on volDef's
5917 } // loop on hex sides
5920 } // removeExcessSideDivision()
5923 //================================================================================
5925 * \brief Remove nodes splitting Cartesian cell edges in the case if a node
5926 * is used in every cells only by two polygons sharing the edge
5929 //================================================================================
5931 void Hexahedron::removeExcessNodes(vector< Hexahedron* >& allHexa)
5933 if ( ! _volumeDefs.IsPolyhedron() )
5934 return; // not a polyhedron
5936 typedef vector< _volumeDef::_nodeDef >::iterator TNodeIt;
5937 vector< int > nodesInPoly[ 4 ]; // node index in _volumeDefs._nodes
5938 vector< int > volDefInd [ 4 ]; // index of a _volumeDefs
5939 Hexahedron* hexa [ 4 ];
5940 int i,j,k, cellIndex, iLink = 0, iCellLink;
5941 for ( int iDir = 0; iDir < 3; ++iDir )
5943 CellsAroundLink fourCells( _grid, iDir );
5944 for ( int iL = 0; iL < 4; ++iL, ++iLink ) // 4 links in a direction
5946 _Link& link = _hexLinks[ iLink ];
5947 fourCells.Init( _i, _j, _k, iLink );
5949 for ( size_t iP = 0; iP < link._fIntPoints.size(); ++iP ) // loop on nodes on the link
5951 bool nodeRemoved = true;
5952 _volumeDef::_nodeDef node; node._intPoint = link._fIntPoints[iP];
5954 for ( size_t i = 0, nb = _volumeDefs.size(); i < nb && nodeRemoved; ++i )
5955 if ( _volumeDef* vol = _volumeDefs.at( i ))
5957 ( std::find( vol->_nodes.begin(), vol->_nodes.end(), node ) == vol->_nodes.end() );
5959 continue; // node already removed
5961 // check if a node encounters zero or two times in 4 cells sharing iLink
5962 // if so, the node can be removed from the cells
5963 bool nodeIsOnEdge = true;
5964 int nbPolyhedraWithNode = 0;
5965 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing a link
5967 nodesInPoly[ iC ].clear();
5968 volDefInd [ iC ].clear();
5970 if ( !fourCells.GetCell( iC, i,j,k, cellIndex, iCellLink ))
5972 hexa[ iC ] = allHexa[ cellIndex ];
5975 for ( size_t i = 0, nb = hexa[ iC ]->_volumeDefs.size(); i < nb; ++i )
5976 if ( _volumeDef* vol = hexa[ iC ]->_volumeDefs.at( i ))
5978 for ( TNodeIt nIt = vol->_nodes.begin(); nIt != vol->_nodes.end(); ++nIt )
5980 nIt = std::find( nIt, vol->_nodes.end(), node );
5981 if ( nIt != vol->_nodes.end() )
5983 nodesInPoly[ iC ].push_back( std::distance( vol->_nodes.begin(), nIt ));
5984 volDefInd [ iC ].push_back( i );
5989 nbPolyhedraWithNode += ( !nodesInPoly[ iC ].empty() );
5991 if ( nodesInPoly[ iC ].size() != 0 &&
5992 nodesInPoly[ iC ].size() != 2 )
5994 nodeIsOnEdge = false;
5997 } // loop on 4 cells
5999 // remove nodes from polyhedra
6000 if ( nbPolyhedraWithNode > 0 && nodeIsOnEdge )
6002 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing the link
6004 if ( nodesInPoly[ iC ].empty() )
6006 for ( int i = volDefInd[ iC ].size() - 1; i >= 0; --i )
6008 _volumeDef* vol = hexa[ iC ]->_volumeDefs.at( volDefInd[ iC ][ i ]);
6009 int nIndex = nodesInPoly[ iC ][ i ];
6010 // decrement _quantities
6011 for ( size_t iQ = 0; iQ < vol->_quantities.size(); ++iQ )
6012 if ( nIndex < vol->_quantities[ iQ ])
6014 vol->_quantities[ iQ ]--;
6019 nIndex -= vol->_quantities[ iQ ];
6021 vol->_nodes.erase( vol->_nodes.begin() + nodesInPoly[ iC ][ i ]);
6024 vol->_nodes.size() == 6 * 4 &&
6025 vol->_quantities.size() == 6 ) // polyhedron becomes hexahedron?
6027 bool allQuads = true;
6028 for ( size_t iQ = 0; iQ < vol->_quantities.size() && allQuads; ++iQ )
6029 allQuads = ( vol->_quantities[ iQ ] == 4 );
6032 // set side nodes as this: bottom, top, top, ...
6033 int iTop = 0, iBot = 0; // side indices
6034 for ( int iS = 0; iS < 6; ++iS )
6036 if ( vol->_names[ iS ] == SMESH_Block::ID_Fxy0 )
6038 if ( vol->_names[ iS ] == SMESH_Block::ID_Fxy1 )
6045 std::copy( vol->_nodes.begin(),
6046 vol->_nodes.begin() + 4,
6047 vol->_nodes.begin() + 4 );
6050 std::copy( vol->_nodes.begin() + 4 * iBot,
6051 vol->_nodes.begin() + 4 * ( iBot + 1),
6052 vol->_nodes.begin() );
6055 std::copy( vol->_nodes.begin() + 4 * iTop,
6056 vol->_nodes.begin() + 4 * ( iTop + 1),
6057 vol->_nodes.begin() + 4 );
6059 std::copy( vol->_nodes.begin() + 4,
6060 vol->_nodes.begin() + 8,
6061 vol->_nodes.begin() + 8 );
6062 // set up top facet nodes by comparing their uvw with bottom nodes
6063 E_IntersectPoint ip[8];
6064 for ( int iN = 0; iN < 8; ++iN )
6066 SMESH_NodeXYZ p = vol->_nodes[ iN ].Node();
6067 _grid->ComputeUVW( p, ip[ iN ]._uvw );
6069 const double tol2 = _grid->_tol * _grid->_tol;
6070 for ( int iN = 0; iN < 4; ++iN )
6072 gp_Pnt2d pBot( ip[ iN ]._uvw[0], ip[ iN ]._uvw[1] );
6073 for ( int iT = 4; iT < 8; ++iT )
6075 gp_Pnt2d pTop( ip[ iT ]._uvw[0], ip[ iT ]._uvw[1] );
6076 if ( pBot.SquareDistance( pTop ) < tol2 )
6078 // vol->_nodes[ iN + 4 ]._node = ip[ iT ]._node;
6079 // vol->_nodes[ iN + 4 ]._intPoint = 0;
6080 vol->_nodes[ iN + 4 ] = vol->_nodes[ iT + 4 ];
6085 vol->_nodes.resize( 8 );
6086 vol->_quantities.clear();
6087 //vol->_names.clear();
6090 } // loop on _volumeDefs
6091 } // loop on 4 cell abound a link
6092 } // if ( nodeIsOnEdge )
6093 } // loop on intersection points of a link
6094 } // loop on 4 links of a direction
6095 } // loop on 3 directions
6099 } // removeExcessNodes()
6101 //================================================================================
6103 * \brief [Issue #19913] Modify _hexLinks._splits to prevent creating overlapping volumes
6105 //================================================================================
6107 void Hexahedron::preventVolumesOverlapping()
6109 // Cut off a quadrangle corner if two links sharing the corner
6110 // are shared by same two solids, in this case each of solids gets
6111 // a triangle for it-self.
6112 std::vector< TGeomID > soIDs[4];
6113 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
6115 _Face& quad = _hexQuads[ iF ] ;
6117 int iFOpposite = iF + ( iF % 2 ? -1 : 1 );
6118 _Face& quadOpp = _hexQuads[ iFOpposite ] ;
6120 int nbSides = 0, nbSidesOpp = 0;
6121 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
6123 nbSides += ( quad._links [ iE ].NbResultLinks() > 0 );
6124 nbSidesOpp += ( quadOpp._links[ iE ].NbResultLinks() > 0 );
6126 if ( nbSides < 4 || nbSidesOpp != 2 )
6129 for ( int iE = 0; iE < 4; ++iE )
6131 soIDs[ iE ].clear();
6132 _Node* n = quad._links[ iE ].FirstNode();
6133 if ( n->_intPoint && n->_intPoint->_faceIDs.size() )
6134 soIDs[ iE ] = _grid->GetSolidIDs( n->_intPoint->_faceIDs[0] );
6136 if ((( soIDs[0].size() >= 2 ) +
6137 ( soIDs[1].size() >= 2 ) +
6138 ( soIDs[2].size() >= 2 ) +
6139 ( soIDs[3].size() >= 2 ) ) < 3 )
6143 for ( int i = 0; i < 4; ++i )
6145 int i1 = _grid->_helper->WrapIndex( i + 1, 4 );
6146 int i2 = _grid->_helper->WrapIndex( i + 2, 4 );
6147 int i3 = _grid->_helper->WrapIndex( i + 3, 4 );
6148 if ( soIDs[i1].size() == 2 && soIDs[i ] != soIDs[i1] &&
6149 soIDs[i2].size() == 2 && soIDs[i1] == soIDs[i2] &&
6150 soIDs[i3].size() == 2 && soIDs[i2] == soIDs[i3] )
6152 quad._links[ i1 ]._link->_splits.clear();
6153 quad._links[ i2 ]._link->_splits.clear();
6162 } // preventVolumesOverlapping()
6164 //================================================================================
6166 * \brief Set to _hexLinks a next portion of splits located on one side of INTERNAL FACEs
6168 bool Hexahedron::_SplitIterator::Next()
6170 if ( _iterationNb > 0 )
6171 // count used splits
6172 for ( size_t i = 0; i < _splits.size(); ++i )
6174 if ( _splits[i]._iCheckIteration == _iterationNb )
6176 _splits[i]._isUsed = _splits[i]._checkedSplit->_faces[1];
6177 _nbUsed += _splits[i]._isUsed;
6185 bool toTestUsed = ( _nbChecked >= _splits.size() );
6188 // all splits are checked; find all not used splits
6189 for ( size_t i = 0; i < _splits.size(); ++i )
6190 if ( !_splits[i].IsCheckedOrUsed( toTestUsed ))
6191 _splits[i]._iCheckIteration = _iterationNb;
6193 _nbUsed = _splits.size(); // to stop iteration
6197 // get any not used/checked split to start from
6199 for ( size_t i = 0; i < _splits.size(); ++i )
6201 if ( !_splits[i].IsCheckedOrUsed( toTestUsed ))
6203 _freeNodes.push_back( _splits[i]._nodes[0] );
6204 _freeNodes.push_back( _splits[i]._nodes[1] );
6205 _splits[i]._iCheckIteration = _iterationNb;
6209 // find splits connected to the start one via _freeNodes
6210 for ( size_t iN = 0; iN < _freeNodes.size(); ++iN )
6212 for ( size_t iS = 0; iS < _splits.size(); ++iS )
6214 if ( _splits[iS].IsCheckedOrUsed( toTestUsed ))
6217 if ( _freeNodes[iN] == _splits[iS]._nodes[0] )
6219 else if ( _freeNodes[iN] == _splits[iS]._nodes[1] )
6223 if ( _freeNodes[iN]->_isInternalFlags > 0 )
6225 if ( _splits[iS]._nodes[ iN2 ]->_isInternalFlags == 0 )
6227 if ( !_splits[iS]._nodes[ iN2 ]->IsLinked( _freeNodes[iN]->_intPoint ))
6230 _splits[iS]._iCheckIteration = _iterationNb;
6231 _freeNodes.push_back( _splits[iS]._nodes[ iN2 ]);
6235 // set splits to hex links
6237 for ( int iL = 0; iL < 12; ++iL )
6238 _hexLinks[ iL ]._splits.clear();
6241 for ( size_t i = 0; i < _splits.size(); ++i )
6243 if ( _splits[i]._iCheckIteration == _iterationNb )
6245 split._nodes[0] = _splits[i]._nodes[0];
6246 split._nodes[1] = _splits[i]._nodes[1];
6247 _Link & hexLink = _hexLinks[ _splits[i]._linkID ];
6248 hexLink._splits.push_back( split );
6249 _splits[i]._checkedSplit = & hexLink._splits.back();
6256 //================================================================================
6258 * \brief computes exact bounding box with axes parallel to given ones
6260 //================================================================================
6262 void getExactBndBox( const vector< TopoDS_Shape >& faceVec,
6263 const double* axesDirs,
6267 TopoDS_Compound allFacesComp;
6268 b.MakeCompound( allFacesComp );
6269 for ( size_t iF = 0; iF < faceVec.size(); ++iF )
6270 b.Add( allFacesComp, faceVec[ iF ] );
6272 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
6273 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
6275 for ( int i = 0; i < 6; ++i )
6276 farDist = Max( farDist, 10 * sP[i] );
6278 gp_XYZ axis[3] = { gp_XYZ( axesDirs[0], axesDirs[1], axesDirs[2] ),
6279 gp_XYZ( axesDirs[3], axesDirs[4], axesDirs[5] ),
6280 gp_XYZ( axesDirs[6], axesDirs[7], axesDirs[8] ) };
6281 axis[0].Normalize();
6282 axis[1].Normalize();
6283 axis[2].Normalize();
6285 gp_Mat basis( axis[0], axis[1], axis[2] );
6286 gp_Mat bi = basis.Inverted();
6289 for ( int iDir = 0; iDir < 3; ++iDir )
6291 gp_XYZ axis0 = axis[ iDir ];
6292 gp_XYZ axis1 = axis[ ( iDir + 1 ) % 3 ];
6293 gp_XYZ axis2 = axis[ ( iDir + 2 ) % 3 ];
6294 for ( int isMax = 0; isMax < 2; ++isMax )
6296 double shift = isMax ? farDist : -farDist;
6297 gp_XYZ orig = shift * axis0;
6298 gp_XYZ norm = axis1 ^ axis2;
6299 gp_Pln pln( orig, norm );
6300 norm = pln.Axis().Direction().XYZ();
6301 BRepBuilderAPI_MakeFace plane( pln, -farDist, farDist, -farDist, farDist );
6303 gp_Pnt& pAxis = isMax ? pMax : pMin;
6304 gp_Pnt pPlane, pFaces;
6305 double dist = GEOMUtils::GetMinDistance( plane, allFacesComp, pPlane, pFaces );
6310 for ( int i = 0; i < 2; ++i ) {
6311 corner.SetCoord( 1, sP[ i*3 ]);
6312 for ( int j = 0; j < 2; ++j ) {
6313 corner.SetCoord( 2, sP[ i*3 + 1 ]);
6314 for ( int k = 0; k < 2; ++k )
6316 corner.SetCoord( 3, sP[ i*3 + 2 ]);
6322 corner = isMax ? bb.CornerMax() : bb.CornerMin();
6323 pAxis.SetCoord( iDir+1, corner.Coord( iDir+1 ));
6327 gp_XYZ pf = pFaces.XYZ() * bi;
6328 pAxis.SetCoord( iDir+1, pf.Coord( iDir+1 ) );
6334 shapeBox.Add( pMin );
6335 shapeBox.Add( pMax );
6342 //=============================================================================
6344 * \brief Generates 3D structured Cartesian mesh in the internal part of
6345 * solid shapes and polyhedral volumes near the shape boundary.
6346 * \param theMesh - mesh to fill in
6347 * \param theShape - a compound of all SOLIDs to mesh
6348 * \retval bool - true in case of success
6350 //=============================================================================
6352 bool StdMeshers_Cartesian_3D::Compute(SMESH_Mesh & theMesh,
6353 const TopoDS_Shape & theShape)
6355 // The algorithm generates the mesh in following steps:
6357 // 1) Intersection of grid lines with the geometry boundary.
6358 // This step allows to find out if a given node of the initial grid is
6359 // inside or outside the geometry.
6361 // 2) For each cell of the grid, check how many of it's nodes are outside
6362 // of the geometry boundary. Depending on a result of this check
6363 // - skip a cell, if all it's nodes are outside
6364 // - skip a cell, if it is too small according to the size threshold
6365 // - add a hexahedron in the mesh, if all nodes are inside
6366 // - add a polyhedron in the mesh, if some nodes are inside and some outside
6368 _computeCanceled = false;
6370 SMESH_MesherHelper helper( theMesh );
6371 SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
6376 grid._helper = &helper;
6377 grid._toAddEdges = _hyp->GetToAddEdges();
6378 grid._toCreateFaces = _hyp->GetToCreateFaces();
6379 grid._toConsiderInternalFaces = _hyp->GetToConsiderInternalFaces();
6380 grid._toUseThresholdForInternalFaces = _hyp->GetToUseThresholdForInternalFaces();
6381 grid._sizeThreshold = _hyp->GetSizeThreshold();
6382 grid.InitGeometry( theShape );
6384 vector< TopoDS_Shape > faceVec;
6386 TopTools_MapOfShape faceMap;
6387 TopExp_Explorer fExp;
6388 for ( fExp.Init( theShape, TopAbs_FACE ); fExp.More(); fExp.Next() )
6390 bool isNewFace = faceMap.Add( fExp.Current() );
6391 if ( !grid._toConsiderInternalFaces )
6392 if ( !isNewFace || fExp.Current().Orientation() == TopAbs_INTERNAL )
6393 // remove an internal face
6394 faceMap.Remove( fExp.Current() );
6396 faceVec.reserve( faceMap.Extent() );
6397 faceVec.assign( faceMap.cbegin(), faceMap.cend() );
6399 vector<FaceGridIntersector> facesItersectors( faceVec.size() );
6401 for ( size_t i = 0; i < faceVec.size(); ++i )
6403 facesItersectors[i]._face = TopoDS::Face( faceVec[i] );
6404 facesItersectors[i]._faceID = grid.ShapeID( faceVec[i] );
6405 facesItersectors[i]._grid = &grid;
6406 shapeBox.Add( facesItersectors[i].GetFaceBndBox() );
6408 getExactBndBox( faceVec, _hyp->GetAxisDirs(), shapeBox );
6411 vector<double> xCoords, yCoords, zCoords;
6412 _hyp->GetCoordinates( xCoords, yCoords, zCoords, shapeBox );
6414 grid.SetCoordinates( xCoords, yCoords, zCoords, _hyp->GetAxisDirs(), shapeBox );
6416 if ( _computeCanceled ) return false;
6419 { // copy partner faces and curves of not thread-safe types
6420 set< const Standard_Transient* > tshapes;
6421 BRepBuilderAPI_Copy copier;
6422 for ( size_t i = 0; i < facesItersectors.size(); ++i )
6424 if ( !facesItersectors[i].IsThreadSafe( tshapes ))
6426 copier.Perform( facesItersectors[i]._face );
6427 facesItersectors[i]._face = TopoDS::Face( copier );
6431 // Intersection of grid lines with the geometry boundary.
6432 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, facesItersectors.size() ),
6433 ParallelIntersector( facesItersectors ),
6434 tbb::simple_partitioner());
6436 for ( size_t i = 0; i < facesItersectors.size(); ++i )
6437 facesItersectors[i].Intersect();
6440 // put intersection points onto the GridLine's; this is done after intersection
6441 // to avoid contention of facesItersectors for writing into the same GridLine
6442 // in case of parallel work of facesItersectors
6443 for ( size_t i = 0; i < facesItersectors.size(); ++i )
6444 facesItersectors[i].StoreIntersections();
6446 if ( _computeCanceled ) return false;
6448 // create nodes on the geometry
6449 grid.ComputeNodes( helper );
6451 if ( _computeCanceled ) return false;
6453 // get EDGEs to take into account
6454 map< TGeomID, vector< TGeomID > > edge2faceIDsMap;
6455 grid.GetEdgesToImplement( edge2faceIDsMap, theShape, faceVec );
6457 // create volume elements
6458 Hexahedron hex( &grid );
6459 int nbAdded = hex.MakeElements( helper, edge2faceIDsMap );
6463 if ( !grid._toConsiderInternalFaces )
6465 // make all SOLIDs computed
6466 TopExp_Explorer solidExp( theShape, TopAbs_SOLID );
6467 if ( SMESHDS_SubMesh* sm1 = meshDS->MeshElements( solidExp.Current()) )
6469 SMDS_ElemIteratorPtr volIt = sm1->GetElements();
6470 for ( ; solidExp.More() && volIt->more(); solidExp.Next() )
6472 const SMDS_MeshElement* vol = volIt->next();
6473 sm1->RemoveElement( vol );
6474 meshDS->SetMeshElementOnShape( vol, solidExp.Current() );
6478 // make other sub-shapes computed
6479 setSubmeshesComputed( theMesh, theShape );
6482 // remove free nodes
6483 //if ( SMESHDS_SubMesh * smDS = meshDS->MeshElements( helper.GetSubShapeID() ))
6485 std::vector< const SMDS_MeshNode* > nodesToRemove;
6486 // get intersection nodes
6487 for ( int iDir = 0; iDir < 3; ++iDir )
6489 vector< GridLine >& lines = grid._lines[ iDir ];
6490 for ( size_t i = 0; i < lines.size(); ++i )
6492 multiset< F_IntersectPoint >::iterator ip = lines[i]._intPoints.begin();
6493 for ( ; ip != lines[i]._intPoints.end(); ++ip )
6495 !ip->_node->IsNull() &&
6496 ip->_node->NbInverseElements() == 0 &&
6497 !ip->_node->isMarked() )
6499 nodesToRemove.push_back( ip->_node );
6500 ip->_node->setIsMarked( true );
6505 for ( size_t i = 0; i < grid._nodes.size(); ++i )
6506 if ( grid._nodes[i] &&
6507 !grid._nodes[i]->IsNull() &&
6508 grid._nodes[i]->NbInverseElements() == 0 &&
6509 !grid._nodes[i]->isMarked() )
6511 nodesToRemove.push_back( grid._nodes[i] );
6512 grid._nodes[i]->setIsMarked( true );
6516 for ( size_t i = 0; i < nodesToRemove.size(); ++i )
6517 meshDS->RemoveFreeNode( nodesToRemove[i], /*smD=*/0, /*fromGroups=*/false );
6523 // SMESH_ComputeError is not caught at SMESH_submesh level for an unknown reason
6524 catch ( SMESH_ComputeError& e)
6526 return error( SMESH_ComputeErrorPtr( new SMESH_ComputeError( e )));
6531 //=============================================================================
6535 //=============================================================================
6537 bool StdMeshers_Cartesian_3D::Evaluate(SMESH_Mesh & /*theMesh*/,
6538 const TopoDS_Shape & /*theShape*/,
6539 MapShapeNbElems& /*theResMap*/)
6542 // std::vector<int> aResVec(SMDSEntity_Last);
6543 // for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
6544 // if(IsQuadratic) {
6545 // aResVec[SMDSEntity_Quad_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
6546 // int nb1d_face0_int = ( nb2d_face0*4 - nb1d ) / 2;
6547 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
6550 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
6551 // aResVec[SMDSEntity_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
6553 // SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
6554 // aResMap.insert(std::make_pair(sm,aResVec));
6559 //=============================================================================
6563 * \brief Event listener setting/unsetting _alwaysComputed flag to
6564 * submeshes of inferior levels to prevent their computing
6566 struct _EventListener : public SMESH_subMeshEventListener
6570 _EventListener(const string& algoName):
6571 SMESH_subMeshEventListener(/*isDeletable=*/true,"StdMeshers_Cartesian_3D::_EventListener"),
6574 // --------------------------------------------------------------------------------
6575 // setting/unsetting _alwaysComputed flag to submeshes of inferior levels
6577 static void setAlwaysComputed( const bool isComputed,
6578 SMESH_subMesh* subMeshOfSolid)
6580 SMESH_subMeshIteratorPtr smIt =
6581 subMeshOfSolid->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
6582 while ( smIt->more() )
6584 SMESH_subMesh* sm = smIt->next();
6585 sm->SetIsAlwaysComputed( isComputed );
6587 subMeshOfSolid->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
6590 // --------------------------------------------------------------------------------
6591 // unsetting _alwaysComputed flag if "Cartesian_3D" was removed
6593 virtual void ProcessEvent(const int /*event*/,
6594 const int eventType,
6595 SMESH_subMesh* subMeshOfSolid,
6596 SMESH_subMeshEventListenerData* /*data*/,
6597 const SMESH_Hypothesis* /*hyp*/ = 0)
6599 if ( eventType == SMESH_subMesh::COMPUTE_EVENT )
6601 setAlwaysComputed( subMeshOfSolid->GetComputeState() == SMESH_subMesh::COMPUTE_OK,
6606 SMESH_Algo* algo3D = subMeshOfSolid->GetAlgo();
6607 if ( !algo3D || _algoName != algo3D->GetName() )
6608 setAlwaysComputed( false, subMeshOfSolid );
6612 // --------------------------------------------------------------------------------
6613 // set the event listener
6615 static void SetOn( SMESH_subMesh* subMeshOfSolid, const string& algoName )
6617 subMeshOfSolid->SetEventListener( new _EventListener( algoName ),
6622 }; // struct _EventListener
6626 //================================================================================
6628 * \brief Sets event listener to submeshes if necessary
6629 * \param subMesh - submesh where algo is set
6630 * This method is called when a submesh gets HYP_OK algo_state.
6631 * After being set, event listener is notified on each event of a submesh.
6633 //================================================================================
6635 void StdMeshers_Cartesian_3D::SetEventListener(SMESH_subMesh* subMesh)
6637 _EventListener::SetOn( subMesh, GetName() );
6640 //================================================================================
6642 * \brief Set _alwaysComputed flag to submeshes of inferior levels to avoid their computing
6644 //================================================================================
6646 void StdMeshers_Cartesian_3D::setSubmeshesComputed(SMESH_Mesh& theMesh,
6647 const TopoDS_Shape& theShape)
6649 for ( TopExp_Explorer soExp( theShape, TopAbs_SOLID ); soExp.More(); soExp.Next() )
6650 _EventListener::setAlwaysComputed( true, theMesh.GetSubMesh( soExp.Current() ));