1 // Copyright (C) 2007-2023 CEA, EDF, 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"
27 #include "StdMeshers_Cartesian_VL.hxx"
28 #include "StdMeshers_FaceSide.hxx"
29 #include "StdMeshers_ViscousLayers.hxx"
31 #include <ObjectPool.hxx>
32 #include <SMDS_LinearEdge.hxx>
33 #include <SMDS_MeshNode.hxx>
34 #include <SMDS_VolumeOfNodes.hxx>
35 #include <SMDS_VolumeTool.hxx>
36 #include <SMESHDS_Mesh.hxx>
37 #include <SMESH_Block.hxx>
38 #include <SMESH_Comment.hxx>
39 #include <SMESH_ControlsDef.hxx>
40 #include <SMESH_Mesh.hxx>
41 #include <SMESH_MeshAlgos.hxx>
42 #include <SMESH_MeshEditor.hxx>
43 #include <SMESH_MesherHelper.hxx>
44 #include <SMESH_subMesh.hxx>
45 #include <SMESH_subMeshEventListener.hxx>
47 #include <utilities.h>
48 #include <Utils_ExceptHandlers.hxx>
50 #include <GEOMUtils.hxx>
52 #include <BRepAdaptor_Curve.hxx>
53 #include <BRepAdaptor_Surface.hxx>
54 #include <BRepBndLib.hxx>
55 #include <BRepBuilderAPI_Copy.hxx>
56 #include <BRepBuilderAPI_MakeFace.hxx>
57 #include <BRepTools.hxx>
58 #include <BRepTopAdaptor_FClass2d.hxx>
59 #include <BRep_Builder.hxx>
60 #include <BRep_Tool.hxx>
61 #include <Bnd_B3d.hxx>
62 #include <Bnd_Box.hxx>
64 #include <GCPnts_UniformDeflection.hxx>
65 #include <Geom2d_BSplineCurve.hxx>
66 #include <Geom2d_BezierCurve.hxx>
67 #include <Geom2d_TrimmedCurve.hxx>
68 #include <GeomAPI_ProjectPointOnSurf.hxx>
69 #include <GeomLib.hxx>
70 #include <Geom_BSplineCurve.hxx>
71 #include <Geom_BSplineSurface.hxx>
72 #include <Geom_BezierCurve.hxx>
73 #include <Geom_BezierSurface.hxx>
74 #include <Geom_RectangularTrimmedSurface.hxx>
75 #include <Geom_TrimmedCurve.hxx>
76 #include <IntAna_IntConicQuad.hxx>
77 #include <IntAna_IntLinTorus.hxx>
78 #include <IntAna_Quadric.hxx>
79 #include <IntCurveSurface_TransitionOnCurve.hxx>
80 #include <IntCurvesFace_Intersector.hxx>
81 #include <Poly_Triangulation.hxx>
82 #include <Precision.hxx>
84 #include <TopExp_Explorer.hxx>
85 #include <TopLoc_Location.hxx>
86 #include <TopTools_DataMapOfShapeInteger.hxx>
87 #include <TopTools_IndexedMapOfShape.hxx>
88 #include <TopTools_MapOfShape.hxx>
90 #include <TopoDS_Compound.hxx>
91 #include <TopoDS_Face.hxx>
92 #include <TopoDS_TShape.hxx>
93 #include <gp_Cone.hxx>
94 #include <gp_Cylinder.hxx>
97 #include <gp_Pnt2d.hxx>
98 #include <gp_Sphere.hxx>
99 #include <gp_Torus.hxx>
103 #include <boost/container/flat_map.hpp>
106 // #define _MY_DEBUG_
113 // See https://docs.microsoft.com/en-gb/cpp/porting/modifying-winver-and-win32-winnt?view=vs-2019
114 // Windows 10 = 0x0A00
115 #define WINVER 0x0A00
116 #define _WIN32_WINNT 0x0A00
119 #include <tbb/parallel_for.h>
120 //#include <tbb/enumerable_thread_specific.h>
124 using namespace SMESH;
126 //=============================================================================
130 //=============================================================================
132 StdMeshers_Cartesian_3D::StdMeshers_Cartesian_3D(int hypId, SMESH_Gen * gen)
133 :SMESH_3D_Algo(hypId, gen)
135 _name = "Cartesian_3D";
136 _shapeType = (1 << TopAbs_SOLID); // 1 bit /shape type
137 _compatibleHypothesis.push_back( "CartesianParameters3D" );
138 _compatibleHypothesis.push_back( StdMeshers_ViscousLayers::GetHypType() );
140 _onlyUnaryInput = false; // to mesh all SOLIDs at once
141 _requireDiscreteBoundary = false; // 2D mesh not needed
142 _supportSubmeshes = false; // do not use any existing mesh
145 //=============================================================================
147 * Check presence of a hypothesis
149 //=============================================================================
151 bool StdMeshers_Cartesian_3D::CheckHypothesis (SMESH_Mesh& aMesh,
152 const TopoDS_Shape& aShape,
153 Hypothesis_Status& aStatus)
155 aStatus = SMESH_Hypothesis::HYP_MISSING;
157 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, /*skipAux=*/false);
158 list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
159 if ( h == hyps.end())
165 _hypViscousLayers = nullptr;
166 _isComputeOffset = false;
168 for ( ; h != hyps.end(); ++h )
170 if ( !_hyp && ( _hyp = dynamic_cast<const StdMeshers_CartesianParameters3D*>( *h )))
172 aStatus = _hyp->IsDefined() ? HYP_OK : HYP_BAD_PARAMETER;
176 _hypViscousLayers = dynamic_cast<const StdMeshers_ViscousLayers*>( *h );
180 return aStatus == HYP_OK;
186 * \brief Temporary mesh to hold
188 struct TmpMesh: public SMESH_Mesh
191 _isShapeToMesh = (_id = 0);
192 _meshDS = new SMESHDS_Mesh( _id, true );
196 typedef int TGeomID; // IDs of sub-shapes
197 typedef TopTools_ShapeMapHasher TShapeHasher; // non-oriented shape hasher
198 typedef std::array< int, 3 > TIJK;
200 const TGeomID theUndefID = 1e+9;
202 //=============================================================================
203 // Definitions of internal utils
204 // --------------------------------------------------------------------------
206 Trans_TANGENT = IntCurveSurface_Tangent,
207 Trans_IN = IntCurveSurface_In,
208 Trans_OUT = IntCurveSurface_Out,
210 Trans_INTERNAL // for INTERNAL FACE
212 // --------------------------------------------------------------------------
214 * \brief Sub-entities of a FACE neighboring its concave VERTEX.
215 * Help to avoid linking nodes on EDGEs that seem connected
216 * by the concave FACE but the link actually lies outside the FACE
220 TGeomID _concaveFace;
221 TGeomID _edge1, _edge2;
223 ConcaveFace( int f=0, int e1=0, int e2=0, int v1=0, int v2=0 )
224 : _concaveFace(f), _edge1(e1), _edge2(e2), _v1(v1), _v2(v2) {}
225 bool HasEdge( TGeomID edge ) const { return edge == _edge1 || edge == _edge2; }
226 bool HasVertex( TGeomID v ) const { return v == _v1 || v == _v2; }
227 void SetEdge( TGeomID edge ) { ( _edge1 ? _edge2 : _edge1 ) = edge; }
228 void SetVertex( TGeomID v ) { ( _v1 ? _v2 : _v1 ) = v; }
230 typedef NCollection_DataMap< TGeomID, ConcaveFace > TConcaveVertex2Face;
231 // --------------------------------------------------------------------------
233 * \brief Container of IDs of SOLID sub-shapes
235 class Solid // sole SOLID contains all sub-shapes
237 TGeomID _id; // SOLID id
238 bool _hasInternalFaces;
239 TConcaveVertex2Face _concaveVertex; // concave VERTEX -> ConcaveFace
242 virtual bool Contains( TGeomID /*subID*/ ) const { return true; }
243 virtual bool ContainsAny( const vector< TGeomID>& /*subIDs*/ ) const { return true; }
244 virtual TopAbs_Orientation Orientation( const TopoDS_Shape& s ) const { return s.Orientation(); }
245 virtual bool IsOutsideOriented( TGeomID /*faceID*/ ) const { return true; }
246 void SetID( TGeomID id ) { _id = id; }
247 TGeomID ID() const { return _id; }
248 void SetHasInternalFaces( bool has ) { _hasInternalFaces = has; }
249 bool HasInternalFaces() const { return _hasInternalFaces; }
250 void SetConcave( TGeomID V, TGeomID F, TGeomID E1, TGeomID E2, TGeomID V1, TGeomID V2 )
251 { _concaveVertex.Bind( V, ConcaveFace{ F, E1, E2, V1, V2 }); }
252 bool HasConcaveVertex() const { return !_concaveVertex.IsEmpty(); }
253 const ConcaveFace* GetConcave( TGeomID V ) const { return _concaveVertex.Seek( V ); }
255 // --------------------------------------------------------------------------
256 class OneOfSolids : public Solid
258 TColStd_MapOfInteger _subIDs;
259 TopTools_MapOfShape _faces; // keep FACE orientation
260 TColStd_MapOfInteger _outFaceIDs; // FACEs of shape_to_mesh oriented outside the SOLID
262 void Init( const TopoDS_Shape& solid,
263 TopAbs_ShapeEnum subType,
264 const SMESHDS_Mesh* mesh );
265 virtual bool Contains( TGeomID i ) const { return i == ID() || _subIDs.Contains( i ); }
266 virtual bool ContainsAny( const vector< TGeomID>& subIDs ) const
268 for ( size_t i = 0; i < subIDs.size(); ++i ) if ( Contains( subIDs[ i ])) return true;
271 virtual TopAbs_Orientation Orientation( const TopoDS_Shape& face ) const
273 const TopoDS_Shape& sInMap = const_cast< OneOfSolids* >(this)->_faces.Added( face );
274 return sInMap.Orientation();
276 virtual bool IsOutsideOriented( TGeomID faceID ) const
278 return faceID == 0 || _outFaceIDs.Contains( faceID );
281 // --------------------------------------------------------------------------
283 * \brief Hold a vector of TGeomID and clear it at destruction
285 class GeomIDVecHelder
287 typedef std::vector< TGeomID > TVector;
288 const TVector& myVec;
292 GeomIDVecHelder( const TVector& idVec, bool isOwner ): myVec( idVec ), myOwn( isOwner ) {}
293 GeomIDVecHelder( const GeomIDVecHelder& holder ): myVec( holder.myVec ), myOwn( holder.myOwn )
295 const_cast< bool& >( holder.myOwn ) = false;
297 ~GeomIDVecHelder() { if ( myOwn ) const_cast<TVector&>( myVec ).clear(); }
298 size_t size() const { return myVec.size(); }
299 TGeomID operator[]( size_t i ) const { return i < size() ? myVec[i] : theUndefID; }
300 bool operator==( const GeomIDVecHelder& other ) const { return myVec == other.myVec; }
301 bool contain( const TGeomID& id ) const {
302 return std::find( myVec.begin(), myVec.end(), id ) != myVec.end();
304 TGeomID otherThan( const TGeomID& id ) const {
305 for ( const TGeomID& id2 : myVec )
310 TGeomID oneCommon( const GeomIDVecHelder& other ) const {
311 TGeomID common = theUndefID;
312 for ( const TGeomID& id : myVec )
313 if ( other.contain( id ))
315 if ( common != theUndefID )
322 // --------------------------------------------------------------------------
328 TopoDS_Shape _mainShape;
329 vector< vector< TGeomID > > _solidIDsByShapeID;// V/E/F ID -> SOLID IDs
331 map< TGeomID, OneOfSolids > _solidByID;
332 TColStd_MapOfInteger _boundaryFaces; // FACEs on boundary of mesh->ShapeToMesh()
333 TColStd_MapOfInteger _strangeEdges; // EDGEs shared by strange FACEs
334 TGeomID _extIntFaceID; // pseudo FACE - extension of INTERNAL FACE
336 TopTools_DataMapOfShapeInteger _shape2NbNodes; // nb of pre-existing nodes on shapes
338 Controls::ElementsOnShape _edgeClassifier;
339 Controls::ElementsOnShape _vertexClassifier;
341 bool IsOneSolid() const { return _solidByID.size() < 2; }
342 GeomIDVecHelder GetSolidIDsByShapeID( const vector< TGeomID >& shapeIDs ) const;
344 // --------------------------------------------------------------------------
346 * \brief Common data of any intersection between a Grid and a shape
348 struct B_IntersectPoint
350 mutable const SMDS_MeshNode* _node;
351 mutable vector< TGeomID > _faceIDs;
353 B_IntersectPoint(): _node(NULL) {}
354 bool Add( const vector< TGeomID >& fIDs, const SMDS_MeshNode* n=0 ) const;
355 TGeomID HasCommonFace( const B_IntersectPoint * other, TGeomID avoidFace=-1 ) const;
356 size_t GetCommonFaces( const B_IntersectPoint * other, TGeomID * commonFaces ) const;
357 bool IsOnFace( TGeomID faceID ) const;
358 virtual ~B_IntersectPoint() {}
360 // --------------------------------------------------------------------------
362 * \brief Data of intersection between a GridLine and a TopoDS_Face
364 struct F_IntersectPoint : public B_IntersectPoint
368 mutable Transition _transition;
369 mutable size_t _indexOnLine;
371 bool operator< ( const F_IntersectPoint& o ) const { return _paramOnLine < o._paramOnLine; }
373 // --------------------------------------------------------------------------
375 * \brief Data of intersection between GridPlanes and a TopoDS_EDGE
377 struct E_IntersectPoint : public B_IntersectPoint
381 TGeomID _shapeID; // ID of EDGE or VERTEX
383 // --------------------------------------------------------------------------
385 * \brief A line of the grid and its intersections with 2D geometry
390 double _length; // line length
391 multiset< F_IntersectPoint > _intPoints;
393 void RemoveExcessIntPoints( const double tol );
394 TGeomID GetSolidIDBefore( multiset< F_IntersectPoint >::iterator ip,
395 const TGeomID prevID,
396 const Geometry& geom);
398 // --------------------------------------------------------------------------
400 * \brief Planes of the grid used to find intersections of an EDGE with a hexahedron
405 vector< gp_XYZ > _origins; // origin points of all planes in one direction
406 vector< double > _zProjs; // projections of origins to _zNorm
408 // --------------------------------------------------------------------------
410 * \brief Iterator on the parallel grid lines of one direction
416 size_t _iVar1, _iVar2, _iConst;
417 string _name1, _name2, _nameConst;
419 LineIndexer( size_t sz1, size_t sz2, size_t sz3,
420 size_t iv1, size_t iv2, size_t iConst,
421 const string& nv1, const string& nv2, const string& nConst )
423 _size[0] = sz1; _size[1] = sz2; _size[2] = sz3;
424 _curInd[0] = _curInd[1] = _curInd[2] = 0;
425 _iVar1 = iv1; _iVar2 = iv2; _iConst = iConst;
426 _name1 = nv1; _name2 = nv2; _nameConst = nConst;
429 size_t I() const { return _curInd[0]; }
430 size_t J() const { return _curInd[1]; }
431 size_t K() const { return _curInd[2]; }
432 void SetIJK( size_t i, size_t j, size_t k )
434 _curInd[0] = i; _curInd[1] = j; _curInd[2] = k;
436 void SetLineIndex(size_t i)
438 _curInd[_iVar2] = i / _size[_iVar1];
439 _curInd[_iVar1] = i % _size[_iVar1];
443 if ( ++_curInd[_iVar1] == _size[_iVar1] )
444 _curInd[_iVar1] = 0, ++_curInd[_iVar2];
446 bool More() const { return _curInd[_iVar2] < _size[_iVar2]; }
447 size_t LineIndex () const { return _curInd[_iVar1] + _curInd[_iVar2]* _size[_iVar1]; }
448 size_t LineIndex10 () const { return (_curInd[_iVar1] + 1 ) + _curInd[_iVar2]* _size[_iVar1]; }
449 size_t LineIndex01 () const { return _curInd[_iVar1] + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
450 size_t LineIndex11 () const { return (_curInd[_iVar1] + 1 ) + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
451 void SetIndexOnLine (size_t i) { _curInd[ _iConst ] = i; }
452 bool IsValidIndexOnLine (size_t i) const { return i < _size[ _iConst ]; }
453 size_t NbLines() const { return _size[_iVar1] * _size[_iVar2]; }
455 struct FaceGridIntersector;
456 // --------------------------------------------------------------------------
458 * \brief Container of GridLine's
462 vector< double > _coords[3]; // coordinates of grid nodes
463 gp_XYZ _axes [3]; // axis directions
464 vector< GridLine > _lines [3]; // in 3 directions
465 double _tol, _minCellSize;
467 gp_Mat _invB; // inverted basis of _axes
469 // index shift within _nodes of nodes of a cell from the 1st node
472 vector< const SMDS_MeshNode* > _nodes; // mesh nodes at grid nodes
473 vector< const F_IntersectPoint* > _gridIntP; // grid node intersection with geometry
474 ObjectPool< E_IntersectPoint > _edgeIntPool; // intersections with EDGEs
475 ObjectPool< F_IntersectPoint > _extIntPool; // intersections with extended INTERNAL FACEs
476 //list< E_IntersectPoint > _edgeIntP; // intersections with EDGEs
481 bool _toConsiderInternalFaces;
482 bool _toUseThresholdForInternalFaces;
483 double _sizeThreshold;
485 SMESH_MesherHelper* _helper;
487 size_t CellIndex( size_t i, size_t j, size_t k ) const
489 return i + j*(_coords[0].size()-1) + k*(_coords[0].size()-1)*(_coords[1].size()-1);
491 size_t NodeIndex( size_t i, size_t j, size_t k ) const
493 return i + j*_coords[0].size() + k*_coords[0].size()*_coords[1].size();
495 size_t NodeIndex( const TIJK& ijk ) const
497 return NodeIndex( ijk[0], ijk[1], ijk[2] );
499 size_t NodeIndexDX() const { return 1; }
500 size_t NodeIndexDY() const { return _coords[0].size(); }
501 size_t NodeIndexDZ() const { return _coords[0].size() * _coords[1].size(); }
503 LineIndexer GetLineIndexer(size_t iDir) const;
504 size_t GetLineDir( const GridLine* line, size_t & index ) const;
506 E_IntersectPoint* Add( const E_IntersectPoint& ip )
508 E_IntersectPoint* eip = _edgeIntPool.getNew();
512 void Remove( E_IntersectPoint* eip ) { _edgeIntPool.destroy( eip ); }
514 TGeomID ShapeID( const TopoDS_Shape& s ) const;
515 const TopoDS_Shape& Shape( TGeomID id ) const;
516 TopAbs_ShapeEnum ShapeType( TGeomID id ) const { return Shape(id).ShapeType(); }
517 void InitGeometry( const TopoDS_Shape& theShape );
518 void InitClassifier( const TopoDS_Shape& mainShape,
519 TopAbs_ShapeEnum shapeType,
520 Controls::ElementsOnShape& classifier );
521 void GetEdgesToImplement( map< TGeomID, vector< TGeomID > > & edge2faceMap,
522 const TopoDS_Shape& shape,
523 const vector< TopoDS_Shape >& faces );
524 void SetSolidFather( const TopoDS_Shape& s, const TopoDS_Shape& theShapeToMesh );
525 bool IsShared( TGeomID faceID ) const;
526 bool IsAnyShared( const std::vector< TGeomID >& faceIDs ) const;
527 bool IsInternal( TGeomID faceID ) const {
528 return ( faceID == PseudoIntExtFaceID() ||
529 Shape( faceID ).Orientation() == TopAbs_INTERNAL ); }
530 bool IsSolid( TGeomID shapeID ) const {
531 if ( _geometry.IsOneSolid() ) return _geometry._soleSolid.ID() == shapeID;
532 else return _geometry._solidByID.count( shapeID ); }
533 bool IsStrangeEdge( TGeomID id ) const { return _geometry._strangeEdges.Contains( id ); }
534 TGeomID PseudoIntExtFaceID() const { return _geometry._extIntFaceID; }
535 Solid* GetSolid( TGeomID solidID = 0 );
536 Solid* GetOneOfSolids( TGeomID solidID );
537 const vector< TGeomID > & GetSolidIDs( TGeomID subShapeID ) const;
538 bool IsCorrectTransition( TGeomID faceID, const Solid* solid );
539 bool IsBoundaryFace( TGeomID face ) const { return _geometry._boundaryFaces.Contains( face ); }
540 void SetOnShape( const SMDS_MeshNode* n, const F_IntersectPoint& ip,
541 TopoDS_Vertex* vertex = nullptr, bool unset = false );
542 void UpdateFacesOfVertex( const B_IntersectPoint& ip, const TopoDS_Vertex& vertex );
543 bool IsToCheckNodePos() const { return !_toAddEdges && _toCreateFaces; }
544 bool IsToRemoveExcessEntities() const { return !_toAddEdges; }
546 void SetCoordinates(const vector<double>& xCoords,
547 const vector<double>& yCoords,
548 const vector<double>& zCoords,
549 const double* axesDirs,
550 const Bnd_Box& bndBox );
551 void ComputeUVW(const gp_XYZ& p, double uvw[3]);
552 void ComputeNodes(SMESH_MesherHelper& helper);
554 // --------------------------------------------------------------------------
556 * \brief Return cells sharing a link
558 struct CellsAroundLink
566 CellsAroundLink( Grid* grid, int iDir ):
568 _dInd{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} },
569 _nbCells{ grid->_coords[0].size() - 1,
570 grid->_coords[1].size() - 1,
571 grid->_coords[2].size() - 1 },
574 const int iDirOther[3][2] = {{ 1,2 },{ 0,2 },{ 0,1 }};
575 _dInd[1][ iDirOther[iDir][0] ] = -1;
576 _dInd[2][ iDirOther[iDir][1] ] = -1;
577 _dInd[3][ iDirOther[iDir][0] ] = -1; _dInd[3][ iDirOther[iDir][1] ] = -1;
579 void Init( int i, int j, int k, int link12 = 0 )
582 _i = i - _dInd[iL][0];
583 _j = j - _dInd[iL][1];
584 _k = k - _dInd[iL][2];
586 bool GetCell( int iL, int& i, int& j, int& k, int& cellIndex, int& linkIndex )
588 i = _i + _dInd[iL][0];
589 j = _j + _dInd[iL][1];
590 k = _k + _dInd[iL][2];
591 if ( i < 0 || i >= (int)_nbCells[0] ||
592 j < 0 || j >= (int)_nbCells[1] ||
593 k < 0 || k >= (int)_nbCells[2] )
595 cellIndex = _grid->CellIndex( i,j,k );
596 linkIndex = iL + _iDir * 4;
600 // --------------------------------------------------------------------------
602 * \brief Intersector of TopoDS_Face with all GridLine's
604 struct FaceGridIntersector
610 IntCurvesFace_Intersector* _surfaceInt;
611 vector< std::pair< GridLine*, F_IntersectPoint > > _intersections;
613 FaceGridIntersector(): _grid(0), _surfaceInt(0) {}
616 void StoreIntersections()
618 for ( size_t i = 0; i < _intersections.size(); ++i )
620 multiset< F_IntersectPoint >::iterator ip =
621 _intersections[i].first->_intPoints.insert( _intersections[i].second );
622 ip->_faceIDs.reserve( 1 );
623 ip->_faceIDs.push_back( _faceID );
626 const Bnd_Box& GetFaceBndBox()
628 GetCurveFaceIntersector();
631 IntCurvesFace_Intersector* GetCurveFaceIntersector()
635 _surfaceInt = new IntCurvesFace_Intersector( _face, Precision::PConfusion() );
636 _bndBox = _surfaceInt->Bounding();
637 if ( _bndBox.IsVoid() )
638 BRepBndLib::Add (_face, _bndBox);
642 bool IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const;
644 // --------------------------------------------------------------------------
646 * \brief Intersector of a surface with a GridLine
648 struct FaceLineIntersector
651 double _u, _v, _w; // params on the face and the line
652 Transition _transition; // transition at intersection (see IntCurveSurface.cdl)
653 Transition _transIn, _transOut; // IN and OUT transitions depending of face orientation
656 gp_Cylinder _cylinder;
660 IntCurvesFace_Intersector* _surfaceInt;
662 vector< F_IntersectPoint > _intPoints;
664 void IntersectWithPlane (const GridLine& gridLine);
665 void IntersectWithCylinder(const GridLine& gridLine);
666 void IntersectWithCone (const GridLine& gridLine);
667 void IntersectWithSphere (const GridLine& gridLine);
668 void IntersectWithTorus (const GridLine& gridLine);
669 void IntersectWithSurface (const GridLine& gridLine);
671 bool UVIsOnFace() const;
672 void addIntPoint(const bool toClassify=true);
673 bool isParamOnLineOK( const double linLength )
675 return -_tol < _w && _w < linLength + _tol;
677 FaceLineIntersector():_surfaceInt(0) {}
678 ~FaceLineIntersector() { if (_surfaceInt ) delete _surfaceInt; _surfaceInt = 0; }
680 // --------------------------------------------------------------------------
682 * \brief Class representing topology of the hexahedron and creating a mesh
683 * volume basing on analysis of hexahedron intersection with geometry
687 // --------------------------------------------------------------------------------
690 enum IsInternalFlag { IS_NOT_INTERNAL, IS_INTERNAL, IS_CUT_BY_INTERNAL_FACE };
691 // --------------------------------------------------------------------------------
692 struct _Node //!< node either at a hexahedron corner or at intersection
694 const SMDS_MeshNode* _node; // mesh node at hexahedron corner
695 const B_IntersectPoint* _intPoint;
696 const _Face* _usedInFace;
697 char _isInternalFlags;
699 _Node(const SMDS_MeshNode* n=0, const B_IntersectPoint* ip=0)
700 :_node(n), _intPoint(ip), _usedInFace(0), _isInternalFlags(0) {}
701 const SMDS_MeshNode* Node() const
702 { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
703 const E_IntersectPoint* EdgeIntPnt() const
704 { return static_cast< const E_IntersectPoint* >( _intPoint ); }
705 const F_IntersectPoint* FaceIntPnt() const
706 { return static_cast< const F_IntersectPoint* >( _intPoint ); }
707 const vector< TGeomID >& faces() const { return _intPoint->_faceIDs; }
708 TGeomID face(size_t i) const { return _intPoint->_faceIDs[ i ]; }
709 void SetInternal( IsInternalFlag intFlag ) { _isInternalFlags |= intFlag; }
710 bool IsCutByInternal() const { return _isInternalFlags & IS_CUT_BY_INTERNAL_FACE; }
711 bool IsUsedInFace( const _Face* polygon = 0 )
713 return polygon ? ( _usedInFace == polygon ) : bool( _usedInFace );
715 TGeomID IsLinked( const B_IntersectPoint* other,
716 TGeomID avoidFace=-1 ) const // returns id of a common face
718 return _intPoint ? _intPoint->HasCommonFace( other, avoidFace ) : 0;
720 bool IsOnFace( TGeomID faceID ) const // returns true if faceID is found
722 return _intPoint ? _intPoint->IsOnFace( faceID ) : false;
724 size_t GetCommonFaces( const B_IntersectPoint * other, TGeomID* common ) const
726 return _intPoint && other ? _intPoint->GetCommonFaces( other, common ) : 0;
730 if ( const SMDS_MeshNode* n = Node() )
731 return SMESH_NodeXYZ( n );
732 if ( const E_IntersectPoint* eip =
733 dynamic_cast< const E_IntersectPoint* >( _intPoint ))
735 return gp_Pnt( 1e100, 0, 0 );
737 TGeomID ShapeID() const
739 if ( const E_IntersectPoint* eip = dynamic_cast< const E_IntersectPoint* >( _intPoint ))
740 return eip->_shapeID;
743 void Add( const E_IntersectPoint* ip )
745 // Possible cases before Add(ip):
746 /// 1) _node != 0 --> _Node at hex corner ( _intPoint == 0 || _intPoint._node == 0 )
747 /// 2) _node == 0 && _intPoint._node != 0 --> link intersected by FACE
748 /// 3) _node == 0 && _intPoint._node == 0 --> _Node at EDGE intersection
750 // If ip is added in cases 1) and 2) _node position must be changed to ip._shapeID
751 // at creation of elements
752 // To recognize this case, set _intPoint._node = Node()
753 const SMDS_MeshNode* node = Node();
758 ip->Add( _intPoint->_faceIDs );
762 _node = _intPoint->_node = node;
765 // --------------------------------------------------------------------------------
766 struct _Link // link connecting two _Node's
769 _Face* _faces[2]; // polygons sharing a link
770 vector< const F_IntersectPoint* > _fIntPoints; // GridLine intersections with FACEs
771 vector< _Node* > _fIntNodes; // _Node's at _fIntPoints
772 vector< _Link > _splits;
773 _Link(): _faces{ 0, 0 } {}
775 // --------------------------------------------------------------------------------
780 _OrientedLink( _Link* link=0, bool reverse=false ): _link(link), _reverse(reverse) {}
781 void Reverse() { _reverse = !_reverse; }
782 size_t NbResultLinks() const { return _link->_splits.size(); }
783 _OrientedLink ResultLink(int i) const
785 return _OrientedLink(&_link->_splits[_reverse ? NbResultLinks()-i-1 : i],_reverse);
787 _Node* FirstNode() const { return _link->_nodes[ _reverse ]; }
788 _Node* LastNode() const { return _link->_nodes[ !_reverse ]; }
789 operator bool() const { return _link; }
790 vector< TGeomID > GetNotUsedFace(const set<TGeomID>& usedIDs ) const // returns supporting FACEs
792 vector< TGeomID > faces;
793 const B_IntersectPoint *ip0, *ip1;
794 if (( ip0 = _link->_nodes[0]->_intPoint ) &&
795 ( ip1 = _link->_nodes[1]->_intPoint ))
797 for ( size_t i = 0; i < ip0->_faceIDs.size(); ++i )
798 if ( ip1->IsOnFace ( ip0->_faceIDs[i] ) &&
799 !usedIDs.count( ip0->_faceIDs[i] ) )
800 faces.push_back( ip0->_faceIDs[i] );
804 bool HasEdgeNodes() const
806 return ( dynamic_cast< const E_IntersectPoint* >( _link->_nodes[0]->_intPoint ) ||
807 dynamic_cast< const E_IntersectPoint* >( _link->_nodes[1]->_intPoint ));
811 return !_link->_faces[0] ? 0 : 1 + bool( _link->_faces[1] );
813 void AddFace( _Face* f )
815 if ( _link->_faces[0] )
817 _link->_faces[1] = f;
821 _link->_faces[0] = f;
822 _link->_faces[1] = 0;
825 void RemoveFace( _Face* f )
827 if ( !_link->_faces[0] ) return;
829 if ( _link->_faces[1] == f )
831 _link->_faces[1] = 0;
833 else if ( _link->_faces[0] == f )
835 _link->_faces[0] = 0;
836 if ( _link->_faces[1] )
838 _link->_faces[0] = _link->_faces[1];
839 _link->_faces[1] = 0;
844 // --------------------------------------------------------------------------------
845 struct _SplitIterator //! set to _hexLinks splits on one side of INTERNAL FACEs
847 struct _Split // data of a link split
849 int _linkID; // hex link ID
851 int _iCheckIteration; // iteration where split is tried as Hexahedron split
852 _Link* _checkedSplit; // split set to hex links
853 bool _isUsed; // used in a volume
855 _Split( _Link & split, int iLink ):
856 _linkID( iLink ), _nodes{ split._nodes[0], split._nodes[1] },
857 _iCheckIteration( 0 ), _isUsed( false )
859 bool IsCheckedOrUsed( bool used ) const { return used ? _isUsed : _iCheckIteration > 0; }
862 std::vector< _Split > _splits;
866 std::vector< _Node* > _freeNodes; // nodes reached while composing a split set
868 _SplitIterator( _Link* hexLinks ):
869 _hexLinks( hexLinks ), _iterationNb(0), _nbChecked(0), _nbUsed(0)
871 _freeNodes.reserve( 12 );
872 _splits.reserve( 24 );
873 for ( int iL = 0; iL < 12; ++iL )
874 for ( size_t iS = 0; iS < _hexLinks[ iL ]._splits.size(); ++iS )
875 _splits.emplace_back( _hexLinks[ iL ]._splits[ iS ], iL );
878 bool More() const { return _nbUsed < _splits.size(); }
881 // --------------------------------------------------------------------------------
884 SMESH_Block::TShapeID _name;
885 vector< _OrientedLink > _links; // links on GridLine's
886 vector< _Link > _polyLinks; // links added to close a polygonal face
887 vector< _Node* > _eIntNodes; // nodes at intersection with EDGEs
889 _Face():_name( SMESH_Block::ID_NONE )
891 bool IsPolyLink( const _OrientedLink& ol )
893 return _polyLinks.empty() ? false :
894 ( &_polyLinks[0] <= ol._link && ol._link <= &_polyLinks.back() );
896 void AddPolyLink(_Node* n0, _Node* n1, _Face* faceToFindEqual=0)
898 if ( faceToFindEqual && faceToFindEqual != this ) {
899 for ( size_t iL = 0; iL < faceToFindEqual->_polyLinks.size(); ++iL )
900 if ( faceToFindEqual->_polyLinks[iL]._nodes[0] == n1 &&
901 faceToFindEqual->_polyLinks[iL]._nodes[1] == n0 )
904 ( _OrientedLink( & faceToFindEqual->_polyLinks[iL], /*reverse=*/true ));
911 _polyLinks.push_back( l );
912 _links.push_back( _OrientedLink( &_polyLinks.back() ));
915 // --------------------------------------------------------------------------------
916 struct _volumeDef // holder of nodes of a volume mesh element
922 const SMDS_MeshNode* _node; // mesh node at hexahedron corner
923 const B_IntersectPoint* _intPoint;
925 _nodeDef(): _node(0), _intPoint(0) {}
926 _nodeDef( _Node* n ): _node( n->_node), _intPoint( n->_intPoint ) {}
927 const SMDS_MeshNode* Node() const
928 { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
929 const E_IntersectPoint* EdgeIntPnt() const
930 { return static_cast< const E_IntersectPoint* >( _intPoint ); }
931 _ptr Ptr() const { return Node() ? (_ptr) Node() : (_ptr) EdgeIntPnt(); }
932 bool operator==(const _nodeDef& other ) const { return Ptr() == other.Ptr(); }
935 vector< _nodeDef > _nodes;
936 vector< int > _quantities;
937 _volumeDef* _next; // to store several _volumeDefs in a chain
940 const SMDS_MeshElement* _volume; // new volume
941 std::vector<const SMDS_MeshElement*> _brotherVolume; // produced due to poly split
943 vector< SMESH_Block::TShapeID > _names; // name of side a polygon originates from
945 _volumeDef(): _next(0), _solidID(0), _size(0), _volume(0) {}
946 ~_volumeDef() { delete _next; }
947 _volumeDef( _volumeDef& other ):
948 _next(0), _solidID( other._solidID ), _size( other._size ), _volume( other._volume )
949 { _nodes.swap( other._nodes ); _quantities.swap( other._quantities ); other._volume = 0;
950 _names.swap( other._names ); }
952 size_t size() const { return 1 + ( _next ? _next->size() : 0 ); } // nb _volumeDef in a chain
953 _volumeDef* at(int index)
954 { return index == 0 ? this : ( _next ? _next->at(index-1) : _next ); }
956 void Set( _Node** nodes, int nb )
957 { _nodes.assign( nodes, nodes + nb ); }
959 void SetNext( _volumeDef* vd )
960 { if ( _next ) { _next->SetNext( vd ); } else { _next = vd; }}
962 bool IsEmpty() const { return (( _nodes.empty() ) &&
963 ( !_next || _next->IsEmpty() )); }
964 bool IsPolyhedron() const { return ( !_quantities.empty() ||
965 ( _next && !_next->_quantities.empty() )); }
968 struct _linkDef: public std::pair<_ptr,_ptr> // to join polygons in removeExcessSideDivision()
970 _nodeDef _node1;//, _node2;
971 mutable /*const */_linkDef *_prev, *_next;
974 _linkDef():_prev(0), _next(0) {}
976 void init( const _nodeDef& n1, const _nodeDef& n2, size_t iLoop )
978 _node1 = n1; //_node2 = n2;
982 if ( first > second ) std::swap( first, second );
984 void setNext( _linkDef* next )
992 // topology of a hexahedron
994 _Link _hexLinks [12];
997 // faces resulted from hexahedron intersection
998 vector< _Face > _polygons;
1000 // intresections with EDGEs
1001 vector< const E_IntersectPoint* > _eIntPoints;
1003 // additional nodes created at intersection points
1004 vector< _Node > _intNodes;
1006 // nodes inside the hexahedron (at VERTEXes) refer to _intNodes
1007 vector< _Node* > _vIntNodes;
1009 // computed volume elements
1010 _volumeDef _volumeDefs;
1013 double _sideLength[3];
1014 int _nbCornerNodes, _nbFaceIntNodes, _nbBndNodes;
1015 int _origNodeInd; // index of _hexNodes[0] node within the _grid
1021 Hexahedron(Grid* grid);
1022 int MakeElements(SMESH_MesherHelper& helper,
1023 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
1024 void computeElements( const Solid* solid = 0, int solidIndex = -1 );
1027 Hexahedron(const Hexahedron& other, size_t i, size_t j, size_t k, int cellID );
1028 void init( size_t i, size_t j, size_t k, const Solid* solid=0 );
1029 void init( size_t i );
1030 void setIJK( size_t i );
1031 bool compute( const Solid* solid, const IsInternalFlag intFlag );
1032 size_t getSolids( TGeomID ids[] );
1033 bool isCutByInternalFace( IsInternalFlag & maxFlag );
1034 void addEdges(SMESH_MesherHelper& helper,
1035 vector< Hexahedron* >& intersectedHex,
1036 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
1037 gp_Pnt findIntPoint( double u1, double proj1, double u2, double proj2,
1038 double proj, BRepAdaptor_Curve& curve,
1039 const gp_XYZ& axis, const gp_XYZ& origin );
1040 int getEntity( const E_IntersectPoint* ip, int* facets, int& sub );
1041 bool addIntersection( const E_IntersectPoint* ip,
1042 vector< Hexahedron* >& hexes,
1043 int ijk[], int dIJK[] );
1044 bool isQuadOnFace( const size_t iQuad );
1045 bool findChain( _Node* n1, _Node* n2, _Face& quad, vector<_Node*>& chainNodes );
1046 bool closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const;
1047 bool findChainOnEdge( const vector< _OrientedLink >& splits,
1048 const _OrientedLink& prevSplit,
1049 const _OrientedLink& avoidSplit,
1050 const std::set< TGeomID > & concaveFaces,
1053 vector<_Node*>& chn);
1054 int addVolumes(SMESH_MesherHelper& helper );
1055 void addFaces( SMESH_MesherHelper& helper,
1056 const vector< const SMDS_MeshElement* > & boundaryVolumes );
1057 void addSegments( SMESH_MesherHelper& helper,
1058 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap );
1059 void getVolumes( vector< const SMDS_MeshElement* > & volumes );
1060 void getBoundaryElems( vector< const SMDS_MeshElement* > & boundaryVolumes );
1061 void removeExcessSideDivision(const vector< Hexahedron* >& allHexa);
1062 void removeExcessNodes(vector< Hexahedron* >& allHexa);
1063 void preventVolumesOverlapping();
1064 TGeomID getAnyFace() const;
1065 void cutByExtendedInternal( std::vector< Hexahedron* >& hexes,
1066 const TColStd_MapOfInteger& intEdgeIDs );
1067 gp_Pnt mostDistantInternalPnt( int hexIndex, const gp_Pnt& p1, const gp_Pnt& p2 );
1068 bool isOutPoint( _Link& link, int iP, SMESH_MesherHelper& helper, const Solid* solid ) const;
1069 void sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID face);
1070 bool isInHole() const;
1071 bool hasStrangeEdge() const;
1072 bool checkPolyhedronSize( bool isCutByInternalFace, double & volSize ) const;
1073 int checkPolyhedronValidity( _volumeDef* volDef, std::vector<std::vector<int>>& splitQuantities,
1074 std::vector<std::vector<const SMDS_MeshNode*>>& splitNodes );
1075 const SMDS_MeshElement* addPolyhedronToMesh( _volumeDef* volDef, SMESH_MesherHelper& helper, const std::vector<const SMDS_MeshNode*>& nodes,
1076 const std::vector<int>& quantities );
1081 bool debugDumpLink( _Link* link );
1082 _Node* findEqualNode( vector< _Node* >& nodes,
1083 const E_IntersectPoint* ip,
1086 for ( size_t i = 0; i < nodes.size(); ++i )
1087 if ( nodes[i]->EdgeIntPnt() == ip ||
1088 nodes[i]->Point().SquareDistance( ip->_point ) <= tol2 )
1092 bool isCorner( const _Node* node ) const { return ( node >= &_hexNodes[0] &&
1093 node - &_hexNodes[0] < 8 ); }
1094 bool hasEdgesAround( const ConcaveFace* cf ) const;
1095 bool isImplementEdges() const { return _grid->_edgeIntPool.nbElements(); }
1096 bool isOutParam(const double uvw[3]) const;
1098 typedef boost::container::flat_map< TGeomID, size_t > TID2Nb;
1099 static void insertAndIncrement( TGeomID id, TID2Nb& id2nbMap )
1101 TID2Nb::value_type s0( id, 0 );
1102 TID2Nb::iterator id2nb = id2nbMap.insert( s0 ).first;
1105 }; // class Hexahedron
1108 // --------------------------------------------------------------------------
1110 * \brief Hexahedron computing volumes in one thread
1112 struct ParallelHexahedron
1114 vector< Hexahedron* >& _hexVec;
1115 ParallelHexahedron( vector< Hexahedron* >& hv ): _hexVec(hv) {}
1116 void operator() ( const tbb::blocked_range<size_t>& r ) const
1118 for ( size_t i = r.begin(); i != r.end(); ++i )
1119 if ( Hexahedron* hex = _hexVec[ i ] )
1120 hex->computeElements();
1123 // --------------------------------------------------------------------------
1125 * \brief Structure intersecting certain nb of faces with GridLine's in one thread
1127 struct ParallelIntersector
1129 vector< FaceGridIntersector >& _faceVec;
1130 ParallelIntersector( vector< FaceGridIntersector >& faceVec): _faceVec(faceVec){}
1131 void operator() ( const tbb::blocked_range<size_t>& r ) const
1133 for ( size_t i = r.begin(); i != r.end(); ++i )
1134 _faceVec[i].Intersect();
1139 //=============================================================================
1140 // Implementation of internal utils
1141 //=============================================================================
1143 * \brief adjust \a i to have \a val between values[i] and values[i+1]
1145 inline void locateValue( int & i, double val, const vector<double>& values,
1146 int& di, double tol )
1148 //val += values[0]; // input \a val is measured from 0.
1149 if ( i > (int) values.size()-2 )
1150 i = values.size()-2;
1152 while ( i+2 < (int) values.size() && val > values[ i+1 ])
1154 while ( i > 0 && val < values[ i ])
1157 if ( i > 0 && val - values[ i ] < tol )
1159 else if ( i+2 < (int) values.size() && values[ i+1 ] - val < tol )
1164 //=============================================================================
1166 * Return a vector of SOLIDS sharing given shapes
1168 GeomIDVecHelder Geometry::GetSolidIDsByShapeID( const vector< TGeomID >& theShapeIDs ) const
1170 if ( theShapeIDs.size() == 1 )
1171 return GeomIDVecHelder( _solidIDsByShapeID[ theShapeIDs[ 0 ]], /*owner=*/false );
1173 // look for an empty slot in _solidIDsByShapeID
1174 vector< TGeomID > * resultIDs = 0;
1175 for ( const vector< TGeomID >& vec : _solidIDsByShapeID )
1178 resultIDs = const_cast< vector< TGeomID > * >( & vec );
1181 // fill in resultIDs
1182 for ( const TGeomID& id : theShapeIDs )
1183 for ( const TGeomID& solid : _solidIDsByShapeID[ id ])
1185 if ( std::find( resultIDs->begin(), resultIDs->end(), solid ) == resultIDs->end() )
1186 resultIDs->push_back( solid );
1188 return GeomIDVecHelder( *resultIDs, /*owner=*/true );
1190 //=============================================================================
1192 * Remove coincident intersection points
1194 void GridLine::RemoveExcessIntPoints( const double tol )
1196 if ( _intPoints.size() < 2 ) return;
1198 set< Transition > tranSet;
1199 multiset< F_IntersectPoint >::iterator ip1, ip2 = _intPoints.begin();
1200 while ( ip2 != _intPoints.end() )
1204 while ( ip2 != _intPoints.end() && ip2->_paramOnLine - ip1->_paramOnLine <= tol )
1206 tranSet.insert( ip1->_transition );
1207 tranSet.insert( ip2->_transition );
1208 ip2->Add( ip1->_faceIDs );
1209 _intPoints.erase( ip1 );
1212 if ( tranSet.size() > 1 ) // points with different transition coincide
1214 bool isIN = tranSet.count( Trans_IN );
1215 bool isOUT = tranSet.count( Trans_OUT );
1216 if ( isIN && isOUT )
1217 (*ip1)._transition = Trans_TANGENT;
1219 (*ip1)._transition = isIN ? Trans_IN : Trans_OUT;
1223 //================================================================================
1225 * Return ID of SOLID for nodes before the given intersection point
1227 TGeomID GridLine::GetSolidIDBefore( multiset< F_IntersectPoint >::iterator ip,
1228 const TGeomID prevID,
1229 const Geometry& geom )
1231 if ( ip == _intPoints.begin() )
1234 if ( geom.IsOneSolid() )
1237 switch ( ip->_transition ) {
1238 case Trans_IN: isOut = true; break;
1239 case Trans_OUT: isOut = false; break;
1240 case Trans_TANGENT: isOut = ( prevID != 0 ); break;
1243 // singularity point (apex of a cone)
1244 multiset< F_IntersectPoint >::iterator ipBef = ip, ipAft = ++ip;
1245 if ( ipAft == _intPoints.end() )
1250 if ( ipBef->_transition != ipAft->_transition )
1251 isOut = ( ipBef->_transition == Trans_OUT );
1253 isOut = ( ipBef->_transition != Trans_OUT );
1257 case Trans_INTERNAL: isOut = false;
1260 return isOut ? 0 : geom._soleSolid.ID();
1263 GeomIDVecHelder solids = geom.GetSolidIDsByShapeID( ip->_faceIDs );
1266 if ( ip->_transition == Trans_INTERNAL )
1269 GeomIDVecHelder solidsBef = geom.GetSolidIDsByShapeID( ip->_faceIDs );
1271 if ( ip->_transition == Trans_IN ||
1272 ip->_transition == Trans_OUT )
1274 if ( solidsBef.size() == 1 )
1276 if ( solidsBef[0] == prevID )
1277 return ip->_transition == Trans_OUT ? 0 : solidsBef[0];
1279 return solidsBef[0];
1282 if ( solids.size() == 2 )
1284 if ( solids == solidsBef )
1285 return solids.contain( prevID ) ? solids.otherThan( prevID ) : theUndefID; // bos #29212
1287 return solids.oneCommon( solidsBef );
1290 if ( solidsBef.size() == 1 )
1291 return solidsBef[0];
1293 return solids.oneCommon( solidsBef );
1295 //================================================================================
1299 bool B_IntersectPoint::Add( const vector< TGeomID >& fIDs,
1300 const SMDS_MeshNode* n) const
1302 size_t prevNbF = _faceIDs.size();
1304 if ( _faceIDs.empty() )
1307 for ( size_t i = 0; i < fIDs.size(); ++i )
1309 vector< TGeomID >::iterator it =
1310 std::find( _faceIDs.begin(), _faceIDs.end(), fIDs[i] );
1311 if ( it == _faceIDs.end() )
1312 _faceIDs.push_back( fIDs[i] );
1317 return prevNbF < _faceIDs.size();
1319 //================================================================================
1321 * Return ID of a common face if any, else zero
1323 TGeomID B_IntersectPoint::HasCommonFace( const B_IntersectPoint * other, TGeomID avoidFace ) const
1326 for ( size_t i = 0; i < other->_faceIDs.size(); ++i )
1327 if ( avoidFace != other->_faceIDs[i] &&
1328 IsOnFace ( other->_faceIDs[i] ))
1329 return other->_faceIDs[i];
1332 //================================================================================
1334 * Return faces common with other point
1336 size_t B_IntersectPoint::GetCommonFaces( const B_IntersectPoint * other, TGeomID* common ) const
1341 if ( _faceIDs.size() > other->_faceIDs.size() )
1342 return other->GetCommonFaces( this, common );
1343 for ( const TGeomID& face : _faceIDs )
1344 if ( other->IsOnFace( face ))
1345 common[ nbComm++ ] = face;
1348 //================================================================================
1350 * Return \c true if \a faceID in in this->_faceIDs
1352 bool B_IntersectPoint::IsOnFace( TGeomID faceID ) const // returns true if faceID is found
1354 vector< TGeomID >::const_iterator it =
1355 std::find( _faceIDs.begin(), _faceIDs.end(), faceID );
1356 return ( it != _faceIDs.end() );
1358 //================================================================================
1360 * OneOfSolids initialization
1362 void OneOfSolids::Init( const TopoDS_Shape& solid,
1363 TopAbs_ShapeEnum subType,
1364 const SMESHDS_Mesh* mesh )
1366 SetID( mesh->ShapeToIndex( solid ));
1368 if ( subType == TopAbs_FACE )
1369 SetHasInternalFaces( false );
1371 for ( TopExp_Explorer sub( solid, subType ); sub.More(); sub.Next() )
1373 _subIDs.Add( mesh->ShapeToIndex( sub.Current() ));
1374 if ( subType == TopAbs_FACE )
1376 _faces.Add( sub.Current() );
1377 if ( sub.Current().Orientation() == TopAbs_INTERNAL )
1378 SetHasInternalFaces( true );
1380 TGeomID faceID = mesh->ShapeToIndex( sub.Current() );
1381 if ( sub.Current().Orientation() == TopAbs_INTERNAL ||
1382 sub.Current().Orientation() == mesh->IndexToShape( faceID ).Orientation() )
1383 _outFaceIDs.Add( faceID );
1387 //================================================================================
1389 * Return an iterator on GridLine's in a given direction
1391 LineIndexer Grid::GetLineIndexer(size_t iDir) const
1393 const size_t indices[] = { 1,2,0, 0,2,1, 0,1,2 };
1394 const string s [] = { "X", "Y", "Z" };
1395 LineIndexer li( _coords[0].size(), _coords[1].size(), _coords[2].size(),
1396 indices[iDir*3], indices[iDir*3+1], indices[iDir*3+2],
1397 s[indices[iDir*3]], s[indices[iDir*3+1]], s[indices[iDir*3+2]]);
1400 //================================================================================
1402 * Return direction [0,1,2] of a GridLine
1404 size_t Grid::GetLineDir( const GridLine* line, size_t & index ) const
1406 for ( size_t iDir = 0; iDir < 3; ++iDir )
1407 if ( &_lines[ iDir ][0] <= line && line <= &_lines[ iDir ].back() )
1409 index = line - &_lines[ iDir ][0];
1414 //=============================================================================
1416 * Creates GridLine's of the grid
1418 void Grid::SetCoordinates(const vector<double>& xCoords,
1419 const vector<double>& yCoords,
1420 const vector<double>& zCoords,
1421 const double* axesDirs,
1422 const Bnd_Box& shapeBox)
1424 _coords[0] = xCoords;
1425 _coords[1] = yCoords;
1426 _coords[2] = zCoords;
1428 _axes[0].SetCoord( axesDirs[0],
1431 _axes[1].SetCoord( axesDirs[3],
1434 _axes[2].SetCoord( axesDirs[6],
1437 _axes[0].Normalize();
1438 _axes[1].Normalize();
1439 _axes[2].Normalize();
1441 _invB.SetCols( _axes[0], _axes[1], _axes[2] );
1444 // compute tolerance
1445 _minCellSize = Precision::Infinite();
1446 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1448 for ( size_t i = 1; i < _coords[ iDir ].size(); ++i )
1450 double cellLen = _coords[ iDir ][ i ] - _coords[ iDir ][ i-1 ];
1451 if ( cellLen < _minCellSize )
1452 _minCellSize = cellLen;
1455 if ( _minCellSize < Precision::Confusion() )
1456 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1457 SMESH_Comment("Too small cell size: ") << _minCellSize );
1458 _tol = _minCellSize / 1000.;
1460 // attune grid extremities to shape bounding box
1462 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
1463 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
1464 double* cP[6] = { &_coords[0].front(), &_coords[1].front(), &_coords[2].front(),
1465 &_coords[0].back(), &_coords[1].back(), &_coords[2].back() };
1466 for ( int i = 0; i < 6; ++i )
1467 if ( fabs( sP[i] - *cP[i] ) < _tol )
1468 *cP[i] = sP[i];// + _tol/1000. * ( i < 3 ? +1 : -1 );
1470 for ( int iDir = 0; iDir < 3; ++iDir )
1472 if ( _coords[iDir][0] - sP[iDir] > _tol )
1474 _minCellSize = Min( _minCellSize, _coords[iDir][0] - sP[iDir] );
1475 _coords[iDir].insert( _coords[iDir].begin(), sP[iDir] + _tol/1000.);
1477 if ( sP[iDir+3] - _coords[iDir].back() > _tol )
1479 _minCellSize = Min( _minCellSize, sP[iDir+3] - _coords[iDir].back() );
1480 _coords[iDir].push_back( sP[iDir+3] - _tol/1000.);
1483 _tol = _minCellSize / 1000.;
1485 _origin = ( _coords[0][0] * _axes[0] +
1486 _coords[1][0] * _axes[1] +
1487 _coords[2][0] * _axes[2] );
1490 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1492 LineIndexer li = GetLineIndexer( iDir );
1493 _lines[iDir].resize( li.NbLines() );
1494 double len = _coords[ iDir ].back() - _coords[iDir].front();
1495 for ( ; li.More(); ++li )
1497 GridLine& gl = _lines[iDir][ li.LineIndex() ];
1498 gl._line.SetLocation( _coords[0][li.I()] * _axes[0] +
1499 _coords[1][li.J()] * _axes[1] +
1500 _coords[2][li.K()] * _axes[2] );
1501 gl._line.SetDirection( _axes[ iDir ]);
1506 //================================================================================
1508 * Return local ID of shape
1510 TGeomID Grid::ShapeID( const TopoDS_Shape& s ) const
1512 return _helper->GetMeshDS()->ShapeToIndex( s );
1514 //================================================================================
1516 * Return a shape by its local ID
1518 const TopoDS_Shape& Grid::Shape( TGeomID id ) const
1520 return _helper->GetMeshDS()->IndexToShape( id );
1522 //================================================================================
1524 * Initialize _geometry
1526 void Grid::InitGeometry( const TopoDS_Shape& theShapeToMesh )
1528 SMESH_Mesh* mesh = _helper->GetMesh();
1530 _geometry._mainShape = theShapeToMesh;
1531 _geometry._extIntFaceID = mesh->GetMeshDS()->MaxShapeIndex() * 100;
1532 _geometry._soleSolid.SetID( 0 );
1533 _geometry._soleSolid.SetHasInternalFaces( false );
1535 InitClassifier( theShapeToMesh, TopAbs_VERTEX, _geometry._vertexClassifier );
1536 InitClassifier( theShapeToMesh, TopAbs_EDGE , _geometry._edgeClassifier );
1538 TopExp_Explorer solidExp( theShapeToMesh, TopAbs_SOLID );
1540 bool isSeveralSolids = false;
1541 if ( _toConsiderInternalFaces ) // check nb SOLIDs
1544 isSeveralSolids = solidExp.More();
1545 _toConsiderInternalFaces = isSeveralSolids;
1548 if ( !isSeveralSolids ) // look for an internal FACE
1550 TopExp_Explorer fExp( theShapeToMesh, TopAbs_FACE );
1551 for ( ; fExp.More() && !_toConsiderInternalFaces; fExp.Next() )
1552 _toConsiderInternalFaces = ( fExp.Current().Orientation() == TopAbs_INTERNAL );
1554 _geometry._soleSolid.SetHasInternalFaces( _toConsiderInternalFaces );
1555 _geometry._soleSolid.SetID( ShapeID( solidExp.Current() ));
1557 else // fill Geometry::_solidByID
1559 for ( ; solidExp.More(); solidExp.Next() )
1561 OneOfSolids & solid = _geometry._solidByID[ ShapeID( solidExp.Current() )];
1562 solid.Init( solidExp.Current(), TopAbs_FACE, mesh->GetMeshDS() );
1563 solid.Init( solidExp.Current(), TopAbs_EDGE, mesh->GetMeshDS() );
1564 solid.Init( solidExp.Current(), TopAbs_VERTEX, mesh->GetMeshDS() );
1570 _geometry._soleSolid.SetID( ShapeID( solidExp.Current() ));
1573 if ( !_toCreateFaces )
1575 int nbSolidsGlobal = _helper->Count( mesh->GetShapeToMesh(), TopAbs_SOLID, false );
1576 int nbSolidsLocal = _helper->Count( theShapeToMesh, TopAbs_SOLID, false );
1577 _toCreateFaces = ( nbSolidsLocal < nbSolidsGlobal );
1580 TopTools_IndexedMapOfShape faces;
1581 TopExp::MapShapes( theShapeToMesh, TopAbs_FACE, faces );
1583 // find boundary FACEs on boundary of mesh->ShapeToMesh()
1584 if ( _toCreateFaces )
1585 for ( int i = 1; i <= faces.Size(); ++i )
1586 if ( faces(i).Orientation() != TopAbs_INTERNAL &&
1587 _helper->NbAncestors( faces(i), *mesh, TopAbs_SOLID ) == 1 )
1589 _geometry._boundaryFaces.Add( ShapeID( faces(i) ));
1592 if ( isSeveralSolids )
1593 for ( int i = 1; i <= faces.Size(); ++i )
1595 SetSolidFather( faces(i), theShapeToMesh );
1596 for ( TopExp_Explorer eExp( faces(i), TopAbs_EDGE ); eExp.More(); eExp.Next() )
1598 const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
1599 SetSolidFather( edge, theShapeToMesh );
1600 SetSolidFather( _helper->IthVertex( 0, edge ), theShapeToMesh );
1601 SetSolidFather( _helper->IthVertex( 1, edge ), theShapeToMesh );
1605 // fill in _geometry._shape2NbNodes == find already meshed sub-shapes
1606 _geometry._shape2NbNodes.Clear();
1607 if ( mesh->NbNodes() > 0 )
1609 for ( TopAbs_ShapeEnum type : { TopAbs_FACE, TopAbs_EDGE, TopAbs_VERTEX })
1610 for ( TopExp_Explorer exp( theShapeToMesh, type ); exp.More(); exp.Next() )
1612 if ( _geometry._shape2NbNodes.IsBound( exp.Current() ))
1614 if ( SMESHDS_SubMesh* sm = mesh->GetMeshDS()->MeshElements( exp.Current() ))
1615 if ( sm->NbNodes() > 0 )
1616 _geometry._shape2NbNodes.Bind( exp.Current(), sm->NbNodes() );
1620 // fill in Solid::_concaveVertex
1621 vector< TGeomID > soleSolidID( 1, _geometry._soleSolid.ID() );
1622 for ( int i = 1; i <= faces.Size(); ++i )
1624 const TopoDS_Face& F = TopoDS::Face( faces( i ));
1626 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *mesh, 0, error,
1627 nullptr, nullptr, false );
1628 for ( StdMeshers_FaceSidePtr& wire : wires )
1630 const int nbEdges = wire->NbEdges();
1631 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wire->Edge(0)))
1633 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1635 if ( SMESH_Algo::isDegenerated( wire->Edge( iE1 ))) continue;
1636 int iE2 = ( iE1 + 1 ) % nbEdges;
1637 while ( SMESH_Algo::isDegenerated( wire->Edge( iE2 )))
1638 iE2 = ( iE2 + 1 ) % nbEdges;
1639 TopoDS_Vertex V = wire->FirstVertex( iE2 );
1640 double angle = _helper->GetAngle( wire->Edge( iE1 ),
1641 wire->Edge( iE2 ), F, V );
1642 if ( angle < -5. * M_PI / 180. )
1644 TGeomID faceID = ShapeID( F );
1645 const vector< TGeomID > & solids =
1646 _geometry.IsOneSolid() ? soleSolidID : GetSolidIDs( faceID );
1647 for ( const TGeomID & solidID : solids )
1649 Solid* solid = GetSolid( solidID );
1650 TGeomID V1 = ShapeID( wire->FirstVertex( iE1 ));
1651 TGeomID V2 = ShapeID( wire->LastVertex ( iE2 ));
1652 solid->SetConcave( ShapeID( V ), faceID,
1653 wire->EdgeID( iE1 ), wire->EdgeID( iE2 ), V1, V2 );
1662 //================================================================================
1664 * Store ID of SOLID as father of its child shape ID
1666 void Grid::SetSolidFather( const TopoDS_Shape& s, const TopoDS_Shape& theShapeToMesh )
1668 if ( _geometry._solidIDsByShapeID.empty() )
1669 _geometry._solidIDsByShapeID.resize( _helper->GetMeshDS()->MaxShapeIndex() + 1 );
1671 vector< TGeomID > & solidIDs = _geometry._solidIDsByShapeID[ ShapeID( s )];
1672 if ( !solidIDs.empty() )
1674 solidIDs.reserve(2);
1675 PShapeIteratorPtr solidIt = _helper->GetAncestors( s,
1676 *_helper->GetMesh(),
1679 while ( const TopoDS_Shape* solid = solidIt->next() )
1680 solidIDs.push_back( ShapeID( *solid ));
1682 //================================================================================
1684 * Return IDs of solids given sub-shape belongs to
1686 const vector< TGeomID > & Grid::GetSolidIDs( TGeomID subShapeID ) const
1688 return _geometry._solidIDsByShapeID[ subShapeID ];
1690 //================================================================================
1692 * Check if a sub-shape belongs to several SOLIDs
1694 bool Grid::IsShared( TGeomID shapeID ) const
1696 return !_geometry.IsOneSolid() && ( _geometry._solidIDsByShapeID[ shapeID ].size() > 1 );
1698 //================================================================================
1700 * Check if any of FACEs belongs to several SOLIDs
1702 bool Grid::IsAnyShared( const std::vector< TGeomID >& faceIDs ) const
1704 for ( size_t i = 0; i < faceIDs.size(); ++i )
1705 if ( IsShared( faceIDs[ i ]))
1709 //================================================================================
1711 * Return Solid by ID
1713 Solid* Grid::GetSolid( TGeomID solidID )
1715 if ( !solidID || _geometry.IsOneSolid() || _geometry._solidByID.empty() )
1716 return & _geometry._soleSolid;
1718 return & _geometry._solidByID[ solidID ];
1720 //================================================================================
1722 * Return OneOfSolids by ID
1724 Solid* Grid::GetOneOfSolids( TGeomID solidID )
1726 map< TGeomID, OneOfSolids >::iterator is2s = _geometry._solidByID.find( solidID );
1727 if ( is2s != _geometry._solidByID.end() )
1728 return & is2s->second;
1730 return & _geometry._soleSolid;
1732 //================================================================================
1734 * Check if transition on given FACE is correct for a given SOLID
1736 bool Grid::IsCorrectTransition( TGeomID faceID, const Solid* solid )
1738 if ( _geometry.IsOneSolid() )
1741 const vector< TGeomID >& solidIDs = _geometry._solidIDsByShapeID[ faceID ];
1742 return solidIDs[0] == solid->ID();
1745 //================================================================================
1747 * Assign to geometry a node at FACE intersection
1748 * Return a found supporting VERTEX
1750 void Grid::SetOnShape( const SMDS_MeshNode* n, const F_IntersectPoint& ip,
1751 TopoDS_Vertex* vertex, bool unset )
1754 SMESHDS_Mesh* mesh = _helper->GetMeshDS();
1755 if ( ip._faceIDs.size() == 1 )
1757 mesh->SetNodeOnFace( n, ip._faceIDs[0], ip._u, ip._v );
1759 else if ( _geometry._vertexClassifier.IsSatisfy( n, &s ))
1761 if ( unset ) mesh->UnSetNodeOnShape( n );
1762 mesh->SetNodeOnVertex( n, TopoDS::Vertex( s ));
1764 *vertex = TopoDS::Vertex( s );
1766 else if ( _geometry._edgeClassifier.IsSatisfy( n, &s ))
1768 if ( unset ) mesh->UnSetNodeOnShape( n );
1769 mesh->SetNodeOnEdge( n, TopoDS::Edge( s ));
1771 else if ( ip._faceIDs.size() > 0 )
1773 mesh->SetNodeOnFace( n, ip._faceIDs[0], ip._u, ip._v );
1775 else if ( !unset && _geometry.IsOneSolid() )
1777 mesh->SetNodeInVolume( n, _geometry._soleSolid.ID() );
1780 //================================================================================
1782 * Fill in B_IntersectPoint::_faceIDs with all FACEs sharing a VERTEX
1784 void Grid::UpdateFacesOfVertex( const B_IntersectPoint& ip, const TopoDS_Vertex& vertex )
1786 if ( vertex.IsNull() )
1788 std::vector< int > faceID(1);
1789 PShapeIteratorPtr fIt = _helper->GetAncestors( vertex, *_helper->GetMesh(),
1790 TopAbs_FACE, & _geometry._mainShape );
1791 while ( const TopoDS_Shape* face = fIt->next() )
1793 faceID[ 0 ] = ShapeID( *face );
1797 //================================================================================
1799 * Initialize a classifier
1801 void Grid::InitClassifier( const TopoDS_Shape& mainShape,
1802 TopAbs_ShapeEnum shapeType,
1803 Controls::ElementsOnShape& classifier )
1805 TopTools_IndexedMapOfShape shapes;
1806 TopExp::MapShapes( mainShape, shapeType, shapes );
1808 TopoDS_Compound compound; BRep_Builder builder;
1809 builder.MakeCompound( compound );
1810 for ( int i = 1; i <= shapes.Size(); ++i )
1811 builder.Add( compound, shapes(i) );
1813 classifier.SetMesh( _helper->GetMeshDS() );
1814 //classifier.SetTolerance( _tol ); // _tol is not initialised
1815 classifier.SetShape( compound, SMDSAbs_Node );
1818 //================================================================================
1820 * Return EDGEs with FACEs to implement into the mesh
1822 void Grid::GetEdgesToImplement( map< TGeomID, vector< TGeomID > > & edge2faceIDsMap,
1823 const TopoDS_Shape& shape,
1824 const vector< TopoDS_Shape >& faces )
1826 // check if there are strange EDGEs
1827 TopTools_IndexedMapOfShape faceMap;
1828 TopExp::MapShapes( _helper->GetMesh()->GetShapeToMesh(), TopAbs_FACE, faceMap );
1829 int nbFacesGlobal = faceMap.Size();
1830 faceMap.Clear( false );
1831 TopExp::MapShapes( shape, TopAbs_FACE, faceMap );
1832 int nbFacesLocal = faceMap.Size();
1833 bool hasStrangeEdges = ( nbFacesGlobal > nbFacesLocal );
1834 if ( !_toAddEdges && !hasStrangeEdges )
1835 return; // no FACEs in contact with those meshed by other algo
1837 for ( size_t i = 0; i < faces.size(); ++i )
1839 _helper->SetSubShape( faces[i] );
1840 for ( TopExp_Explorer eExp( faces[i], TopAbs_EDGE ); eExp.More(); eExp.Next() )
1842 const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
1843 if ( hasStrangeEdges )
1845 bool hasStrangeFace = false;
1846 PShapeIteratorPtr faceIt = _helper->GetAncestors( edge, *_helper->GetMesh(), TopAbs_FACE);
1847 while ( const TopoDS_Shape* face = faceIt->next() )
1848 if (( hasStrangeFace = !faceMap.Contains( *face )))
1850 if ( !hasStrangeFace && !_toAddEdges )
1852 _geometry._strangeEdges.Add( ShapeID( edge ));
1853 _geometry._strangeEdges.Add( ShapeID( _helper->IthVertex( 0, edge )));
1854 _geometry._strangeEdges.Add( ShapeID( _helper->IthVertex( 1, edge )));
1856 if ( !SMESH_Algo::isDegenerated( edge ) &&
1857 !_helper->IsRealSeam( edge ))
1859 edge2faceIDsMap[ ShapeID( edge )].push_back( ShapeID( faces[i] ));
1866 //================================================================================
1868 * Computes coordinates of a point in the grid CS
1870 void Grid::ComputeUVW(const gp_XYZ& P, double UVW[3])
1872 gp_XYZ p = P * _invB;
1873 p.Coord( UVW[0], UVW[1], UVW[2] );
1875 //================================================================================
1879 void Grid::ComputeNodes(SMESH_MesherHelper& helper)
1881 // state of each node of the grid relative to the geometry
1882 const size_t nbGridNodes = _coords[0].size() * _coords[1].size() * _coords[2].size();
1883 vector< TGeomID > shapeIDVec( nbGridNodes, theUndefID );
1884 _nodes.resize( nbGridNodes, 0 );
1885 _gridIntP.resize( nbGridNodes, NULL );
1887 SMESHDS_Mesh* mesh = helper.GetMeshDS();
1889 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1891 LineIndexer li = GetLineIndexer( iDir );
1893 // find out a shift of node index while walking along a GridLine in this direction
1894 li.SetIndexOnLine( 0 );
1895 size_t nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1896 li.SetIndexOnLine( 1 );
1897 const size_t nShift = NodeIndex( li.I(), li.J(), li.K() ) - nIndex0;
1899 const vector<double> & coords = _coords[ iDir ];
1900 for ( ; li.More(); ++li ) // loop on lines in iDir
1902 li.SetIndexOnLine( 0 );
1903 nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1905 GridLine& line = _lines[ iDir ][ li.LineIndex() ];
1906 const gp_XYZ lineLoc = line._line.Location().XYZ();
1907 const gp_XYZ lineDir = line._line.Direction().XYZ();
1909 line.RemoveExcessIntPoints( _tol );
1910 multiset< F_IntersectPoint >& intPnts = line._intPoints;
1911 multiset< F_IntersectPoint >::iterator ip = intPnts.begin();
1913 // Create mesh nodes at intersections with geometry
1914 // and set OUT state of nodes between intersections
1916 TGeomID solidID = 0;
1917 const double* nodeCoord = & coords[0];
1918 const double* coord0 = nodeCoord;
1919 const double* coordEnd = coord0 + coords.size();
1920 double nodeParam = 0;
1921 for ( ; ip != intPnts.end(); ++ip )
1923 solidID = line.GetSolidIDBefore( ip, solidID, _geometry );
1925 // set OUT state or just skip IN nodes before ip
1926 if ( nodeParam < ip->_paramOnLine - _tol )
1928 while ( nodeParam < ip->_paramOnLine - _tol )
1930 TGeomID & nodeShapeID = shapeIDVec[ nIndex0 + nShift * ( nodeCoord-coord0 ) ];
1931 nodeShapeID = Min( solidID, nodeShapeID );
1932 if ( ++nodeCoord < coordEnd )
1933 nodeParam = *nodeCoord - *coord0;
1937 if ( nodeCoord == coordEnd ) break;
1939 // create a mesh node on a GridLine at ip if it does not coincide with a grid node
1940 if ( nodeParam > ip->_paramOnLine + _tol )
1942 gp_XYZ xyz = lineLoc + ip->_paramOnLine * lineDir;
1943 ip->_node = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1944 ip->_indexOnLine = nodeCoord-coord0-1;
1946 SetOnShape( ip->_node, *ip, & v );
1947 UpdateFacesOfVertex( *ip, v );
1949 // create a mesh node at ip coincident with a grid node
1952 int nodeIndex = nIndex0 + nShift * ( nodeCoord-coord0 );
1953 if ( !_nodes[ nodeIndex ] )
1955 gp_XYZ xyz = lineLoc + nodeParam * lineDir;
1956 _nodes [ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1957 //_gridIntP[ nodeIndex ] = & * ip;
1958 //SetOnShape( _nodes[ nodeIndex ], *ip );
1960 if ( _gridIntP[ nodeIndex ] )
1961 _gridIntP[ nodeIndex ]->Add( ip->_faceIDs );
1963 _gridIntP[ nodeIndex ] = & * ip;
1964 // ip->_node = _nodes[ nodeIndex ]; -- to differ from ip on links
1965 ip->_indexOnLine = nodeCoord-coord0;
1966 if ( ++nodeCoord < coordEnd )
1967 nodeParam = *nodeCoord - *coord0;
1970 // set OUT state to nodes after the last ip
1971 for ( ; nodeCoord < coordEnd; ++nodeCoord )
1972 shapeIDVec[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = 0;
1976 // Create mesh nodes at !OUT nodes of the grid
1978 for ( size_t z = 0; z < _coords[2].size(); ++z )
1979 for ( size_t y = 0; y < _coords[1].size(); ++y )
1980 for ( size_t x = 0; x < _coords[0].size(); ++x )
1982 size_t nodeIndex = NodeIndex( x, y, z );
1983 if ( !_nodes[ nodeIndex ] &&
1984 0 < shapeIDVec[ nodeIndex ] && shapeIDVec[ nodeIndex ] < theUndefID )
1986 gp_XYZ xyz = ( _coords[0][x] * _axes[0] +
1987 _coords[1][y] * _axes[1] +
1988 _coords[2][z] * _axes[2] );
1989 _nodes[ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1990 mesh->SetNodeInVolume( _nodes[ nodeIndex ], shapeIDVec[ nodeIndex ]);
1992 else if ( _nodes[ nodeIndex ] && _gridIntP[ nodeIndex ] /*&&
1993 !_nodes[ nodeIndex]->GetShapeID()*/ )
1996 SetOnShape( _nodes[ nodeIndex ], *_gridIntP[ nodeIndex ], & v );
1997 UpdateFacesOfVertex( *_gridIntP[ nodeIndex ], v );
2002 // check validity of transitions
2003 const char* trName[] = { "TANGENT", "IN", "OUT", "APEX" };
2004 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
2006 LineIndexer li = GetLineIndexer( iDir );
2007 for ( ; li.More(); ++li )
2009 multiset< F_IntersectPoint >& intPnts = _lines[ iDir ][ li.LineIndex() ]._intPoints;
2010 if ( intPnts.empty() ) continue;
2011 if ( intPnts.size() == 1 )
2013 if ( intPnts.begin()->_transition != Trans_TANGENT &&
2014 intPnts.begin()->_transition != Trans_APEX )
2015 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
2016 SMESH_Comment("Wrong SOLE transition of GridLine (")
2017 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
2018 << ") along " << li._nameConst
2019 << ": " << trName[ intPnts.begin()->_transition] );
2023 if ( intPnts.begin()->_transition == Trans_OUT )
2024 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
2025 SMESH_Comment("Wrong START transition of GridLine (")
2026 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
2027 << ") along " << li._nameConst
2028 << ": " << trName[ intPnts.begin()->_transition ]);
2029 if ( intPnts.rbegin()->_transition == Trans_IN )
2030 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
2031 SMESH_Comment("Wrong END transition of GridLine (")
2032 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
2033 << ") along " << li._nameConst
2034 << ": " << trName[ intPnts.rbegin()->_transition ]);
2043 //=============================================================================
2045 * Intersects TopoDS_Face with all GridLine's
2047 void FaceGridIntersector::Intersect()
2049 FaceLineIntersector intersector;
2050 intersector._surfaceInt = GetCurveFaceIntersector();
2051 intersector._tol = _grid->_tol;
2052 intersector._transOut = _face.Orientation() == TopAbs_REVERSED ? Trans_IN : Trans_OUT;
2053 intersector._transIn = _face.Orientation() == TopAbs_REVERSED ? Trans_OUT : Trans_IN;
2055 typedef void (FaceLineIntersector::* PIntFun )(const GridLine& gridLine);
2056 PIntFun interFunction;
2058 bool isDirect = true;
2059 BRepAdaptor_Surface surf( _face );
2060 switch ( surf.GetType() ) {
2062 intersector._plane = surf.Plane();
2063 interFunction = &FaceLineIntersector::IntersectWithPlane;
2064 isDirect = intersector._plane.Direct();
2066 case GeomAbs_Cylinder:
2067 intersector._cylinder = surf.Cylinder();
2068 interFunction = &FaceLineIntersector::IntersectWithCylinder;
2069 isDirect = intersector._cylinder.Direct();
2072 intersector._cone = surf.Cone();
2073 interFunction = &FaceLineIntersector::IntersectWithCone;
2074 //isDirect = intersector._cone.Direct();
2076 case GeomAbs_Sphere:
2077 intersector._sphere = surf.Sphere();
2078 interFunction = &FaceLineIntersector::IntersectWithSphere;
2079 isDirect = intersector._sphere.Direct();
2082 intersector._torus = surf.Torus();
2083 interFunction = &FaceLineIntersector::IntersectWithTorus;
2084 //isDirect = intersector._torus.Direct();
2087 interFunction = &FaceLineIntersector::IntersectWithSurface;
2090 std::swap( intersector._transOut, intersector._transIn );
2092 _intersections.clear();
2093 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
2095 if ( surf.GetType() == GeomAbs_Plane )
2097 // check if all lines in this direction are parallel to a plane
2098 if ( intersector._plane.Axis().IsNormal( _grid->_lines[iDir][0]._line.Position(),
2099 Precision::Angular()))
2101 // find out a transition, that is the same for all lines of a direction
2102 gp_Dir plnNorm = intersector._plane.Axis().Direction();
2103 gp_Dir lineDir = _grid->_lines[iDir][0]._line.Direction();
2104 intersector._transition =
2105 ( plnNorm * lineDir < 0 ) ? intersector._transIn : intersector._transOut;
2107 if ( surf.GetType() == GeomAbs_Cylinder )
2109 // check if all lines in this direction are parallel to a cylinder
2110 if ( intersector._cylinder.Axis().IsParallel( _grid->_lines[iDir][0]._line.Position(),
2111 Precision::Angular()))
2115 // intersect the grid lines with the face
2116 for ( size_t iL = 0; iL < _grid->_lines[iDir].size(); ++iL )
2118 GridLine& gridLine = _grid->_lines[iDir][iL];
2119 if ( _bndBox.IsOut( gridLine._line )) continue;
2121 intersector._intPoints.clear();
2122 (intersector.*interFunction)( gridLine ); // <- intersection with gridLine
2123 for ( size_t i = 0; i < intersector._intPoints.size(); ++i )
2124 _intersections.push_back( make_pair( &gridLine, intersector._intPoints[i] ));
2128 if ( _face.Orientation() == TopAbs_INTERNAL )
2130 for ( size_t i = 0; i < _intersections.size(); ++i )
2131 if ( _intersections[i].second._transition == Trans_IN ||
2132 _intersections[i].second._transition == Trans_OUT )
2134 _intersections[i].second._transition = Trans_INTERNAL;
2139 //================================================================================
2141 * Return true if (_u,_v) is on the face
2143 bool FaceLineIntersector::UVIsOnFace() const
2145 TopAbs_State state = _surfaceInt->ClassifyUVPoint(gp_Pnt2d( _u,_v ));
2146 return ( state == TopAbs_IN || state == TopAbs_ON );
2148 //================================================================================
2150 * Store an intersection if it is IN or ON the face
2152 void FaceLineIntersector::addIntPoint(const bool toClassify)
2154 if ( !toClassify || UVIsOnFace() )
2157 p._paramOnLine = _w;
2160 p._transition = _transition;
2161 _intPoints.push_back( p );
2164 //================================================================================
2166 * Intersect a line with a plane
2168 void FaceLineIntersector::IntersectWithPlane(const GridLine& gridLine)
2170 IntAna_IntConicQuad linPlane( gridLine._line, _plane, Precision::Angular());
2171 _w = linPlane.ParamOnConic(1);
2172 if ( isParamOnLineOK( gridLine._length ))
2174 ElSLib::Parameters(_plane, linPlane.Point(1) ,_u,_v);
2178 //================================================================================
2180 * Intersect a line with a cylinder
2182 void FaceLineIntersector::IntersectWithCylinder(const GridLine& gridLine)
2184 IntAna_IntConicQuad linCylinder( gridLine._line, _cylinder );
2185 if ( linCylinder.IsDone() && linCylinder.NbPoints() > 0 )
2187 _w = linCylinder.ParamOnConic(1);
2188 if ( linCylinder.NbPoints() == 1 )
2189 _transition = Trans_TANGENT;
2191 _transition = _w < linCylinder.ParamOnConic(2) ? _transIn : _transOut;
2192 if ( isParamOnLineOK( gridLine._length ))
2194 ElSLib::Parameters(_cylinder, linCylinder.Point(1) ,_u,_v);
2197 if ( linCylinder.NbPoints() > 1 )
2199 _w = linCylinder.ParamOnConic(2);
2200 if ( isParamOnLineOK( gridLine._length ))
2202 ElSLib::Parameters(_cylinder, linCylinder.Point(2) ,_u,_v);
2203 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
2209 //================================================================================
2211 * Intersect a line with a cone
2213 void FaceLineIntersector::IntersectWithCone (const GridLine& gridLine)
2215 IntAna_IntConicQuad linCone(gridLine._line,_cone);
2216 if ( !linCone.IsDone() ) return;
2218 gp_Vec du, dv, norm;
2219 for ( int i = 1; i <= linCone.NbPoints(); ++i )
2221 _w = linCone.ParamOnConic( i );
2222 if ( !isParamOnLineOK( gridLine._length )) continue;
2223 ElSLib::Parameters(_cone, linCone.Point(i) ,_u,_v);
2226 ElSLib::D1( _u, _v, _cone, P, du, dv );
2228 double normSize2 = norm.SquareMagnitude();
2229 if ( normSize2 > Precision::Angular() * Precision::Angular() )
2231 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
2232 cos /= sqrt( normSize2 );
2233 if ( cos < -Precision::Angular() )
2234 _transition = _transIn;
2235 else if ( cos > Precision::Angular() )
2236 _transition = _transOut;
2238 _transition = Trans_TANGENT;
2242 _transition = Trans_APEX;
2244 addIntPoint( /*toClassify=*/false);
2248 //================================================================================
2250 * Intersect a line with a sphere
2252 void FaceLineIntersector::IntersectWithSphere (const GridLine& gridLine)
2254 IntAna_IntConicQuad linSphere(gridLine._line,_sphere);
2255 if ( linSphere.IsDone() && linSphere.NbPoints() > 0 )
2257 _w = linSphere.ParamOnConic(1);
2258 if ( linSphere.NbPoints() == 1 )
2259 _transition = Trans_TANGENT;
2261 _transition = _w < linSphere.ParamOnConic(2) ? _transIn : _transOut;
2262 if ( isParamOnLineOK( gridLine._length ))
2264 ElSLib::Parameters(_sphere, linSphere.Point(1) ,_u,_v);
2267 if ( linSphere.NbPoints() > 1 )
2269 _w = linSphere.ParamOnConic(2);
2270 if ( isParamOnLineOK( gridLine._length ))
2272 ElSLib::Parameters(_sphere, linSphere.Point(2) ,_u,_v);
2273 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
2279 //================================================================================
2281 * Intersect a line with a torus
2283 void FaceLineIntersector::IntersectWithTorus (const GridLine& gridLine)
2285 IntAna_IntLinTorus linTorus(gridLine._line,_torus);
2286 if ( !linTorus.IsDone()) return;
2288 gp_Vec du, dv, norm;
2289 for ( int i = 1; i <= linTorus.NbPoints(); ++i )
2291 _w = linTorus.ParamOnLine( i );
2292 if ( !isParamOnLineOK( gridLine._length )) continue;
2293 linTorus.ParamOnTorus( i, _u,_v );
2296 ElSLib::D1( _u, _v, _torus, P, du, dv );
2298 double normSize = norm.Magnitude();
2299 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
2301 if ( cos < -Precision::Angular() )
2302 _transition = _transIn;
2303 else if ( cos > Precision::Angular() )
2304 _transition = _transOut;
2306 _transition = Trans_TANGENT;
2307 addIntPoint( /*toClassify=*/false);
2311 //================================================================================
2313 * Intersect a line with a non-analytical surface
2315 void FaceLineIntersector::IntersectWithSurface (const GridLine& gridLine)
2317 _surfaceInt->Perform( gridLine._line, 0.0, gridLine._length );
2318 if ( !_surfaceInt->IsDone() ) return;
2319 for ( int i = 1; i <= _surfaceInt->NbPnt(); ++i )
2321 _transition = Transition( _surfaceInt->Transition( i ) );
2322 _w = _surfaceInt->WParameter( i );
2323 addIntPoint(/*toClassify=*/false);
2326 //================================================================================
2328 * check if its face can be safely intersected in a thread
2330 bool FaceGridIntersector::IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const
2335 TopLoc_Location loc;
2336 Handle(Geom_Surface) surf = BRep_Tool::Surface( _face, loc );
2337 Handle(Geom_RectangularTrimmedSurface) ts =
2338 Handle(Geom_RectangularTrimmedSurface)::DownCast( surf );
2339 while( !ts.IsNull() ) {
2340 surf = ts->BasisSurface();
2341 ts = Handle(Geom_RectangularTrimmedSurface)::DownCast(surf);
2343 if ( surf->IsKind( STANDARD_TYPE(Geom_BSplineSurface )) ||
2344 surf->IsKind( STANDARD_TYPE(Geom_BezierSurface )))
2345 if ( !noSafeTShapes.insert( _face.TShape().get() ).second )
2349 TopExp_Explorer exp( _face, TopAbs_EDGE );
2350 for ( ; exp.More(); exp.Next() )
2352 bool edgeIsSafe = true;
2353 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
2356 Handle(Geom_Curve) c = BRep_Tool::Curve( e, loc, f, l);
2359 Handle(Geom_TrimmedCurve) tc = Handle(Geom_TrimmedCurve)::DownCast(c);
2360 while( !tc.IsNull() ) {
2361 c = tc->BasisCurve();
2362 tc = Handle(Geom_TrimmedCurve)::DownCast(c);
2364 if ( c->IsKind( STANDARD_TYPE(Geom_BSplineCurve )) ||
2365 c->IsKind( STANDARD_TYPE(Geom_BezierCurve )))
2372 Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( e, surf, loc, f, l);
2375 Handle(Geom2d_TrimmedCurve) tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
2376 while( !tc.IsNull() ) {
2377 c2 = tc->BasisCurve();
2378 tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
2380 if ( c2->IsKind( STANDARD_TYPE(Geom2d_BSplineCurve )) ||
2381 c2->IsKind( STANDARD_TYPE(Geom2d_BezierCurve )))
2385 if ( !edgeIsSafe && !noSafeTShapes.insert( e.TShape().get() ).second )
2390 //================================================================================
2392 * \brief Creates topology of the hexahedron
2394 Hexahedron::Hexahedron(Grid* grid)
2395 : _grid( grid ), _nbFaceIntNodes(0), _hasTooSmall( false )
2397 _polygons.reserve(100); // to avoid reallocation;
2399 //set nodes shift within grid->_nodes from the node 000
2400 size_t dx = _grid->NodeIndexDX();
2401 size_t dy = _grid->NodeIndexDY();
2402 size_t dz = _grid->NodeIndexDZ();
2404 size_t i100 = i000 + dx;
2405 size_t i010 = i000 + dy;
2406 size_t i110 = i010 + dx;
2407 size_t i001 = i000 + dz;
2408 size_t i101 = i100 + dz;
2409 size_t i011 = i010 + dz;
2410 size_t i111 = i110 + dz;
2411 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V000 )] = i000;
2412 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V100 )] = i100;
2413 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V010 )] = i010;
2414 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V110 )] = i110;
2415 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V001 )] = i001;
2416 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V101 )] = i101;
2417 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V011 )] = i011;
2418 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V111 )] = i111;
2420 vector< int > idVec;
2421 // set nodes to links
2422 for ( int linkID = SMESH_Block::ID_Ex00; linkID <= SMESH_Block::ID_E11z; ++linkID )
2424 SMESH_Block::GetEdgeVertexIDs( linkID, idVec );
2425 _Link& link = _hexLinks[ SMESH_Block::ShapeIndex( linkID )];
2426 link._nodes[0] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[0] )];
2427 link._nodes[1] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[1] )];
2430 // set links to faces
2431 int interlace[4] = { 0, 3, 1, 2 }; // to walk by links around a face: { u0, 1v, u1, 0v }
2432 for ( int faceID = SMESH_Block::ID_Fxy0; faceID <= SMESH_Block::ID_F1yz; ++faceID )
2434 _Face& quad = _hexQuads[ SMESH_Block::ShapeIndex( faceID )];
2435 quad._name = (SMESH_Block::TShapeID) faceID;
2437 SMESH_Block::GetFaceEdgesIDs( faceID, idVec );
2438 bool revFace = ( faceID == SMESH_Block::ID_Fxy0 ||
2439 faceID == SMESH_Block::ID_Fx1z ||
2440 faceID == SMESH_Block::ID_F0yz );
2441 quad._links.resize(4);
2442 vector<_OrientedLink>::iterator frwLinkIt = quad._links.begin();
2443 vector<_OrientedLink>::reverse_iterator revLinkIt = quad._links.rbegin();
2444 for ( int i = 0; i < 4; ++i )
2446 bool revLink = revFace;
2447 if ( i > 1 ) // reverse links u1 and v0
2449 _OrientedLink& link = revFace ? *revLinkIt++ : *frwLinkIt++;
2450 link = _OrientedLink( & _hexLinks[ SMESH_Block::ShapeIndex( idVec[interlace[i]] )],
2455 //================================================================================
2457 * \brief Copy constructor
2459 Hexahedron::Hexahedron( const Hexahedron& other, size_t i, size_t j, size_t k, int cellID )
2460 :_grid( other._grid ), _nbFaceIntNodes(0), _i( i ), _j( j ), _k( k ), _hasTooSmall( false )
2462 _polygons.reserve(100); // to avoid reallocation;
2465 for ( int i = 0; i < 12; ++i )
2467 const _Link& srcLink = other._hexLinks[ i ];
2468 _Link& tgtLink = this->_hexLinks[ i ];
2469 tgtLink._nodes[0] = _hexNodes + ( srcLink._nodes[0] - other._hexNodes );
2470 tgtLink._nodes[1] = _hexNodes + ( srcLink._nodes[1] - other._hexNodes );
2473 for ( int i = 0; i < 6; ++i )
2475 const _Face& srcQuad = other._hexQuads[ i ];
2476 _Face& tgtQuad = this->_hexQuads[ i ];
2477 tgtQuad._name = srcQuad._name;
2478 tgtQuad._links.resize(4);
2479 for ( int j = 0; j < 4; ++j )
2481 const _OrientedLink& srcLink = srcQuad._links[ j ];
2482 _OrientedLink& tgtLink = tgtQuad._links[ j ];
2483 tgtLink._reverse = srcLink._reverse;
2484 tgtLink._link = _hexLinks + ( srcLink._link - other._hexLinks );
2488 if (SALOME::VerbosityActivated())
2492 //================================================================================
2494 * \brief Return IDs of SOLIDs interfering with this Hexahedron
2496 size_t Hexahedron::getSolids( TGeomID ids[] )
2498 if ( _grid->_geometry.IsOneSolid() )
2500 ids[0] = _grid->GetSolid()->ID();
2503 // count intersection points belonging to each SOLID
2505 id2NbPoints.reserve( 3 );
2507 _origNodeInd = _grid->NodeIndex( _i,_j,_k );
2508 for ( int iN = 0; iN < 8; ++iN )
2510 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
2511 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
2513 if ( _hexNodes[iN]._intPoint ) // intersection with a FACE
2515 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2517 const vector< TGeomID > & solidIDs =
2518 _grid->GetSolidIDs( _hexNodes[iN]._intPoint->_faceIDs[iF] );
2519 for ( size_t i = 0; i < solidIDs.size(); ++i )
2520 insertAndIncrement( solidIDs[i], id2NbPoints );
2523 else if ( _hexNodes[iN]._node ) // node inside a SOLID
2525 insertAndIncrement( _hexNodes[iN]._node->GetShapeID(), id2NbPoints );
2529 for ( int iL = 0; iL < 12; ++iL )
2531 const _Link& link = _hexLinks[ iL ];
2532 for ( size_t iP = 0; iP < link._fIntPoints.size(); ++iP )
2534 for ( size_t iF = 0; iF < link._fIntPoints[iP]->_faceIDs.size(); ++iF )
2536 const vector< TGeomID > & solidIDs =
2537 _grid->GetSolidIDs( link._fIntPoints[iP]->_faceIDs[iF] );
2538 for ( size_t i = 0; i < solidIDs.size(); ++i )
2539 insertAndIncrement( solidIDs[i], id2NbPoints );
2544 for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
2546 const vector< TGeomID > & solidIDs = _grid->GetSolidIDs( _eIntPoints[iP]->_shapeID );
2547 for ( size_t i = 0; i < solidIDs.size(); ++i )
2548 insertAndIncrement( solidIDs[i], id2NbPoints );
2551 size_t nbSolids = 0;
2552 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2553 if ( id2nb->second >= 3 )
2554 ids[ nbSolids++ ] = id2nb->first;
2559 //================================================================================
2561 * \brief Count cuts by INTERNAL FACEs and set _Node::_isInternalFlags
2563 bool Hexahedron::isCutByInternalFace( IsInternalFlag & maxFlag )
2566 id2NbPoints.reserve( 3 );
2568 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2569 for ( size_t iF = 0; iF < _intNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2571 if ( _grid->IsInternal( _intNodes[iN]._intPoint->_faceIDs[iF]))
2572 insertAndIncrement( _intNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2574 for ( size_t iN = 0; iN < 8; ++iN )
2575 if ( _hexNodes[iN]._intPoint )
2576 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2578 if ( _grid->IsInternal( _hexNodes[iN]._intPoint->_faceIDs[iF]))
2579 insertAndIncrement( _hexNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2582 maxFlag = IS_NOT_INTERNAL;
2583 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2585 TGeomID intFace = id2nb->first;
2586 IsInternalFlag intFlag = ( id2nb->second >= 3 ? IS_CUT_BY_INTERNAL_FACE : IS_INTERNAL );
2587 if ( intFlag > maxFlag )
2590 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2591 if ( _intNodes[iN].IsOnFace( intFace ))
2592 _intNodes[iN].SetInternal( intFlag );
2594 for ( size_t iN = 0; iN < 8; ++iN )
2595 if ( _hexNodes[iN].IsOnFace( intFace ))
2596 _hexNodes[iN].SetInternal( intFlag );
2602 //================================================================================
2604 * \brief Return any FACE interfering with this Hexahedron
2606 TGeomID Hexahedron::getAnyFace() const
2609 id2NbPoints.reserve( 3 );
2611 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2612 for ( size_t iF = 0; iF < _intNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2613 insertAndIncrement( _intNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2615 for ( size_t iN = 0; iN < 8; ++iN )
2616 if ( _hexNodes[iN]._intPoint )
2617 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2618 insertAndIncrement( _hexNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2620 for ( unsigned int minNb = 3; minNb > 0; --minNb )
2621 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2622 if ( id2nb->second >= minNb )
2623 return id2nb->first;
2628 //================================================================================
2630 * \brief Initializes IJK by Hexahedron index
2632 void Hexahedron::setIJK( size_t iCell )
2634 size_t iNbCell = _grid->_coords[0].size() - 1;
2635 size_t jNbCell = _grid->_coords[1].size() - 1;
2636 _i = iCell % iNbCell;
2637 _j = ( iCell % ( iNbCell * jNbCell )) / iNbCell;
2638 _k = iCell / iNbCell / jNbCell;
2641 //================================================================================
2643 * \brief Initializes its data by given grid cell (countered from zero)
2645 void Hexahedron::init( size_t iCell )
2651 //================================================================================
2653 * \brief Initializes its data by given grid cell nodes and intersections
2655 void Hexahedron::init( size_t i, size_t j, size_t k, const Solid* solid )
2657 _i = i; _j = j; _k = k;
2659 bool isCompute = solid;
2661 solid = _grid->GetSolid();
2663 // set nodes of grid to nodes of the hexahedron and
2664 // count nodes at hexahedron corners located IN and ON geometry
2665 _nbCornerNodes = _nbBndNodes = 0;
2666 _origNodeInd = _grid->NodeIndex( i,j,k );
2667 for ( int iN = 0; iN < 8; ++iN )
2669 _hexNodes[iN]._isInternalFlags = 0;
2671 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
2672 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
2674 if ( _hexNodes[iN]._node && !solid->Contains( _hexNodes[iN]._node->GetShapeID() ))
2675 _hexNodes[iN]._node = 0;
2676 if ( _hexNodes[iN]._intPoint && !solid->ContainsAny( _hexNodes[iN]._intPoint->_faceIDs ))
2677 _hexNodes[iN]._intPoint = 0;
2679 _nbCornerNodes += bool( _hexNodes[iN]._node );
2680 _nbBndNodes += bool( _hexNodes[iN]._intPoint );
2682 _sideLength[0] = _grid->_coords[0][i+1] - _grid->_coords[0][i];
2683 _sideLength[1] = _grid->_coords[1][j+1] - _grid->_coords[1][j];
2684 _sideLength[2] = _grid->_coords[2][k+1] - _grid->_coords[2][k];
2692 if ( _nbFaceIntNodes + _eIntPoints.size() > 0 &&
2693 _nbFaceIntNodes + _eIntPoints.size() + _nbCornerNodes > 3)
2695 _intNodes.reserve( 3 * ( _nbBndNodes + _nbFaceIntNodes + _eIntPoints.size() ));
2697 // this method can be called in parallel, so use own helper
2698 SMESH_MesherHelper helper( *_grid->_helper->GetMesh() );
2700 // Create sub-links (_Link::_splits) by splitting links with _Link::_fIntPoints
2701 // ---------------------------------------------------------------
2703 for ( int iLink = 0; iLink < 12; ++iLink )
2705 _Link& link = _hexLinks[ iLink ];
2706 link._fIntNodes.clear();
2707 link._fIntNodes.reserve( link._fIntPoints.size() );
2708 for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
2709 if ( solid->ContainsAny( link._fIntPoints[i]->_faceIDs ))
2711 _intNodes.push_back( _Node( 0, link._fIntPoints[i] ));
2712 link._fIntNodes.push_back( & _intNodes.back() );
2715 link._splits.clear();
2716 split._nodes[ 0 ] = link._nodes[0];
2717 bool isOut = ( ! link._nodes[0]->Node() );
2718 bool checkTransition;
2719 for ( size_t i = 0; i < link._fIntNodes.size(); ++i )
2721 const bool isGridNode = ( ! link._fIntNodes[i]->Node() );
2722 if ( !isGridNode ) // intersection non-coincident with a grid node
2724 if ( split._nodes[ 0 ]->Node() && !isOut )
2726 split._nodes[ 1 ] = link._fIntNodes[i];
2727 link._splits.push_back( split );
2729 split._nodes[ 0 ] = link._fIntNodes[i];
2730 checkTransition = true;
2732 else // FACE intersection coincident with a grid node (at link ends)
2734 checkTransition = ( i == 0 && link._nodes[0]->Node() );
2736 if ( checkTransition )
2738 const vector< TGeomID >& faceIDs = link._fIntNodes[i]->_intPoint->_faceIDs;
2739 if ( _grid->IsInternal( faceIDs.back() ))
2741 else if ( faceIDs.size() > 1 || _eIntPoints.size() > 0 )
2742 isOut = isOutPoint( link, i, helper, solid );
2745 bool okTransi = _grid->IsCorrectTransition( faceIDs[0], solid );
2746 switch ( link._fIntNodes[i]->FaceIntPnt()->_transition ) {
2747 case Trans_OUT: isOut = okTransi; break;
2748 case Trans_IN : isOut = !okTransi; break;
2750 isOut = isOutPoint( link, i, helper, solid );
2755 if ( link._nodes[ 1 ]->Node() && split._nodes[ 0 ]->Node() && !isOut )
2757 split._nodes[ 1 ] = link._nodes[1];
2758 link._splits.push_back( split );
2762 // Create _Node's at intersections with EDGEs.
2763 // --------------------------------------------
2764 // 1) add this->_eIntPoints to _Face::_eIntNodes
2765 // 2) fill _intNodes and _vIntNodes
2767 const double tol2 = _grid->_tol * _grid->_tol * 4;
2768 int facets[3], nbFacets, subEntity;
2770 for ( int iF = 0; iF < 6; ++iF )
2771 _hexQuads[ iF ]._eIntNodes.clear();
2773 for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
2775 if ( !solid->ContainsAny( _eIntPoints[iP]->_faceIDs ))
2777 nbFacets = getEntity( _eIntPoints[iP], facets, subEntity );
2778 _Node* equalNode = 0;
2779 switch( nbFacets ) {
2780 case 1: // in a _Face
2782 _Face& quad = _hexQuads[ facets[0] - SMESH_Block::ID_FirstF ];
2783 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2785 equalNode->Add( _eIntPoints[ iP ] );
2788 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2789 quad._eIntNodes.push_back( & _intNodes.back() );
2793 case 2: // on a _Link
2795 _Link& link = _hexLinks[ subEntity - SMESH_Block::ID_FirstE ];
2796 if ( link._splits.size() > 0 )
2798 equalNode = findEqualNode( link._fIntNodes, _eIntPoints[ iP ], tol2 );
2800 equalNode->Add( _eIntPoints[ iP ] );
2801 else if ( link._splits.size() == 1 &&
2802 link._splits[0]._nodes[0] &&
2803 link._splits[0]._nodes[1] )
2804 link._splits.clear(); // hex edge is divided by _eIntPoints[iP]
2809 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2810 bool newNodeUsed = false;
2811 for ( int iF = 0; iF < 2; ++iF )
2813 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
2814 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2816 equalNode->Add( _eIntPoints[ iP ] );
2819 quad._eIntNodes.push_back( & _intNodes.back() );
2824 _intNodes.pop_back();
2828 case 3: // at a corner
2830 _Node& node = _hexNodes[ subEntity - SMESH_Block::ID_FirstV ];
2833 if ( node._intPoint )
2834 node._intPoint->Add( _eIntPoints[ iP ]->_faceIDs, _eIntPoints[ iP ]->_node );
2838 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2839 for ( int iF = 0; iF < 3; ++iF )
2841 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
2842 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2844 equalNode->Add( _eIntPoints[ iP ] );
2847 quad._eIntNodes.push_back( & _intNodes.back() );
2853 } // switch( nbFacets )
2855 if ( nbFacets == 0 ||
2856 _grid->ShapeType( _eIntPoints[ iP ]->_shapeID ) == TopAbs_VERTEX )
2858 equalNode = findEqualNode( _vIntNodes, _eIntPoints[ iP ], tol2 );
2860 equalNode->Add( _eIntPoints[ iP ] );
2862 else if ( nbFacets == 0 ) {
2863 if ( _intNodes.empty() || _intNodes.back().EdgeIntPnt() != _eIntPoints[ iP ])
2864 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2865 _vIntNodes.push_back( & _intNodes.back() );
2868 } // loop on _eIntPoints
2871 else if (( 3 < _nbCornerNodes && _nbCornerNodes < 8 ) || // _nbFaceIntNodes == 0
2872 ( !_grid->_geometry.IsOneSolid() ))
2875 // create sub-links (_splits) of whole links
2876 for ( int iLink = 0; iLink < 12; ++iLink )
2878 _Link& link = _hexLinks[ iLink ];
2879 link._splits.clear();
2880 if ( link._nodes[ 0 ]->Node() && link._nodes[ 1 ]->Node() )
2882 split._nodes[ 0 ] = link._nodes[0];
2883 split._nodes[ 1 ] = link._nodes[1];
2884 link._splits.push_back( split );
2890 } // init( _i, _j, _k )
2892 //================================================================================
2894 * \brief Compute mesh volumes resulted from intersection of the Hexahedron
2896 void Hexahedron::computeElements( const Solid* solid, int solidIndex )
2900 solid = _grid->GetSolid();
2901 if ( !_grid->_geometry.IsOneSolid() )
2903 TGeomID solidIDs[20] = { 0 };
2904 size_t nbSolids = getSolids( solidIDs );
2907 for ( size_t i = 0; i < nbSolids; ++i )
2909 solid = _grid->GetSolid( solidIDs[i] );
2910 computeElements( solid, i );
2911 if ( !_volumeDefs._nodes.empty() && i < nbSolids - 1 )
2912 _volumeDefs.SetNext( new _volumeDef( _volumeDefs ));
2916 solid = _grid->GetSolid( solidIDs[0] );
2920 init( _i, _j, _k, solid ); // get nodes and intersections from grid nodes and split links
2922 int nbIntersections = _nbFaceIntNodes + _eIntPoints.size();
2923 if ( _nbCornerNodes + nbIntersections < 4 )
2926 if ( _nbBndNodes == _nbCornerNodes && nbIntersections == 0 && isInHole() )
2927 return; // cell is in a hole
2929 IsInternalFlag intFlag = IS_NOT_INTERNAL;
2930 if ( solid->HasInternalFaces() && this->isCutByInternalFace( intFlag ))
2932 for ( _SplitIterator it( _hexLinks ); it.More(); it.Next() )
2934 if ( compute( solid, intFlag ))
2935 _volumeDefs.SetNext( new _volumeDef( _volumeDefs ));
2940 if ( solidIndex >= 0 )
2941 intFlag = IS_CUT_BY_INTERNAL_FACE;
2943 compute( solid, intFlag );
2947 //================================================================================
2949 * \brief Compute mesh volumes resulted from intersection of the Hexahedron
2951 bool Hexahedron::compute( const Solid* solid, const IsInternalFlag intFlag )
2954 _polygons.reserve( 20 );
2956 for ( int iN = 0; iN < 8; ++iN )
2957 _hexNodes[iN]._usedInFace = 0;
2959 if ( intFlag & IS_CUT_BY_INTERNAL_FACE && !_grid->_toAddEdges ) // Issue #19913
2960 preventVolumesOverlapping();
2962 std::set< TGeomID > concaveFaces; // to avoid connecting nodes laying on them
2964 if ( solid->HasConcaveVertex() )
2966 for ( const E_IntersectPoint* ip : _eIntPoints )
2968 if ( const ConcaveFace* cf = solid->GetConcave( ip->_shapeID ))
2969 if ( this->hasEdgesAround( cf ))
2970 concaveFaces.insert( cf->_concaveFace );
2972 if ( concaveFaces.empty() || concaveFaces.size() * 3 < _eIntPoints.size() )
2973 for ( const _Node& hexNode: _hexNodes )
2975 if ( hexNode._node && hexNode._intPoint && hexNode._intPoint->_faceIDs.size() >= 3 )
2976 if ( const ConcaveFace* cf = solid->GetConcave( hexNode._node->GetShapeID() ))
2977 if ( this->hasEdgesAround( cf ))
2978 concaveFaces.insert( cf->_concaveFace );
2982 // Create polygons from quadrangles
2983 // --------------------------------
2985 vector< _OrientedLink > splits;
2986 vector<_Node*> chainNodes;
2987 _Face* coplanarPolyg;
2989 const bool hasEdgeIntersections = !_eIntPoints.empty();
2990 const bool toCheckSideDivision = isImplementEdges() || intFlag & IS_CUT_BY_INTERNAL_FACE;
2992 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
2994 _Face& quad = _hexQuads[ iF ] ;
2996 _polygons.resize( _polygons.size() + 1 );
2997 _Face* polygon = &_polygons.back();
2998 polygon->_polyLinks.reserve( 20 );
2999 polygon->_name = quad._name;
3002 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
3003 for ( size_t iS = 0; iS < quad._links[ iE ].NbResultLinks(); ++iS )
3004 splits.push_back( quad._links[ iE ].ResultLink( iS ));
3006 if ( splits.size() == 4 &&
3007 isQuadOnFace( iF )) // check if a quad on FACE is not split
3009 polygon->_links.swap( splits );
3010 continue; // goto the next quad
3013 // add splits of links to a polygon and add _polyLinks to make
3014 // polygon's boundary closed
3016 int nbSplits = splits.size();
3017 if (( nbSplits == 1 ) &&
3018 ( quad._eIntNodes.empty() ||
3019 splits[0].FirstNode()->IsLinked( splits[0].LastNode()->_intPoint )))
3020 //( quad._eIntNodes.empty() || _nbCornerNodes + nbIntersections > 6 ))
3023 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
3024 if ( quad._eIntNodes[ iP ]->IsUsedInFace( polygon ))
3025 quad._eIntNodes[ iP ]->_usedInFace = 0;
3027 size_t nbUsedEdgeNodes = 0;
3028 _Face* prevPolyg = 0; // polygon previously created from this quad
3030 while ( nbSplits > 0 )
3033 while ( !splits[ iS ] )
3036 if ( !polygon->_links.empty() )
3038 _polygons.resize( _polygons.size() + 1 );
3039 polygon = &_polygons.back();
3040 polygon->_polyLinks.reserve( 20 );
3041 polygon->_name = quad._name;
3043 polygon->_links.push_back( splits[ iS ] );
3044 splits[ iS++ ]._link = 0;
3047 _Node* nFirst = polygon->_links.back().FirstNode();
3048 _Node *n1,*n2 = polygon->_links.back().LastNode();
3049 for ( ; nFirst != n2 && iS < splits.size(); ++iS )
3051 _OrientedLink& split = splits[ iS ];
3052 if ( !split ) continue;
3054 n1 = split.FirstNode();
3057 (( n1->_intPoint->_faceIDs.size() > 1 && toCheckSideDivision ) ||
3058 ( n1->_isInternalFlags )))
3060 // n1 is at intersection with EDGE
3061 if ( findChainOnEdge( splits, polygon->_links.back(), split, concaveFaces,
3062 iS, quad, chainNodes ))
3064 for ( size_t i = 1; i < chainNodes.size(); ++i )
3065 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
3066 if ( chainNodes.back() != n1 ) // not a partial cut by INTERNAL FACE
3068 prevPolyg = polygon;
3069 n2 = chainNodes.back();
3074 else if ( n1 != n2 )
3076 // try to connect to intersections with EDGEs
3077 if ( quad._eIntNodes.size() > nbUsedEdgeNodes &&
3078 findChain( n2, n1, quad, chainNodes ))
3080 for ( size_t i = 1; i < chainNodes.size(); ++i )
3082 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i] );
3083 nbUsedEdgeNodes += ( chainNodes[i]->IsUsedInFace( polygon ));
3085 if ( chainNodes.back() != n1 )
3087 n2 = chainNodes.back();
3092 // try to connect to a split ending on the same FACE
3095 _OrientedLink foundSplit;
3096 for ( size_t i = iS; i < splits.size() && !foundSplit; ++i )
3097 if (( foundSplit = splits[ i ]) &&
3098 ( n2->IsLinked( foundSplit.FirstNode()->_intPoint )))
3104 foundSplit._link = 0;
3108 if ( n2 != foundSplit.FirstNode() )
3110 polygon->AddPolyLink( n2, foundSplit.FirstNode() );
3111 n2 = foundSplit.FirstNode();
3117 if ( n2->IsLinked( nFirst->_intPoint ))
3119 polygon->AddPolyLink( n2, n1, prevPolyg );
3122 } // if ( n1 != n2 )
3124 polygon->_links.push_back( split );
3127 n2 = polygon->_links.back().LastNode();
3131 if ( nFirst != n2 ) // close a polygon
3133 if ( !findChain( n2, nFirst, quad, chainNodes ))
3135 if ( !closePolygon( polygon, chainNodes ))
3136 if ( !isImplementEdges() )
3137 chainNodes.push_back( nFirst );
3139 for ( size_t i = 1; i < chainNodes.size(); ++i )
3141 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
3142 nbUsedEdgeNodes += bool( chainNodes[i]->IsUsedInFace( polygon ));
3146 if ( polygon->_links.size() < 3 && nbSplits > 0 )
3148 polygon->_polyLinks.clear();
3149 polygon->_links.clear();
3151 } // while ( nbSplits > 0 )
3153 if ( polygon->_links.size() < 3 )
3155 _polygons.pop_back();
3157 } // loop on 6 hexahedron sides
3159 // Create polygons closing holes in a polyhedron
3160 // ----------------------------------------------
3162 // clear _usedInFace
3163 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
3164 _intNodes[ iN ]._usedInFace = 0;
3166 // add polygons to their links and mark used nodes
3167 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3169 _Face& polygon = _polygons[ iP ];
3170 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3172 polygon._links[ iL ].AddFace( &polygon );
3173 polygon._links[ iL ].FirstNode()->_usedInFace = &polygon;
3177 vector< _OrientedLink* > freeLinks;
3178 freeLinks.reserve(20);
3179 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3181 _Face& polygon = _polygons[ iP ];
3182 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3183 if ( polygon._links[ iL ].NbFaces() < 2 )
3184 freeLinks.push_back( & polygon._links[ iL ]);
3186 int nbFreeLinks = freeLinks.size();
3187 if ( nbFreeLinks == 1 ) return false;
3189 // put not used intersection nodes to _vIntNodes
3190 int nbVertexNodes = 0; // nb not used vertex nodes
3192 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
3193 nbVertexNodes += ( !_vIntNodes[ iN ]->IsUsedInFace() );
3195 const double tol = 1e-3 * Min( Min( _sideLength[0], _sideLength[1] ), _sideLength[0] );
3196 for ( size_t iN = _nbFaceIntNodes; iN < _intNodes.size(); ++iN )
3198 if ( _intNodes[ iN ].IsUsedInFace() ) continue;
3199 if ( dynamic_cast< const F_IntersectPoint* >( _intNodes[ iN ]._intPoint )) continue;
3201 findEqualNode( _vIntNodes, _intNodes[ iN ].EdgeIntPnt(), tol*tol );
3204 _vIntNodes.push_back( &_intNodes[ iN ]);
3210 std::set<TGeomID> usedFaceIDs;
3211 std::vector< TGeomID > faces;
3212 TGeomID curFace = 0;
3213 const size_t nbQuadPolygons = _polygons.size();
3214 E_IntersectPoint ipTmp;
3215 std::map< TGeomID, std::vector< const B_IntersectPoint* > > tmpAddedFace; // face added to _intPoint
3217 // create polygons by making closed chains of free links
3218 size_t iPolygon = _polygons.size();
3219 while ( nbFreeLinks > 0 )
3221 if ( iPolygon == _polygons.size() )
3223 _polygons.resize( _polygons.size() + 1 );
3224 _polygons[ iPolygon ]._polyLinks.reserve( 20 );
3225 _polygons[ iPolygon ]._links.reserve( 20 );
3227 _Face& polygon = _polygons[ iPolygon ];
3229 _OrientedLink* curLink = 0;
3231 if (( !hasEdgeIntersections ) ||
3232 ( nbFreeLinks < 4 && nbVertexNodes == 0 ))
3234 // get a remaining link to start from
3235 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3236 if (( curLink = freeLinks[ iL ] ))
3237 freeLinks[ iL ] = 0;
3238 polygon._links.push_back( *curLink );
3242 // find all links connected to curLink
3243 curNode = curLink->FirstNode();
3245 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3246 if ( freeLinks[ iL ] && freeLinks[ iL ]->LastNode() == curNode )
3248 curLink = freeLinks[ iL ];
3249 freeLinks[ iL ] = 0;
3251 polygon._links.push_back( *curLink );
3253 } while ( curLink );
3255 else // there are intersections with EDGEs
3257 // get a remaining link to start from, one lying on minimal nb of FACEs
3259 typedef pair< TGeomID, int > TFaceOfLink;
3260 TFaceOfLink faceOfLink( -1, -1 );
3261 TFaceOfLink facesOfLink[3] = { faceOfLink, faceOfLink, faceOfLink };
3262 for ( size_t iL = 0; iL < freeLinks.size(); ++iL )
3263 if ( freeLinks[ iL ] )
3265 faces = freeLinks[ iL ]->GetNotUsedFace( usedFaceIDs );
3266 if ( faces.size() == 1 )
3268 faceOfLink = TFaceOfLink( faces[0], iL );
3269 if ( !freeLinks[ iL ]->HasEdgeNodes() )
3271 facesOfLink[0] = faceOfLink;
3273 else if ( facesOfLink[0].first < 0 )
3275 faceOfLink = TFaceOfLink(( faces.empty() ? -1 : faces[0]), iL );
3276 facesOfLink[ 1 + faces.empty() ] = faceOfLink;
3279 for ( int i = 0; faceOfLink.first < 0 && i < 3; ++i )
3280 faceOfLink = facesOfLink[i];
3282 if ( faceOfLink.first < 0 ) // all faces used
3284 for ( size_t iL = 0; iL < freeLinks.size() && faceOfLink.first < 1; ++iL )
3285 if (( curLink = freeLinks[ iL ]))
3288 curLink->FirstNode()->IsLinked( curLink->LastNode()->_intPoint );
3289 faceOfLink.second = iL;
3291 usedFaceIDs.clear();
3293 curFace = faceOfLink.first;
3294 curLink = freeLinks[ faceOfLink.second ];
3295 freeLinks[ faceOfLink.second ] = 0;
3297 usedFaceIDs.insert( curFace );
3298 polygon._links.push_back( *curLink );
3301 // find all links lying on a curFace
3304 // go forward from curLink
3305 curNode = curLink->LastNode();
3307 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3308 if ( freeLinks[ iL ] &&
3309 freeLinks[ iL ]->FirstNode() == curNode &&
3310 freeLinks[ iL ]->LastNode()->IsOnFace( curFace ))
3312 curLink = freeLinks[ iL ];
3313 freeLinks[ iL ] = 0;
3314 polygon._links.push_back( *curLink );
3317 } while ( curLink );
3319 std::reverse( polygon._links.begin(), polygon._links.end() );
3321 curLink = & polygon._links.back();
3324 // go backward from curLink
3325 curNode = curLink->FirstNode();
3327 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3328 if ( freeLinks[ iL ] &&
3329 freeLinks[ iL ]->LastNode() == curNode &&
3330 freeLinks[ iL ]->FirstNode()->IsOnFace( curFace ))
3332 curLink = freeLinks[ iL ];
3333 freeLinks[ iL ] = 0;
3334 polygon._links.push_back( *curLink );
3337 } while ( curLink );
3339 curNode = polygon._links.back().FirstNode();
3341 if ( polygon._links[0].LastNode() != curNode )
3343 if ( nbVertexNodes > 0 )
3345 // add links with _vIntNodes if not already used
3347 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
3348 if ( !_vIntNodes[ iN ]->IsUsedInFace() &&
3349 _vIntNodes[ iN ]->IsOnFace( curFace ))
3351 _vIntNodes[ iN ]->_usedInFace = &polygon;
3352 chainNodes.push_back( _vIntNodes[ iN ] );
3354 if ( chainNodes.size() > 1 &&
3355 curFace != _grid->PseudoIntExtFaceID() ) /////// TODO
3357 sortVertexNodes( chainNodes, curNode, curFace );
3359 for ( size_t i = 0; i < chainNodes.size(); ++i )
3361 polygon.AddPolyLink( chainNodes[ i ], curNode );
3362 curNode = chainNodes[ i ];
3363 freeLinks.push_back( &polygon._links.back() );
3366 nbVertexNodes -= chainNodes.size();
3368 // if ( polygon._links.size() > 1 )
3370 polygon.AddPolyLink( polygon._links[0].LastNode(), curNode );
3371 freeLinks.push_back( &polygon._links.back() );
3375 } // if there are intersections with EDGEs
3377 if ( polygon._links.size() < 2 ||
3378 polygon._links[0].LastNode() != polygon._links.back().FirstNode() )
3381 break; // closed polygon not found -> invalid polyhedron
3384 if ( polygon._links.size() == 2 )
3386 if ( freeLinks.back() == &polygon._links.back() )
3388 freeLinks.pop_back();
3391 if ( polygon._links.front().NbFaces() > 0 )
3392 polygon._links.back().AddFace( polygon._links.front()._link->_faces[0] );
3393 if ( polygon._links.back().NbFaces() > 0 )
3394 polygon._links.front().AddFace( polygon._links.back()._link->_faces[0] );
3396 if ( iPolygon == _polygons.size()-1 )
3397 _polygons.pop_back();
3399 else // polygon._links.size() >= 2
3401 // add polygon to its links
3402 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3404 polygon._links[ iL ].AddFace( &polygon );
3405 polygon._links[ iL ].Reverse();
3407 if ( /*hasEdgeIntersections &&*/ iPolygon == _polygons.size() - 1 )
3409 // check that a polygon does not lie on a hexa side
3411 for ( size_t iL = 0; iL < polygon._links.size() && !coplanarPolyg; ++iL )
3413 if ( polygon._links[ iL ].NbFaces() < 2 )
3414 continue; // it's a just added free link
3415 // look for a polygon made on a hexa side and sharing
3416 // two or more haxa links
3418 coplanarPolyg = polygon._links[ iL ]._link->_faces[0];
3419 for ( iL2 = iL + 1; iL2 < polygon._links.size(); ++iL2 )
3420 if ( polygon._links[ iL2 ]._link->_faces[0] == coplanarPolyg &&
3421 !coplanarPolyg->IsPolyLink( polygon._links[ iL ]) &&
3422 !coplanarPolyg->IsPolyLink( polygon._links[ iL2 ]) &&
3423 coplanarPolyg < & _polygons[ nbQuadPolygons ])
3425 if ( iL2 == polygon._links.size() )
3428 if ( coplanarPolyg ) // coplanar polygon found
3430 freeLinks.resize( freeLinks.size() - polygon._polyLinks.size() );
3431 nbFreeLinks -= polygon._polyLinks.size();
3433 // an E_IntersectPoint used to mark nodes of coplanarPolyg
3434 // as lying on curFace while they are not at intersection with geometry
3435 ipTmp._faceIDs.resize(1);
3436 ipTmp._faceIDs[0] = curFace;
3438 // fill freeLinks with links not shared by coplanarPolyg and polygon
3439 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3440 if ( polygon._links[ iL ]._link->_faces[1] &&
3441 polygon._links[ iL ]._link->_faces[0] != coplanarPolyg )
3443 _Face* p = polygon._links[ iL ]._link->_faces[0];
3444 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
3445 if ( p->_links[ iL2 ]._link == polygon._links[ iL ]._link )
3447 freeLinks.push_back( & p->_links[ iL2 ] );
3449 freeLinks.back()->RemoveFace( &polygon );
3453 for ( size_t iL = 0; iL < coplanarPolyg->_links.size(); ++iL )
3454 if ( coplanarPolyg->_links[ iL ]._link->_faces[1] &&
3455 coplanarPolyg->_links[ iL ]._link->_faces[1] != &polygon )
3457 _Face* p = coplanarPolyg->_links[ iL ]._link->_faces[0];
3458 if ( p == coplanarPolyg )
3459 p = coplanarPolyg->_links[ iL ]._link->_faces[1];
3460 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
3461 if ( p->_links[ iL2 ]._link == coplanarPolyg->_links[ iL ]._link )
3463 // set links of coplanarPolyg in place of used freeLinks
3464 // to re-create coplanarPolyg next
3466 for ( ; iL3 < freeLinks.size() && freeLinks[ iL3 ]; ++iL3 );
3467 if ( iL3 < freeLinks.size() )
3468 freeLinks[ iL3 ] = ( & p->_links[ iL2 ] );
3470 freeLinks.push_back( & p->_links[ iL2 ] );
3472 freeLinks[ iL3 ]->RemoveFace( coplanarPolyg );
3473 // mark nodes of coplanarPolyg as lying on curFace
3474 for ( int iN = 0; iN < 2; ++iN )
3476 _Node* n = freeLinks[ iL3 ]->_link->_nodes[ iN ];
3478 if ( n->_intPoint ) added = n->_intPoint->Add( ipTmp._faceIDs );
3479 else n->_intPoint = &ipTmp;
3481 tmpAddedFace[ ipTmp._faceIDs[0] ].push_back( n->_intPoint );
3486 // set coplanarPolyg to be re-created next
3487 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3488 if ( coplanarPolyg == & _polygons[ iP ] )
3491 _polygons[ iPolygon ]._links.clear();
3492 _polygons[ iPolygon ]._polyLinks.clear();
3495 _polygons.pop_back();
3496 usedFaceIDs.erase( curFace );
3498 } // if ( coplanarPolyg )
3499 } // if ( hasEdgeIntersections ) - search for coplanarPolyg
3501 iPolygon = _polygons.size();
3503 } // end of case ( polygon._links.size() > 2 )
3504 } // while ( nbFreeLinks > 0 )
3506 for ( auto & face_ip : tmpAddedFace )
3508 curFace = face_ip.first;
3509 for ( const B_IntersectPoint* ip : face_ip.second )
3511 auto it = std::find( ip->_faceIDs.begin(), ip->_faceIDs.end(), curFace );
3512 if ( it != ip->_faceIDs.end() )
3513 ip->_faceIDs.erase( it );
3517 if ( _polygons.size() < 3 )
3520 // check volume size
3522 _hasTooSmall = ! checkPolyhedronSize( intFlag & IS_CUT_BY_INTERNAL_FACE, volSize );
3524 for ( size_t i = 0; i < 8; ++i )
3525 if ( _hexNodes[ i ]._intPoint == &ipTmp )
3526 _hexNodes[ i ]._intPoint = 0;
3529 return false; // too small volume
3532 // Try to find out names of no-name polygons (issue # 19887)
3533 if ( _grid->IsToRemoveExcessEntities() && _polygons.back()._name == SMESH_Block::ID_NONE )
3536 0.5 * ( _grid->_coords[0][_i] + _grid->_coords[0][_i+1] ) * _grid->_axes[0] +
3537 0.5 * ( _grid->_coords[1][_j] + _grid->_coords[1][_j+1] ) * _grid->_axes[1] +
3538 0.5 * ( _grid->_coords[2][_k] + _grid->_coords[2][_k+1] ) * _grid->_axes[2];
3539 for ( size_t i = _polygons.size() - 1; _polygons[i]._name == SMESH_Block::ID_NONE; --i )
3541 _Face& face = _polygons[ i ];
3544 for ( size_t iL = 0; iL < face._links.size(); ++iL )
3546 _Node* n = face._links[ iL ].FirstNode();
3547 gp_XYZ p = SMESH_NodeXYZ( n->Node() );
3548 _grid->ComputeUVW( p, uvw.ChangeCoord().ChangeData() );
3551 gp_Pnt pMin = bb.CornerMin();
3552 if ( bb.IsXThin( _grid->_tol ))
3553 face._name = pMin.X() < uvwCenter.X() ? SMESH_Block::ID_F0yz : SMESH_Block::ID_F1yz;
3554 else if ( bb.IsYThin( _grid->_tol ))
3555 face._name = pMin.Y() < uvwCenter.Y() ? SMESH_Block::ID_Fx0z : SMESH_Block::ID_Fx1z;
3556 else if ( bb.IsZThin( _grid->_tol ))
3557 face._name = pMin.Z() < uvwCenter.Z() ? SMESH_Block::ID_Fxy0 : SMESH_Block::ID_Fxy1;
3561 _volumeDefs._nodes.clear();
3562 _volumeDefs._quantities.clear();
3563 _volumeDefs._names.clear();
3564 // create a classic cell if possible
3567 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
3568 nbPolygons += (_polygons[ iF ]._links.size() > 2 );
3570 //const int nbNodes = _nbCornerNodes + nbIntersections;
3572 for ( size_t i = 0; i < 8; ++i )
3573 nbNodes += _hexNodes[ i ].IsUsedInFace();
3574 for ( size_t i = 0; i < _intNodes.size(); ++i )
3575 nbNodes += _intNodes[ i ].IsUsedInFace();
3577 bool isClassicElem = false;
3578 if ( nbNodes == 8 && nbPolygons == 6 ) isClassicElem = addHexa();
3579 else if ( nbNodes == 4 && nbPolygons == 4 ) isClassicElem = addTetra();
3580 else if ( nbNodes == 6 && nbPolygons == 5 ) isClassicElem = addPenta();
3581 else if ( nbNodes == 5 && nbPolygons == 5 ) isClassicElem = addPyra ();
3582 if ( !isClassicElem )
3584 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
3586 const size_t nbLinks = _polygons[ iF ]._links.size();
3587 if ( nbLinks < 3 ) continue;
3588 _volumeDefs._quantities.push_back( nbLinks );
3589 _volumeDefs._names.push_back( _polygons[ iF ]._name );
3590 for ( size_t iL = 0; iL < nbLinks; ++iL )
3591 _volumeDefs._nodes.push_back( _polygons[ iF ]._links[ iL ].FirstNode() );
3594 _volumeDefs._solidID = solid->ID();
3595 _volumeDefs._size = volSize;
3597 return !_volumeDefs._nodes.empty();
3599 //================================================================================
3601 * \brief Create elements in the mesh
3603 int Hexahedron::MakeElements(SMESH_MesherHelper& helper,
3604 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
3606 SMESHDS_Mesh* mesh = helper.GetMeshDS();
3608 CellsAroundLink c( _grid, 0 );
3609 const size_t nbGridCells = c._nbCells[0] * c._nbCells[1] * c._nbCells[2];
3610 vector< Hexahedron* > allHexa( nbGridCells, 0 );
3613 // set intersection nodes from GridLine's to links of allHexa
3614 int i,j,k, cellIndex, iLink;
3615 for ( int iDir = 0; iDir < 3; ++iDir )
3617 // loop on GridLine's parallel to iDir
3618 LineIndexer lineInd = _grid->GetLineIndexer( iDir );
3619 CellsAroundLink fourCells( _grid, iDir );
3620 for ( ; lineInd.More(); ++lineInd )
3622 GridLine& line = _grid->_lines[ iDir ][ lineInd.LineIndex() ];
3623 multiset< F_IntersectPoint >::const_iterator ip = line._intPoints.begin();
3624 for ( ; ip != line._intPoints.end(); ++ip )
3626 // if ( !ip->_node ) continue; // intersection at a grid node
3627 lineInd.SetIndexOnLine( ip->_indexOnLine );
3628 fourCells.Init( lineInd.I(), lineInd.J(), lineInd.K() );
3629 for ( int iL = 0; iL < 4; ++iL ) // loop on 4 cells sharing a link
3631 if ( !fourCells.GetCell( iL, i,j,k, cellIndex, iLink ))
3633 Hexahedron *& hex = allHexa[ cellIndex ];
3636 hex = new Hexahedron( *this, i, j, k, cellIndex );
3639 hex->_hexLinks[iLink]._fIntPoints.push_back( &(*ip) );
3640 hex->_nbFaceIntNodes += bool( ip->_node );
3646 // implement geom edges into the mesh
3647 addEdges( helper, allHexa, edge2faceIDsMap );
3649 // add not split hexahedra to the mesh
3651 TGeomID solidIDs[20];
3652 vector< Hexahedron* > intHexa; intHexa.reserve( nbIntHex );
3653 vector< const SMDS_MeshElement* > boundaryVolumes; boundaryVolumes.reserve( nbIntHex * 1.1 );
3654 for ( size_t i = 0; i < allHexa.size(); ++i )
3656 // initialize this by not cut allHexa[ i ]
3657 Hexahedron * & hex = allHexa[ i ];
3658 if ( hex ) // split hexahedron
3660 intHexa.push_back( hex );
3661 if ( hex->_nbFaceIntNodes > 0 ||
3662 hex->_eIntPoints.size() > 0 ||
3663 hex->getSolids( solidIDs ) > 1 )
3664 continue; // treat intersected hex later in parallel
3665 this->init( hex->_i, hex->_j, hex->_k );
3669 this->init( i ); // == init(i,j,k)
3671 if (( _nbCornerNodes == 8 ) &&
3672 ( _nbBndNodes < _nbCornerNodes || !isInHole() ))
3674 // order of _hexNodes is defined by enum SMESH_Block::TShapeID
3675 SMDS_MeshElement* el =
3676 mesh->AddVolume( _hexNodes[0].Node(), _hexNodes[2].Node(),
3677 _hexNodes[3].Node(), _hexNodes[1].Node(),
3678 _hexNodes[4].Node(), _hexNodes[6].Node(),
3679 _hexNodes[7].Node(), _hexNodes[5].Node() );
3680 TGeomID solidID = 0;
3681 if ( _nbBndNodes < _nbCornerNodes )
3683 for ( int iN = 0; iN < 8 && !solidID; ++iN )
3684 if ( !_hexNodes[iN]._intPoint ) // no intersection
3685 solidID = _hexNodes[iN].Node()->GetShapeID();
3689 getSolids( solidIDs );
3690 solidID = solidIDs[0];
3692 mesh->SetMeshElementOnShape( el, solidID );
3696 if ( _grid->_toCreateFaces && _nbBndNodes >= 3 )
3698 boundaryVolumes.push_back( el );
3699 el->setIsMarked( true );
3702 else if ( _nbCornerNodes > 3 && !hex )
3704 // all intersections of hex with geometry are at grid nodes
3705 hex = new Hexahedron( *this, _i, _j, _k, i );
3706 intHexa.push_back( hex );
3710 // compute definitions of volumes resulted from hexadron intersection
3712 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, intHexa.size() ),
3713 ParallelHexahedron( intHexa ),
3714 tbb::simple_partitioner()); // computeElements() is called here
3716 for ( size_t i = 0; i < intHexa.size(); ++i )
3717 if ( Hexahedron * hex = intHexa[ i ] )
3718 hex->computeElements();
3721 // simplify polyhedrons
3722 if ( _grid->IsToRemoveExcessEntities() )
3724 for ( size_t i = 0; i < intHexa.size(); ++i )
3725 if ( Hexahedron * hex = intHexa[ i ] )
3726 hex->removeExcessSideDivision( allHexa );
3728 for ( size_t i = 0; i < intHexa.size(); ++i )
3729 if ( Hexahedron * hex = intHexa[ i ] )
3730 hex->removeExcessNodes( allHexa );
3734 for ( size_t i = 0; i < intHexa.size(); ++i )
3735 if ( Hexahedron * hex = intHexa[ i ] )
3736 nbAdded += hex->addVolumes( helper );
3738 // fill boundaryVolumes with volumes neighboring too small skipped volumes
3739 if ( _grid->_toCreateFaces )
3741 for ( size_t i = 0; i < intHexa.size(); ++i )
3742 if ( Hexahedron * hex = intHexa[ i ] )
3743 hex->getBoundaryElems( boundaryVolumes );
3746 // merge nodes on outer sub-shapes with pre-existing ones
3747 TopTools_DataMapIteratorOfDataMapOfShapeInteger s2nIt( _grid->_geometry._shape2NbNodes );
3748 for ( ; s2nIt.More(); s2nIt.Next() )
3749 if ( s2nIt.Value() > 0 )
3750 if ( SMESHDS_SubMesh* sm = mesh->MeshElements( s2nIt.Key() ))
3752 TIDSortedNodeSet smNodes( SMDS_MeshElement::iterator( sm->GetNodes() ),
3753 SMDS_MeshElement::iterator() );
3754 SMESH_MeshEditor::TListOfListOfNodes equalNodes;
3755 SMESH_MeshEditor editor( helper.GetMesh() );
3756 editor.FindCoincidentNodes( smNodes, 10 * _grid->_tol, equalNodes,
3757 /*SeparateCornersAndMedium =*/ false);
3758 if ((int) equalNodes.size() <= s2nIt.Value() )
3759 editor.MergeNodes( equalNodes );
3762 // create boundary mesh faces
3763 addFaces( helper, boundaryVolumes );
3765 // create mesh edges
3766 addSegments( helper, edge2faceIDsMap );
3768 for ( size_t i = 0; i < allHexa.size(); ++i )
3770 delete allHexa[ i ];
3775 //================================================================================
3777 * \brief Implements geom edges into the mesh
3779 void Hexahedron::addEdges(SMESH_MesherHelper& helper,
3780 vector< Hexahedron* >& hexes,
3781 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
3783 if ( edge2faceIDsMap.empty() ) return;
3785 // Prepare planes for intersecting with EDGEs
3788 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ ) // iDirZ gives normal direction to planes
3790 GridPlanes& planes = pln[ iDirZ ];
3791 int iDirX = ( iDirZ + 1 ) % 3;
3792 int iDirY = ( iDirZ + 2 ) % 3;
3793 planes._zNorm = ( _grid->_axes[ iDirX ] ^ _grid->_axes[ iDirY ] ).Normalized();
3794 planes._zProjs.resize ( _grid->_coords[ iDirZ ].size() );
3795 planes._zProjs [0] = 0;
3796 const double zFactor = _grid->_axes[ iDirZ ] * planes._zNorm;
3797 const vector< double > & u = _grid->_coords[ iDirZ ];
3798 for ( size_t i = 1; i < planes._zProjs.size(); ++i )
3800 planes._zProjs [i] = zFactor * ( u[i] - u[0] );
3804 const double deflection = _grid->_minCellSize / 20.;
3805 const double tol = _grid->_tol;
3806 E_IntersectPoint ip;
3808 TColStd_MapOfInteger intEdgeIDs; // IDs of not shared INTERNAL EDGES
3810 // Intersect EDGEs with the planes
3811 map< TGeomID, vector< TGeomID > >::const_iterator e2fIt = edge2faceIDsMap.begin();
3812 for ( ; e2fIt != edge2faceIDsMap.end(); ++e2fIt )
3814 const TGeomID edgeID = e2fIt->first;
3815 const TopoDS_Edge & E = TopoDS::Edge( _grid->Shape( edgeID ));
3816 BRepAdaptor_Curve curve( E );
3817 TopoDS_Vertex v1 = helper.IthVertex( 0, E, false );
3818 TopoDS_Vertex v2 = helper.IthVertex( 1, E, false );
3820 ip._faceIDs = e2fIt->second;
3821 ip._shapeID = edgeID;
3823 bool isInternal = ( ip._faceIDs.size() == 1 && _grid->IsInternal( edgeID ));
3826 intEdgeIDs.Add( edgeID );
3827 intEdgeIDs.Add( _grid->ShapeID( v1 ));
3828 intEdgeIDs.Add( _grid->ShapeID( v2 ));
3831 // discretize the EDGE
3832 GCPnts_UniformDeflection discret( curve, deflection, true );
3833 if ( !discret.IsDone() || discret.NbPoints() < 2 )
3836 // perform intersection
3837 E_IntersectPoint* eip, *vip = 0;
3838 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ )
3840 GridPlanes& planes = pln[ iDirZ ];
3841 int iDirX = ( iDirZ + 1 ) % 3;
3842 int iDirY = ( iDirZ + 2 ) % 3;
3843 double xLen = _grid->_coords[ iDirX ].back() - _grid->_coords[ iDirX ][0];
3844 double yLen = _grid->_coords[ iDirY ].back() - _grid->_coords[ iDirY ][0];
3845 double zLen = _grid->_coords[ iDirZ ].back() - _grid->_coords[ iDirZ ][0];
3846 int dIJK[3], d000[3] = { 0,0,0 };
3847 double o[3] = { _grid->_coords[0][0],
3848 _grid->_coords[1][0],
3849 _grid->_coords[2][0] };
3851 // locate the 1st point of a segment within the grid
3852 gp_XYZ p1 = discret.Value( 1 ).XYZ();
3853 double u1 = discret.Parameter( 1 );
3854 double zProj1 = planes._zNorm * ( p1 - _grid->_origin );
3856 _grid->ComputeUVW( p1, ip._uvw );
3857 int iX1 = int(( ip._uvw[iDirX] - o[iDirX]) / xLen * (_grid->_coords[ iDirX ].size() - 1));
3858 int iY1 = int(( ip._uvw[iDirY] - o[iDirY]) / yLen * (_grid->_coords[ iDirY ].size() - 1));
3859 int iZ1 = int(( ip._uvw[iDirZ] - o[iDirZ]) / zLen * (_grid->_coords[ iDirZ ].size() - 1));
3860 locateValue( iX1, ip._uvw[iDirX], _grid->_coords[ iDirX ], dIJK[ iDirX ], tol );
3861 locateValue( iY1, ip._uvw[iDirY], _grid->_coords[ iDirY ], dIJK[ iDirY ], tol );
3862 locateValue( iZ1, ip._uvw[iDirZ], _grid->_coords[ iDirZ ], dIJK[ iDirZ ], tol );
3864 int ijk[3]; // grid index where a segment intersects a plane
3869 // add the 1st vertex point to a hexahedron
3873 ip._shapeID = _grid->ShapeID( v1 );
3874 vip = _grid->Add( ip );
3875 _grid->UpdateFacesOfVertex( *vip, v1 );
3877 vip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3878 if ( !addIntersection( vip, hexes, ijk, d000 ))
3879 _grid->Remove( vip );
3880 ip._shapeID = edgeID;
3882 for ( int iP = 2; iP <= discret.NbPoints(); ++iP )
3884 // locate the 2nd point of a segment within the grid
3885 gp_XYZ p2 = discret.Value( iP ).XYZ();
3886 double u2 = discret.Parameter( iP );
3887 double zProj2 = planes._zNorm * ( p2 - _grid->_origin );
3889 if ( Abs( zProj2 - zProj1 ) > std::numeric_limits<double>::min() )
3891 locateValue( iZ2, zProj2, planes._zProjs, dIJK[ iDirZ ], tol );
3893 // treat intersections with planes between 2 end points of a segment
3894 int dZ = ( iZ1 <= iZ2 ) ? +1 : -1;
3895 int iZ = iZ1 + ( iZ1 < iZ2 );
3896 for ( int i = 0, nb = Abs( iZ1 - iZ2 ); i < nb; ++i, iZ += dZ )
3898 ip._point = findIntPoint( u1, zProj1, u2, zProj2,
3899 planes._zProjs[ iZ ],
3900 curve, planes._zNorm, _grid->_origin );
3901 _grid->ComputeUVW( ip._point.XYZ(), ip._uvw );
3902 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
3903 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
3906 // add ip to hex "above" the plane
3907 eip = _grid->Add( ip );
3909 eip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3911 bool added = addIntersection( eip, hexes, ijk, dIJK);
3913 // add ip to hex "below" the plane
3914 ijk[ iDirZ ] = iZ-1;
3915 if ( !addIntersection( eip, hexes, ijk, dIJK ) &&
3917 _grid->Remove( eip );
3925 // add the 2nd vertex point to a hexahedron
3929 ip._shapeID = _grid->ShapeID( v2 );
3930 _grid->ComputeUVW( p1, ip._uvw );
3931 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
3932 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
3934 bool sameV = ( v1.IsSame( v2 ));
3937 vip = _grid->Add( ip );
3938 _grid->UpdateFacesOfVertex( *vip, v2 );
3940 vip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3942 if ( !addIntersection( vip, hexes, ijk, d000 ) && !sameV )
3943 _grid->Remove( vip );
3944 ip._shapeID = edgeID;
3946 } // loop on 3 grid directions
3950 if ( intEdgeIDs.Size() > 0 )
3951 cutByExtendedInternal( hexes, intEdgeIDs );
3956 //================================================================================
3958 * \brief Fully cut hexes that are partially cut by INTERNAL FACE.
3959 * Cut them by extended INTERNAL FACE.
3961 void Hexahedron::cutByExtendedInternal( std::vector< Hexahedron* >& hexes,
3962 const TColStd_MapOfInteger& intEdgeIDs )
3964 IntAna_IntConicQuad intersection;
3965 SMESHDS_Mesh* meshDS = _grid->_helper->GetMeshDS();
3966 const double tol2 = _grid->_tol * _grid->_tol;
3968 for ( size_t iH = 0; iH < hexes.size(); ++iH )
3970 Hexahedron* hex = hexes[ iH ];
3971 if ( !hex || hex->_eIntPoints.size() < 2 )
3973 if ( !intEdgeIDs.Contains( hex->_eIntPoints.back()->_shapeID ))
3976 // get 3 points on INTERNAL FACE to construct a cutting plane
3977 gp_Pnt p1 = hex->_eIntPoints[0]->_point;
3978 gp_Pnt p2 = hex->_eIntPoints[1]->_point;
3979 gp_Pnt p3 = hex->mostDistantInternalPnt( iH, p1, p2 );
3981 gp_Vec norm = gp_Vec( p1, p2 ) ^ gp_Vec( p1, p3 );
3984 pln = gp_Pln( p1, norm );
3991 TGeomID intFaceID = hex->_eIntPoints.back()->_faceIDs.front(); // FACE being "extended"
3992 TGeomID solidID = _grid->GetSolid( intFaceID )->ID();
3994 // cut links by the plane
3995 //bool isCut = false;
3996 for ( int iLink = 0; iLink < 12; ++iLink )
3998 _Link& link = hex->_hexLinks[ iLink ];
3999 if ( !link._fIntPoints.empty() )
4001 // if ( link._fIntPoints[0]->_faceIDs.back() == _grid->PseudoIntExtFaceID() )
4003 continue; // already cut link
4005 if ( !link._nodes[0]->Node() ||
4006 !link._nodes[1]->Node() )
4007 continue; // outside link
4009 if ( link._nodes[0]->IsOnFace( intFaceID ))
4011 if ( link._nodes[0]->_intPoint->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
4012 if ( p1.SquareDistance( link._nodes[0]->Point() ) < tol2 ||
4013 p2.SquareDistance( link._nodes[0]->Point() ) < tol2 )
4014 link._nodes[0]->_intPoint->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4015 continue; // link is cut by FACE being "extended"
4017 if ( link._nodes[1]->IsOnFace( intFaceID ))
4019 if ( link._nodes[1]->_intPoint->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
4020 if ( p1.SquareDistance( link._nodes[1]->Point() ) < tol2 ||
4021 p2.SquareDistance( link._nodes[1]->Point() ) < tol2 )
4022 link._nodes[1]->_intPoint->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4023 continue; // link is cut by FACE being "extended"
4025 gp_Pnt p4 = link._nodes[0]->Point();
4026 gp_Pnt p5 = link._nodes[1]->Point();
4027 gp_Lin line( p4, gp_Vec( p4, p5 ));
4029 intersection.Perform( line, pln );
4030 if ( !intersection.IsDone() ||
4031 intersection.IsInQuadric() ||
4032 intersection.IsParallel() ||
4033 intersection.NbPoints() < 1 )
4036 double u = intersection.ParamOnConic(1);
4037 if ( u + _grid->_tol < 0 )
4039 int iDir = iLink / 4;
4040 int index = (&hex->_i)[iDir];
4041 double linkLen = _grid->_coords[iDir][index+1] - _grid->_coords[iDir][index];
4042 if ( u - _grid->_tol > linkLen )
4045 if ( u < _grid->_tol ||
4046 u > linkLen - _grid->_tol ) // intersection at grid node
4048 int i = ! ( u < _grid->_tol ); // [0,1]
4049 int iN = link._nodes[ i ] - hex->_hexNodes; // [0-7]
4051 const F_IntersectPoint * & ip = _grid->_gridIntP[ hex->_origNodeInd +
4052 _grid->_nodeShift[iN] ];
4055 ip = _grid->_extIntPool.getNew();
4056 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4057 //ip->_transition = Trans_INTERNAL;
4059 else if ( ip->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
4061 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4063 hex->_nbFaceIntNodes++;
4068 const gp_Pnt& p = intersection.Point( 1 );
4069 F_IntersectPoint* ip = _grid->_extIntPool.getNew();
4070 ip->_node = meshDS->AddNode( p.X(), p.Y(), p.Z() );
4071 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4072 ip->_transition = Trans_INTERNAL;
4073 meshDS->SetNodeInVolume( ip->_node, solidID );
4075 CellsAroundLink fourCells( _grid, iDir );
4076 fourCells.Init( hex->_i, hex->_j, hex->_k, iLink );
4077 int i,j,k, cellIndex;
4078 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing the link
4080 if ( !fourCells.GetCell( iC, i,j,k, cellIndex, iLink ))
4082 Hexahedron * h = hexes[ cellIndex ];
4084 h = hexes[ cellIndex ] = new Hexahedron( *this, i, j, k, cellIndex );
4085 h->_hexLinks[iLink]._fIntPoints.push_back( ip );
4086 h->_nbFaceIntNodes++;
4093 // for ( size_t i = 0; i < hex->_eIntPoints.size(); ++i )
4095 // if ( _grid->IsInternal( hex->_eIntPoints[i]->_shapeID ) &&
4096 // ! hex->_eIntPoints[i]->IsOnFace( _grid->PseudoIntExtFaceID() ))
4097 // hex->_eIntPoints[i]->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4101 } // loop on all hexes
4105 //================================================================================
4107 * \brief Return intersection point on INTERNAL FACE most distant from given ones
4109 gp_Pnt Hexahedron::mostDistantInternalPnt( int hexIndex, const gp_Pnt& p1, const gp_Pnt& p2 )
4111 gp_Pnt resultPnt = p1;
4113 double maxDist2 = 0;
4114 for ( int iLink = 0; iLink < 12; ++iLink ) // check links
4116 _Link& link = _hexLinks[ iLink ];
4117 for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
4118 if ( _grid->PseudoIntExtFaceID() != link._fIntPoints[i]->_faceIDs[0] &&
4119 _grid->IsInternal( link._fIntPoints[i]->_faceIDs[0] ) &&
4120 link._fIntPoints[i]->_node )
4122 gp_Pnt p = SMESH_NodeXYZ( link._fIntPoints[i]->_node );
4123 double d = p1.SquareDistance( p );
4131 d = p2.SquareDistance( p );
4141 _origNodeInd = _grid->NodeIndex( _i,_j,_k );
4143 for ( size_t iN = 0; iN < 8; ++iN ) // check corners
4145 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
4146 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
4147 if ( _hexNodes[iN]._intPoint )
4148 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
4150 if ( _grid->IsInternal( _hexNodes[iN]._intPoint->_faceIDs[iF]))
4152 gp_Pnt p = SMESH_NodeXYZ( _hexNodes[iN]._node );
4153 double d = p1.SquareDistance( p );
4161 d = p2.SquareDistance( p );
4171 if ( maxDist2 < _grid->_tol * _grid->_tol )
4177 //================================================================================
4179 * \brief Finds intersection of a curve with a plane
4180 * \param [in] u1 - parameter of one curve point
4181 * \param [in] proj1 - projection of the curve point to the plane normal
4182 * \param [in] u2 - parameter of another curve point
4183 * \param [in] proj2 - projection of the other curve point to the plane normal
4184 * \param [in] proj - projection of a point where the curve intersects the plane
4185 * \param [in] curve - the curve
4186 * \param [in] axis - the plane normal
4187 * \param [in] origin - the plane origin
4188 * \return gp_Pnt - the found intersection point
4190 gp_Pnt Hexahedron::findIntPoint( double u1, double proj1,
4191 double u2, double proj2,
4193 BRepAdaptor_Curve& curve,
4195 const gp_XYZ& origin)
4197 double r = (( proj - proj1 ) / ( proj2 - proj1 ));
4198 double u = u1 * ( 1 - r ) + u2 * r;
4199 gp_Pnt p = curve.Value( u );
4200 double newProj = axis * ( p.XYZ() - origin );
4201 if ( Abs( proj - newProj ) > _grid->_tol / 10. )
4204 return findIntPoint( u2, proj2, u, newProj, proj, curve, axis, origin );
4206 return findIntPoint( u1, proj2, u, newProj, proj, curve, axis, origin );
4211 //================================================================================
4213 * \brief Returns indices of a hexahedron sub-entities holding a point
4214 * \param [in] ip - intersection point
4215 * \param [out] facets - 0-3 facets holding a point
4216 * \param [out] sub - index of a vertex or an edge holding a point
4217 * \return int - number of facets holding a point
4219 int Hexahedron::getEntity( const E_IntersectPoint* ip, int* facets, int& sub )
4221 enum { X = 1, Y = 2, Z = 4 }; // == 001, 010, 100
4223 int vertex = 0, edgeMask = 0;
4225 if ( Abs( _grid->_coords[0][ _i ] - ip->_uvw[0] ) < _grid->_tol ) {
4226 facets[ nbFacets++ ] = SMESH_Block::ID_F0yz;
4229 else if ( Abs( _grid->_coords[0][ _i+1 ] - ip->_uvw[0] ) < _grid->_tol ) {
4230 facets[ nbFacets++ ] = SMESH_Block::ID_F1yz;
4234 if ( Abs( _grid->_coords[1][ _j ] - ip->_uvw[1] ) < _grid->_tol ) {
4235 facets[ nbFacets++ ] = SMESH_Block::ID_Fx0z;
4238 else if ( Abs( _grid->_coords[1][ _j+1 ] - ip->_uvw[1] ) < _grid->_tol ) {
4239 facets[ nbFacets++ ] = SMESH_Block::ID_Fx1z;
4243 if ( Abs( _grid->_coords[2][ _k ] - ip->_uvw[2] ) < _grid->_tol ) {
4244 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy0;
4247 else if ( Abs( _grid->_coords[2][ _k+1 ] - ip->_uvw[2] ) < _grid->_tol ) {
4248 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy1;
4255 case 0: sub = 0; break;
4256 case 1: sub = facets[0]; break;
4258 const int edge [3][8] = {
4259 { SMESH_Block::ID_E00z, SMESH_Block::ID_E10z,
4260 SMESH_Block::ID_E01z, SMESH_Block::ID_E11z },
4261 { SMESH_Block::ID_E0y0, SMESH_Block::ID_E1y0, 0, 0,
4262 SMESH_Block::ID_E0y1, SMESH_Block::ID_E1y1 },
4263 { SMESH_Block::ID_Ex00, 0, SMESH_Block::ID_Ex10, 0,
4264 SMESH_Block::ID_Ex01, 0, SMESH_Block::ID_Ex11 }
4266 switch ( edgeMask ) {
4267 case X | Y: sub = edge[ 0 ][ vertex ]; break;
4268 case X | Z: sub = edge[ 1 ][ vertex ]; break;
4269 default: sub = edge[ 2 ][ vertex ];
4275 sub = vertex + SMESH_Block::ID_FirstV;
4280 //================================================================================
4282 * \brief Adds intersection with an EDGE
4284 bool Hexahedron::addIntersection( const E_IntersectPoint* ip,
4285 vector< Hexahedron* >& hexes,
4286 int ijk[], int dIJK[] )
4290 size_t hexIndex[4] = {
4291 _grid->CellIndex( ijk[0], ijk[1], ijk[2] ),
4292 dIJK[0] ? _grid->CellIndex( ijk[0]+dIJK[0], ijk[1], ijk[2] ) : -1,
4293 dIJK[1] ? _grid->CellIndex( ijk[0], ijk[1]+dIJK[1], ijk[2] ) : -1,
4294 dIJK[2] ? _grid->CellIndex( ijk[0], ijk[1], ijk[2]+dIJK[2] ) : -1
4296 for ( int i = 0; i < 4; ++i )
4298 if ( hexIndex[i] < hexes.size() && hexes[ hexIndex[i] ] )
4300 Hexahedron* h = hexes[ hexIndex[i] ];
4301 h->_eIntPoints.reserve(2);
4302 h->_eIntPoints.push_back( ip );
4305 // check if ip is really inside the hex
4306 if (SALOME::VerbosityActivated() && h->isOutParam( ip->_uvw ))
4307 throw SALOME_Exception("ip outside a hex");
4312 //================================================================================
4314 * \brief Check if a hexahedron facet lies on a FACE
4315 * Also return true if the facet does not interfere with any FACE
4317 bool Hexahedron::isQuadOnFace( const size_t iQuad )
4319 _Face& quad = _hexQuads[ iQuad ] ;
4321 int nbGridNodesInt = 0; // nb FACE intersections at grid nodes
4322 int nbNoGeomNodes = 0;
4323 for ( int iE = 0; iE < 4; ++iE )
4325 nbNoGeomNodes = ( !quad._links[ iE ].FirstNode()->_intPoint &&
4326 quad._links[ iE ].NbResultLinks() == 1 );
4328 ( quad._links[ iE ].FirstNode()->_intPoint &&
4329 quad._links[ iE ].NbResultLinks() == 1 &&
4330 quad._links[ iE ].ResultLink( 0 ).FirstNode() == quad._links[ iE ].FirstNode() &&
4331 quad._links[ iE ].ResultLink( 0 ).LastNode() == quad._links[ iE ].LastNode() );
4333 if ( nbNoGeomNodes == 4 )
4336 if ( nbGridNodesInt == 4 ) // all quad nodes are at FACE intersection
4338 size_t iEmin = 0, minNbFaces = 1000;
4339 for ( int iE = 0; iE < 4; ++iE ) // look for a node with min nb FACEs
4341 size_t nbFaces = quad._links[ iE ].FirstNode()->faces().size();
4342 if ( minNbFaces > nbFaces )
4345 minNbFaces = nbFaces;
4348 // check if there is a FACE passing through all 4 nodes
4349 for ( const TGeomID& faceID : quad._links[ iEmin ].FirstNode()->faces() )
4351 bool allNodesAtFace = true;
4352 for ( size_t iE = 0; iE < 4 && allNodesAtFace; ++iE )
4353 allNodesAtFace = ( iE == iEmin ||
4354 quad._links[ iE ].FirstNode()->IsOnFace( faceID ));
4355 if ( allNodesAtFace ) // quad if on faceID
4361 //================================================================================
4363 * \brief Finds nodes at a path from one node to another via intersections with EDGEs
4365 bool Hexahedron::findChain( _Node* n1,
4368 vector<_Node*>& chn )
4371 chn.push_back( n1 );
4372 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4373 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
4374 n1->IsLinked( quad._eIntNodes[ iP ]->_intPoint ) &&
4375 n2->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
4377 chn.push_back( quad._eIntNodes[ iP ]);
4378 chn.push_back( n2 );
4379 quad._eIntNodes[ iP ]->_usedInFace = &quad;
4386 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4387 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
4388 chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
4390 chn.push_back( quad._eIntNodes[ iP ]);
4391 found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
4394 } while ( found && ! chn.back()->IsLinked( n2->_intPoint ) );
4396 if ( chn.back() != n2 && chn.back()->IsLinked( n2->_intPoint ))
4397 chn.push_back( n2 );
4399 return chn.size() > 1;
4401 //================================================================================
4403 * \brief Try to heal a polygon whose ends are not connected
4405 bool Hexahedron::closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const
4407 int i = -1, nbLinks = polygon->_links.size();
4410 vector< _OrientedLink > newLinks;
4411 // find a node lying on the same FACE as the last one
4412 _Node* node = polygon->_links.back().LastNode();
4413 TGeomID avoidFace = node->IsLinked( polygon->_links.back().FirstNode()->_intPoint );
4414 for ( i = nbLinks - 2; i >= 0; --i )
4415 if ( node->IsLinked( polygon->_links[i].FirstNode()->_intPoint, avoidFace ))
4419 for ( ; i < nbLinks; ++i )
4420 newLinks.push_back( polygon->_links[i] );
4424 // find a node lying on the same FACE as the first one
4425 node = polygon->_links[0].FirstNode();
4426 avoidFace = node->IsLinked( polygon->_links[0].LastNode()->_intPoint );
4427 for ( i = 1; i < nbLinks; ++i )
4428 if ( node->IsLinked( polygon->_links[i].LastNode()->_intPoint, avoidFace ))
4431 for ( nbLinks = i + 1, i = 0; i < nbLinks; ++i )
4432 newLinks.push_back( polygon->_links[i] );
4434 if ( newLinks.size() > 1 )
4436 polygon->_links.swap( newLinks );
4438 chainNodes.push_back( polygon->_links.back().LastNode() );
4439 chainNodes.push_back( polygon->_links[0].FirstNode() );
4444 //================================================================================
4446 * \brief Finds nodes on the same EDGE as the first node of avoidSplit.
4448 * This function is for
4449 * 1) a case where an EDGE lies on a quad which lies on a FACE
4450 * so that a part of quad in ON and another part is IN
4451 * 2) INTERNAL FACE passes through the 1st node of avoidSplit
4453 bool Hexahedron::findChainOnEdge( const vector< _OrientedLink >& splits,
4454 const _OrientedLink& prevSplit,
4455 const _OrientedLink& avoidSplit,
4456 const std::set< TGeomID > & concaveFaces,
4459 vector<_Node*>& chn )
4461 _Node* pn1 = prevSplit.FirstNode();
4462 _Node* pn2 = prevSplit.LastNode(); // pn2 is on EDGE, if not on INTERNAL FACE
4463 _Node* an3 = avoidSplit.LastNode();
4464 TGeomID avoidFace = pn1->IsLinked( pn2->_intPoint ); // FACE under the quad
4465 if ( avoidFace < 1 && pn1->_intPoint )
4470 if ( !quad._eIntNodes.empty() ) // connect pn2 with EDGE intersections
4472 chn.push_back( pn2 );
4477 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4478 if (( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad )) &&
4479 ( chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint, avoidFace )) &&
4480 ( !avoidFace || quad._eIntNodes[ iP ]->IsOnFace( avoidFace )))
4482 chn.push_back( quad._eIntNodes[ iP ]);
4483 found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
4490 _Node* n = 0, *stopNode = avoidSplit.LastNode();
4492 if ( pn2 == prevSplit.LastNode() && // pn2 is at avoidSplit.FirstNode()
4493 !isCorner( stopNode )) // stopNode is in the middle of a _hexLinks
4495 // move stopNode to a _hexNodes
4496 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
4497 for ( size_t iL = 0; iL < quad._links[ iE ].NbResultLinks(); ++iL )
4499 const _Link* sideSplit = & quad._links[ iE ]._link->_splits[ iL ];
4500 if ( sideSplit == avoidSplit._link )
4502 if ( quad._links[ iE ].LastNode()->Node() )
4503 stopNode = quad._links[ iE ].LastNode();
4510 // connect pn2 (probably new, at _eIntNodes) with a split
4514 TGeomID commonFaces[20];
4515 _Node* nPrev = nullptr;
4516 for ( i = splits.size()-1; i >= 0; --i )
4522 for ( int is1st = 0; is1st < 2; ++is1st )
4524 _Node* nConn = is1st ? splits[i].FirstNode() : splits[i].LastNode();
4525 if ( nConn == nPrev )
4532 if (( stop = ( nConn == stopNode )))
4534 // find a FACE connecting nConn with pn2 but not with an3
4535 if (( nConn != pn1 ) &&
4536 ( nConn->_intPoint && !nConn->_intPoint->_faceIDs.empty() ) &&
4537 ( nbCommon = nConn->GetCommonFaces( pn2->_intPoint, commonFaces )))
4539 bool a3Coonect = true;
4540 for ( size_t iF = 0; iF < nbCommon && a3Coonect; ++iF )
4541 a3Coonect = an3->IsOnFace( commonFaces[ iF ]) || concaveFaces.count( commonFaces[ iF ]);
4550 if ( nbCommon > 1 ) // nConn is linked with pn2 by an EDGE
4566 if ( n && n != stopNode )
4569 chn.push_back( pn2 );
4574 else if ( !chn.empty() && chn.back()->_isInternalFlags )
4576 // INTERNAL FACE partially cuts the quad
4577 for ( int ip = chn.size() - 2; ip >= 0; --ip )
4578 chn.push_back( chn[ ip ]);
4583 //================================================================================
4585 * \brief Checks transition at the ginen intersection node of a link
4587 bool Hexahedron::isOutPoint( _Link& link, int iP,
4588 SMESH_MesherHelper& helper, const Solid* solid ) const
4592 if ( link._fIntNodes[iP]->faces().size() == 1 &&
4593 _grid->IsInternal( link._fIntNodes[iP]->face(0) ))
4596 const bool moreIntPoints = ( iP+1 < (int) link._fIntNodes.size() );
4599 _Node* n1 = link._fIntNodes[ iP ];
4601 n1 = link._nodes[0];
4602 _Node* n2 = moreIntPoints ? link._fIntNodes[ iP+1 ] : 0;
4603 if ( !n2 || !n2->Node() )
4604 n2 = link._nodes[1];
4608 // get all FACEs under n1 and n2
4609 set< TGeomID > faceIDs;
4610 if ( moreIntPoints ) faceIDs.insert( link._fIntNodes[iP+1]->faces().begin(),
4611 link._fIntNodes[iP+1]->faces().end() );
4612 if ( n2->_intPoint ) faceIDs.insert( n2->_intPoint->_faceIDs.begin(),
4613 n2->_intPoint->_faceIDs.end() );
4614 if ( faceIDs.empty() )
4615 return false; // n2 is inside
4616 if ( n1->_intPoint ) faceIDs.insert( n1->_intPoint->_faceIDs.begin(),
4617 n1->_intPoint->_faceIDs.end() );
4618 faceIDs.insert( link._fIntNodes[iP]->faces().begin(),
4619 link._fIntNodes[iP]->faces().end() );
4621 // get a point between 2 nodes
4622 gp_Pnt p1 = n1->Point();
4623 gp_Pnt p2 = n2->Point();
4624 gp_Pnt pOnLink = 0.8 * p1.XYZ() + 0.2 * p2.XYZ();
4626 TopLoc_Location loc;
4628 set< TGeomID >::iterator faceID = faceIDs.begin();
4629 for ( ; faceID != faceIDs.end(); ++faceID )
4631 // project pOnLink on a FACE
4632 if ( *faceID < 1 || !solid->Contains( *faceID )) continue;
4633 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( *faceID ));
4634 GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( face, loc, 0.1*_grid->_tol );
4635 gp_Pnt testPnt = pOnLink.Transformed( loc.Transformation().Inverted() );
4636 proj.Perform( testPnt );
4637 if ( proj.IsDone() && proj.NbPoints() > 0 )
4640 proj.LowerDistanceParameters( u,v );
4642 if ( proj.LowerDistance() <= 0.1 * _grid->_tol )
4648 // find isOut by normals
4650 if ( GeomLib::NormEstim( BRep_Tool::Surface( face, loc ),
4655 if ( solid->Orientation( face ) == TopAbs_REVERSED )
4657 gp_Vec v( proj.NearestPoint(), testPnt );
4658 isOut = ( v * normal > 0 );
4663 // classify a projection
4664 if ( !n1->IsOnFace( *faceID ) || !n2->IsOnFace( *faceID ))
4666 BRepTopAdaptor_FClass2d cls( face, Precision::Confusion() );
4667 TopAbs_State state = cls.Perform( gp_Pnt2d( u,v ));
4668 if ( state == TopAbs_OUT )
4680 //================================================================================
4682 * \brief Sort nodes on a FACE
4684 void Hexahedron::sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID faceID)
4686 if ( nodes.size() > 20 ) return;
4688 // get shapes under nodes
4689 TGeomID nShapeIds[20], *nShapeIdsEnd = &nShapeIds[0] + nodes.size();
4690 for ( size_t i = 0; i < nodes.size(); ++i )
4691 if ( !( nShapeIds[i] = nodes[i]->ShapeID() ))
4694 // get shapes of the FACE
4695 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( faceID ));
4696 list< TopoDS_Edge > edges;
4697 list< int > nbEdges;
4698 int nbW = SMESH_Block::GetOrderedEdges (face, edges, nbEdges);
4700 // select a WIRE - remove EDGEs of irrelevant WIREs from edges
4701 list< TopoDS_Edge >::iterator e = edges.begin(), eEnd = e;
4702 list< int >::iterator nE = nbEdges.begin();
4703 for ( ; nbW > 0; ++nE, --nbW )
4705 std::advance( eEnd, *nE );
4706 for ( ; e != eEnd; ++e )
4707 for ( int i = 0; i < 2; ++i )
4710 _grid->ShapeID( *e ) :
4711 _grid->ShapeID( SMESH_MesherHelper::IthVertex( 0, *e ));
4713 ( std::find( &nShapeIds[0], nShapeIdsEnd, id ) != nShapeIdsEnd ))
4715 edges.erase( eEnd, edges.end() ); // remove rest wires
4716 e = eEnd = edges.end();
4723 edges.erase( edges.begin(), eEnd ); // remove a current irrelevant wire
4726 // rotate edges to have the first one at least partially out of the hexa
4727 list< TopoDS_Edge >::iterator e = edges.begin(), eMidOut = edges.end();
4728 for ( ; e != edges.end(); ++e )
4730 if ( !_grid->ShapeID( *e ))
4735 for ( int i = 0; i < 2 && !isOut; ++i )
4739 TopoDS_Vertex v = SMESH_MesherHelper::IthVertex( 0, *e );
4740 p = BRep_Tool::Pnt( v );
4742 else if ( eMidOut == edges.end() )
4744 TopLoc_Location loc;
4745 Handle(Geom_Curve) c = BRep_Tool::Curve( *e, loc, f, l);
4746 if ( c.IsNull() ) break;
4747 p = c->Value( 0.5 * ( f + l )).Transformed( loc );
4754 _grid->ComputeUVW( p.XYZ(), uvw );
4755 if ( isOutParam( uvw ))
4766 if ( e != edges.end() )
4767 edges.splice( edges.end(), edges, edges.begin(), e );
4768 else if ( eMidOut != edges.end() )
4769 edges.splice( edges.end(), edges, edges.begin(), eMidOut );
4771 // sort nodes according to the order of edges
4772 _Node* orderNodes [20];
4773 //TGeomID orderShapeIDs[20];
4775 TGeomID id, *pID = 0;
4776 for ( e = edges.begin(); e != edges.end(); ++e )
4778 if (( id = _grid->ShapeID( SMESH_MesherHelper::IthVertex( 0, *e ))) &&
4779 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
4781 //orderShapeIDs[ nbN ] = id;
4782 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
4785 if (( id = _grid->ShapeID( *e )) &&
4786 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
4788 //orderShapeIDs[ nbN ] = id;
4789 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
4793 if ( nbN != nodes.size() )
4796 bool reverse = ( orderNodes[0 ]->Point().SquareDistance( curNode->Point() ) >
4797 orderNodes[nbN-1]->Point().SquareDistance( curNode->Point() ));
4799 for ( size_t i = 0; i < nodes.size(); ++i )
4800 nodes[ i ] = orderNodes[ reverse ? nbN-1-i : i ];
4803 //================================================================================
4805 * \brief Adds computed elements to the mesh
4807 int Hexahedron::addVolumes( SMESH_MesherHelper& helper )
4809 F_IntersectPoint noIntPnt;
4810 const bool toCheckNodePos = _grid->IsToCheckNodePos();
4813 // add elements resulted from hexahedron intersection
4814 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4816 vector< const SMDS_MeshNode* > nodes( volDef->_nodes.size() );
4817 for ( size_t iN = 0; iN < nodes.size(); ++iN )
4819 if ( !( nodes[iN] = volDef->_nodes[iN].Node() ))
4821 if ( const E_IntersectPoint* eip = volDef->_nodes[iN].EdgeIntPnt() )
4823 nodes[iN] = volDef->_nodes[iN]._intPoint->_node =
4824 helper.AddNode( eip->_point.X(),
4827 if ( _grid->ShapeType( eip->_shapeID ) == TopAbs_VERTEX )
4828 helper.GetMeshDS()->SetNodeOnVertex( nodes[iN], eip->_shapeID );
4830 helper.GetMeshDS()->SetNodeOnEdge( nodes[iN], eip->_shapeID );
4833 throw SALOME_Exception("Bug: no node at intersection point");
4835 else if ( volDef->_nodes[iN]._intPoint &&
4836 volDef->_nodes[iN]._intPoint->_node == volDef->_nodes[iN]._node )
4838 // Update position of node at EDGE intersection;
4839 // see comment to _Node::Add( E_IntersectPoint )
4840 SMESHDS_Mesh* mesh = helper.GetMeshDS();
4841 TGeomID shapeID = volDef->_nodes[iN].EdgeIntPnt()->_shapeID;
4842 mesh->UnSetNodeOnShape( nodes[iN] );
4843 if ( _grid->ShapeType( shapeID ) == TopAbs_VERTEX )
4844 mesh->SetNodeOnVertex( nodes[iN], shapeID );
4846 mesh->SetNodeOnEdge( nodes[iN], shapeID );
4848 else if ( toCheckNodePos &&
4849 !nodes[iN]->isMarked() &&
4850 _grid->ShapeType( nodes[iN]->GetShapeID() ) == TopAbs_FACE )
4852 _grid->SetOnShape( nodes[iN], noIntPnt, /*v=*/nullptr,/*unset=*/true );
4853 nodes[iN]->setIsMarked( true );
4855 } // loop to get nodes
4857 const SMDS_MeshElement* v = 0;
4859 if ( !volDef->_quantities.empty() )
4861 // split polyhedrons of with disjoint volumes
4862 std::vector<std::vector<int>> splitQuantities;
4863 std::vector<std::vector< const SMDS_MeshNode* > > splitNodes;
4864 if ( checkPolyhedronValidity( volDef, splitQuantities, splitNodes ) == 1 )
4866 v = addPolyhedronToMesh( volDef, helper, nodes, volDef->_quantities );
4871 for (size_t id = 0; id < splitQuantities.size(); id++)
4873 v = addPolyhedronToMesh( volDef, helper, splitNodes[ id ], splitQuantities[ id ] );
4874 if ( id < splitQuantities.size()-1 )
4875 volDef->_brotherVolume.push_back( v );
4883 switch ( nodes.size() )
4885 case 8: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],
4886 nodes[4],nodes[5],nodes[6],nodes[7] );
4888 case 4: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3] );
4890 case 6: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4],nodes[5] );
4892 case 5: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4] );
4896 volDef->_volume = v;
4897 nbAdded += bool( v );
4899 } // loop on _volumeDefs chain
4901 // avoid creating overlapping volumes (bos #24052)
4904 double sumSize = 0, maxSize = 0;
4905 _volumeDef* maxSizeDef = nullptr;
4906 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4908 if ( !volDef->_volume )
4910 sumSize += volDef->_size;
4911 if ( volDef->_size > maxSize )
4913 maxSize = volDef->_size;
4914 maxSizeDef = volDef;
4917 if ( sumSize > _sideLength[0] * _sideLength[1] * _sideLength[2] * 1.05 )
4919 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4920 if ( volDef != maxSizeDef && volDef->_volume )
4922 helper.GetMeshDS()->RemoveFreeElement( volDef->_volume, /*sm=*/nullptr,
4923 /*fromGroups=*/false );
4924 volDef->_volume = nullptr;
4925 //volDef->_nodes.clear();
4931 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4933 if ( volDef->_volume )
4935 helper.GetMeshDS()->SetMeshElementOnShape( volDef->_volume, volDef->_solidID );
4936 for (auto broVol : volDef->_brotherVolume )
4938 helper.GetMeshDS()->SetMeshElementOnShape( broVol, volDef->_solidID );
4945 //================================================================================
4947 * \brief Return true if the element is in a hole
4949 bool Hexahedron::isInHole() const
4951 if ( !_vIntNodes.empty() )
4954 const size_t ijk[3] = { _i, _j, _k };
4955 F_IntersectPoint curIntPnt;
4957 // consider a cell to be in a hole if all links in any direction
4958 // comes OUT of geometry
4959 for ( int iDir = 0; iDir < 3; ++iDir )
4961 const vector<double>& coords = _grid->_coords[ iDir ];
4962 LineIndexer li = _grid->GetLineIndexer( iDir );
4963 li.SetIJK( _i,_j,_k );
4964 size_t lineIndex[4] = { li.LineIndex (),
4968 bool allLinksOut = true, hasLinks = false;
4969 for ( int iL = 0; iL < 4 && allLinksOut; ++iL ) // loop on 4 links parallel to iDir
4971 const _Link& link = _hexLinks[ iL + 4*iDir ];
4972 // check transition of the first node of a link
4973 const F_IntersectPoint* firstIntPnt = 0;
4974 if ( link._nodes[0]->Node() ) // 1st node is a hexa corner
4976 curIntPnt._paramOnLine = coords[ ijk[ iDir ]] - coords[0] + _grid->_tol;
4977 const GridLine& line = _grid->_lines[ iDir ][ lineIndex[ iL ]];
4978 if ( !line._intPoints.empty() )
4980 multiset< F_IntersectPoint >::const_iterator ip =
4981 line._intPoints.upper_bound( curIntPnt );
4983 firstIntPnt = &(*ip);
4986 else if ( !link._fIntPoints.empty() )
4988 firstIntPnt = link._fIntPoints[0];
4994 allLinksOut = ( firstIntPnt->_transition == Trans_OUT &&
4995 !_grid->IsShared( firstIntPnt->_faceIDs[0] ));
4998 if ( hasLinks && allLinksOut )
5004 //================================================================================
5006 * \brief Check if a polyherdon has an edge lying on EDGE shared by strange FACE
5007 * that will be meshed by other algo
5009 bool Hexahedron::hasStrangeEdge() const
5011 if ( _eIntPoints.size() < 2 )
5014 TopTools_MapOfShape edges;
5015 for ( size_t i = 0; i < _eIntPoints.size(); ++i )
5017 if ( !_grid->IsStrangeEdge( _eIntPoints[i]->_shapeID ))
5019 const TopoDS_Shape& s = _grid->Shape( _eIntPoints[i]->_shapeID );
5020 if ( s.ShapeType() == TopAbs_EDGE )
5022 if ( ! edges.Add( s ))
5023 return true; // an EDGE encounters twice
5027 PShapeIteratorPtr edgeIt = _grid->_helper->GetAncestors( s,
5028 *_grid->_helper->GetMesh(),
5030 while ( const TopoDS_Shape* edge = edgeIt->next() )
5031 if ( ! edges.Add( *edge ))
5032 return true; // an EDGE encounters twice
5038 //================================================================================
5040 * \brief Return true if a polyhedron passes _sizeThreshold criterion
5042 bool Hexahedron::checkPolyhedronSize( bool cutByInternalFace, double & volume) const
5046 if ( cutByInternalFace && !_grid->_toUseThresholdForInternalFaces )
5048 // check if any polygon fully lies on shared/internal FACEs
5049 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
5051 const _Face& polygon = _polygons[iP];
5052 if ( polygon._links.empty() )
5054 bool allNodesInternal = true;
5055 for ( size_t iL = 0; iL < polygon._links.size() && allNodesInternal; ++iL )
5057 _Node* n = polygon._links[ iL ].FirstNode();
5058 allNodesInternal = (( n->IsCutByInternal() ) ||
5059 ( n->_intPoint && _grid->IsAnyShared( n->_intPoint->_faceIDs )));
5061 if ( allNodesInternal )
5065 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
5067 const _Face& polygon = _polygons[iP];
5068 if ( polygon._links.empty() )
5070 gp_XYZ area (0,0,0);
5071 gp_XYZ p1 = polygon._links[ 0 ].FirstNode()->Point().XYZ();
5072 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
5074 gp_XYZ p2 = polygon._links[ iL ].LastNode()->Point().XYZ();
5078 volume += p1 * area;
5082 if ( this->hasStrangeEdge() && volume > 1e-13 )
5085 double initVolume = _sideLength[0] * _sideLength[1] * _sideLength[2];
5087 return volume > initVolume / _grid->_sizeThreshold;
5090 //================================================================================
5092 * \brief Check that all faces in polyhedron are connected so a unique volume is defined.
5093 * We test that it is possible to go from any node to all nodes in the polyhedron.
5094 * The set of nodes that can be visit within then defines a unique element.
5095 * In case more than one polyhedron is detected. The function return the set of quantities and nodes defining separates elements.
5096 * Reference to issue #bos[38521][EDF] Generate polyhedron with separate volume.
5098 int Hexahedron::checkPolyhedronValidity( _volumeDef* volDef, std::vector<std::vector<int>>& splitQuantities,
5099 std::vector<std::vector<const SMDS_MeshNode*>>& splitNodes )
5102 std::map<int,int> numberOfSets; // define set id with the number of faces associated!
5103 if ( !volDef->_quantities.empty() )
5105 auto connectivity = volDef->_quantities;
5107 std::vector<bool> allFaces( connectivity.size(), false );
5108 std::set<int> elementSet;
5109 allFaces[ 0 ] = true; // the first node below to the first face
5110 size_t connectedFaces = 1;
5111 // Start filling the set with the nodes of the first face
5112 splitQuantities.push_back( { connectivity[ 0 ] } );
5113 splitNodes.push_back( { volDef->_nodes[ 0 ].Node() } );
5114 elementSet.insert( volDef->_nodes[ 0 ].Node()->GetID() );
5115 for (int n = 1; n < connectivity[ 0 ]; n++)
5117 elementSet.insert( volDef->_nodes[ n ].Node()->GetID() );
5118 splitNodes.back().push_back( volDef->_nodes[ n ].Node() );
5121 numberOfSets.insert( std::pair<int,int>(mySet,1) );
5122 while ( connectedFaces != allFaces.size() )
5124 for (size_t innerId = 1; innerId < connectivity.size(); innerId++)
5127 accum = connectivity[ 0 ];
5129 if ( !allFaces[ innerId ] )
5131 int faceCounter = 0;
5132 for (int n = 0; n < connectivity[ innerId ]; n++)
5134 int nodeId = volDef->_nodes[ accum + n ].Node()->GetID();
5135 if ( elementSet.count( nodeId ) != 0 )
5138 if ( faceCounter >= 2 ) // found coincidences nodes
5140 for (int n = 0; n < connectivity[ innerId ]; n++)
5142 int nodeId = volDef->_nodes[ accum + n ].Node()->GetID();
5143 // insert new nodes so other faces can be identified as belowing to the element
5144 splitNodes.back().push_back( volDef->_nodes[ accum + n ].Node() );
5145 elementSet.insert( nodeId );
5147 allFaces[ innerId ] = true;
5148 splitQuantities.back().push_back( connectivity[ innerId ] );
5149 numberOfSets[ mySet ]++;
5151 innerId = 0; // to restart searching!
5154 accum += connectivity[ innerId ];
5157 if ( connectedFaces != allFaces.size() )
5159 // empty the set, and fill it with nodes of a unvisited face!
5161 accum = connectivity[ 0 ];
5162 for (size_t faceId = 1; faceId < connectivity.size(); faceId++)
5164 if ( !allFaces[ faceId ] )
5166 splitNodes.push_back( { volDef->_nodes[ accum ].Node() } );
5167 elementSet.insert( volDef->_nodes[ accum ].Node()->GetID() );
5168 for (int n = 1; n < connectivity[ faceId ]; n++)
5170 elementSet.insert( volDef->_nodes[ accum + n ].Node()->GetID() );
5171 splitNodes.back().push_back( volDef->_nodes[ accum + n ].Node() );
5174 splitQuantities.push_back( { connectivity[ faceId ] } );
5175 allFaces[ faceId ] = true;
5179 accum += connectivity[ faceId ];
5182 numberOfSets.insert( std::pair<int,int>(mySet,1) );
5186 if ( numberOfSets.size() > 1 )
5188 bool allMoreThan2Faces = true;
5189 for( auto k : numberOfSets )
5191 if ( k.second <= 2 )
5192 allMoreThan2Faces &= false;
5195 if ( allMoreThan2Faces )
5197 // The separate objects are suspect to be closed
5198 return numberOfSets.size();
5202 // Have to index the last face nodes to the final set
5203 // contrary case return as it were a valid polyhedron for backward compatibility
5208 return numberOfSets.size();
5212 //================================================================================
5214 * \brief add original or separated polyhedrons to the mesh
5216 const SMDS_MeshElement* Hexahedron::addPolyhedronToMesh( _volumeDef* volDef, SMESH_MesherHelper& helper, const std::vector<const SMDS_MeshNode*>& nodes,
5217 const std::vector<int>& quantities )
5219 const SMDS_MeshElement* v = helper.AddPolyhedralVolume( nodes, quantities );
5221 volDef->_size = SMDS_VolumeTool( v ).GetSize();
5222 if ( volDef->_size < 0 ) // invalid polyhedron
5224 if ( ! SMESH_MeshEditor( helper.GetMesh() ).Reorient( v ) || // try to fix
5225 SMDS_VolumeTool( v ).GetSize() < 0 )
5227 helper.GetMeshDS()->RemoveFreeElement( v, /*sm=*/nullptr, /*fromGroups=*/false );
5229 //_hasTooSmall = true;
5231 if (SALOME::VerbosityActivated())
5233 std::cout << "Remove INVALID polyhedron, _cellID = " << _cellID
5234 << " ijk = ( " << _i << " " << _j << " " << _k << " ) "
5235 << " solid " << volDef->_solidID << std::endl;
5242 //================================================================================
5244 * \brief Tries to create a hexahedron
5246 bool Hexahedron::addHexa()
5248 int nbQuad = 0, iQuad = -1;
5249 for ( size_t i = 0; i < _polygons.size(); ++i )
5251 if ( _polygons[i]._links.empty() )
5253 if ( _polygons[i]._links.size() != 4 )
5264 for ( int iL = 0; iL < 4; ++iL )
5267 nodes[iL] = _polygons[iQuad]._links[iL].FirstNode();
5270 // find a top node above the base node
5271 _Link* link = _polygons[iQuad]._links[iL]._link;
5272 if ( !link->_faces[0] || !link->_faces[1] )
5273 return debugDumpLink( link );
5274 // a quadrangle sharing <link> with _polygons[iQuad]
5275 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[iQuad] )];
5276 for ( int i = 0; i < 4; ++i )
5277 if ( quad->_links[i]._link == link )
5279 // 1st node of a link opposite to <link> in <quad>
5280 nodes[iL+4] = quad->_links[(i+2)%4].FirstNode();
5286 _volumeDefs.Set( &nodes[0], 8 );
5290 //================================================================================
5292 * \brief Tries to create a tetrahedron
5294 bool Hexahedron::addTetra()
5297 for ( size_t i = 0; i < _polygons.size() && iTria < 0; ++i )
5298 if ( _polygons[i]._links.size() == 3 )
5304 nodes[0] = _polygons[iTria]._links[0].FirstNode();
5305 nodes[1] = _polygons[iTria]._links[1].FirstNode();
5306 nodes[2] = _polygons[iTria]._links[2].FirstNode();
5308 _Link* link = _polygons[iTria]._links[0]._link;
5309 if ( !link->_faces[0] || !link->_faces[1] )
5310 return debugDumpLink( link );
5312 // a triangle sharing <link> with _polygons[0]
5313 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[iTria] )];
5314 for ( int i = 0; i < 3; ++i )
5315 if ( tria->_links[i]._link == link )
5317 nodes[3] = tria->_links[(i+1)%3].LastNode();
5318 _volumeDefs.Set( &nodes[0], 4 );
5324 //================================================================================
5326 * \brief Tries to create a pentahedron
5328 bool Hexahedron::addPenta()
5330 // find a base triangular face
5332 for ( int iF = 0; iF < 5 && iTri < 0; ++iF )
5333 if ( _polygons[ iF ]._links.size() == 3 )
5335 if ( iTri < 0 ) return false;
5340 for ( int iL = 0; iL < 3; ++iL )
5343 nodes[iL] = _polygons[ iTri ]._links[iL].FirstNode();
5346 // find a top node above the base node
5347 _Link* link = _polygons[ iTri ]._links[iL]._link;
5348 if ( !link->_faces[0] || !link->_faces[1] )
5349 return debugDumpLink( link );
5350 // a quadrangle sharing <link> with a base triangle
5351 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[ iTri ] )];
5352 if ( quad->_links.size() != 4 ) return false;
5353 for ( int i = 0; i < 4; ++i )
5354 if ( quad->_links[i]._link == link )
5356 // 1st node of a link opposite to <link> in <quad>
5357 nodes[iL+3] = quad->_links[(i+2)%4].FirstNode();
5363 _volumeDefs.Set( &nodes[0], 6 );
5365 return ( nbN == 6 );
5367 //================================================================================
5369 * \brief Tries to create a pyramid
5371 bool Hexahedron::addPyra()
5373 // find a base quadrangle
5375 for ( int iF = 0; iF < 5 && iQuad < 0; ++iF )
5376 if ( _polygons[ iF ]._links.size() == 4 )
5378 if ( iQuad < 0 ) return false;
5382 nodes[0] = _polygons[iQuad]._links[0].FirstNode();
5383 nodes[1] = _polygons[iQuad]._links[1].FirstNode();
5384 nodes[2] = _polygons[iQuad]._links[2].FirstNode();
5385 nodes[3] = _polygons[iQuad]._links[3].FirstNode();
5387 _Link* link = _polygons[iQuad]._links[0]._link;
5388 if ( !link->_faces[0] || !link->_faces[1] )
5389 return debugDumpLink( link );
5391 // a triangle sharing <link> with a base quadrangle
5392 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[ iQuad ] )];
5393 if ( tria->_links.size() != 3 ) return false;
5394 for ( int i = 0; i < 3; ++i )
5395 if ( tria->_links[i]._link == link )
5397 nodes[4] = tria->_links[(i+1)%3].LastNode();
5398 _volumeDefs.Set( &nodes[0], 5 );
5404 //================================================================================
5406 * \brief Return true if there are _eIntPoints at EDGEs forming a concave corner
5408 bool Hexahedron::hasEdgesAround( const ConcaveFace* cf ) const
5411 ConcaveFace foundGeomHolder;
5412 for ( const E_IntersectPoint* ip : _eIntPoints )
5414 if ( cf->HasEdge( ip->_shapeID ))
5416 if ( ++nbEdges == 2 )
5418 foundGeomHolder.SetEdge( ip->_shapeID );
5420 else if ( ip->_faceIDs.size() >= 3 )
5422 const TGeomID & vID = ip->_shapeID;
5423 if ( cf->HasVertex( vID ) && !foundGeomHolder.HasVertex( vID ))
5425 if ( ++nbEdges == 2 )
5427 foundGeomHolder.SetVertex( vID );
5432 for ( const _Node& hexNode: _hexNodes )
5434 if ( !hexNode._node || !hexNode._intPoint )
5436 const B_IntersectPoint* ip = hexNode._intPoint;
5437 if ( ip->_faceIDs.size() == 2 ) // EDGE
5439 TGeomID edgeID = hexNode._node->GetShapeID();
5440 if ( cf->HasEdge( edgeID ) && !foundGeomHolder.HasEdge( edgeID ))
5442 foundGeomHolder.SetEdge( edgeID );
5443 if ( ++nbEdges == 2 )
5447 else if ( ip->_faceIDs.size() >= 3 ) // VERTEX
5449 TGeomID vID = hexNode._node->GetShapeID();
5450 if ( cf->HasVertex( vID ) && !foundGeomHolder.HasVertex( vID ))
5452 if ( ++nbEdges == 2 )
5454 foundGeomHolder.SetVertex( vID );
5461 //================================================================================
5463 * \brief Dump a link and return \c false
5465 bool Hexahedron::debugDumpLink( Hexahedron::_Link* link )
5467 if (SALOME::VerbosityActivated())
5469 gp_Pnt p1 = link->_nodes[0]->Point(), p2 = link->_nodes[1]->Point();
5470 cout << "BUG: not shared link. IKJ = ( "<< _i << " " << _j << " " << _k << " )" << endl
5471 << "n1 (" << p1.X() << ", "<< p1.Y() << ", "<< p1.Z() << " )" << endl
5472 << "n2 (" << p2.X() << ", "<< p2.Y() << ", "<< p2.Z() << " )" << endl;
5477 //================================================================================
5479 * \brief Classify a point by grid parameters
5481 bool Hexahedron::isOutParam(const double uvw[3]) const
5483 return (( _grid->_coords[0][ _i ] - _grid->_tol > uvw[0] ) ||
5484 ( _grid->_coords[0][ _i+1 ] + _grid->_tol < uvw[0] ) ||
5485 ( _grid->_coords[1][ _j ] - _grid->_tol > uvw[1] ) ||
5486 ( _grid->_coords[1][ _j+1 ] + _grid->_tol < uvw[1] ) ||
5487 ( _grid->_coords[2][ _k ] - _grid->_tol > uvw[2] ) ||
5488 ( _grid->_coords[2][ _k+1 ] + _grid->_tol < uvw[2] ));
5490 //================================================================================
5492 * \brief Find existing triangulation of a polygon
5494 int findExistingTriangulation( const SMDS_MeshElement* polygon,
5495 //const SMDS_Mesh* mesh,
5496 std::vector< const SMDS_MeshNode* >& nodes )
5500 std::vector<const SMDS_MeshNode *> twoNodes(2);
5501 std::vector<const SMDS_MeshElement *> foundFaces; foundFaces.reserve(10);
5502 std::set< const SMDS_MeshElement * > avoidFaces; avoidFaces.insert( polygon );
5504 const int nbPolyNodes = polygon->NbCornerNodes();
5505 twoNodes[1] = polygon->GetNode( nbPolyNodes - 1 );
5506 for ( int iN = 0; iN < nbPolyNodes; ++iN ) // loop on border links of polygon
5508 twoNodes[0] = polygon->GetNode( iN );
5510 int nbFaces = SMDS_Mesh::GetElementsByNodes( twoNodes, foundFaces, SMDSAbs_Face );
5512 for ( int iF = 0; iF < nbFaces; ++iF ) // keep faces lying over polygon
5514 if ( avoidFaces.count( foundFaces[ iF ]))
5516 int i, nbFaceNodes = foundFaces[ iF ]->NbCornerNodes();
5517 for ( i = 0; i < nbFaceNodes; ++i )
5519 const SMDS_MeshNode* n = foundFaces[ iF ]->GetNode( i );
5520 bool isCommonNode = ( n == twoNodes[0] ||
5522 polygon->GetNodeIndex( n ) >= 0 );
5523 if ( !isCommonNode )
5526 if ( i == nbFaceNodes ) // all nodes of foundFaces[iF] are shared with polygon
5527 if ( nbOkFaces++ != iF )
5528 foundFaces[ nbOkFaces-1 ] = foundFaces[ iF ];
5530 if ( nbOkFaces > 0 )
5532 int iFaceSelected = 0;
5533 if ( nbOkFaces > 1 ) // select a face with minimal distance from polygon
5535 double minDist = Precision::Infinite();
5536 for ( int iF = 0; iF < nbOkFaces; ++iF )
5538 int i, nbFaceNodes = foundFaces[ iF ]->NbCornerNodes();
5539 gp_XYZ gc = SMESH_NodeXYZ( foundFaces[ iF ]->GetNode( 0 ));
5540 for ( i = 1; i < nbFaceNodes; ++i )
5541 gc += SMESH_NodeXYZ( foundFaces[ iF ]->GetNode( i ));
5544 double dist = SMESH_MeshAlgos::GetDistance( polygon, gc );
5545 if ( dist < minDist )
5552 if ( foundFaces[ iFaceSelected ]->NbCornerNodes() != 3 )
5554 nodes.insert( nodes.end(),
5555 foundFaces[ iFaceSelected ]->begin_nodes(),
5556 foundFaces[ iFaceSelected ]->end_nodes());
5557 if ( !SMESH_MeshAlgos::IsRightOrder( foundFaces[ iFaceSelected ],
5558 twoNodes[0], twoNodes[1] ))
5560 // reverse just added nodes
5561 std::reverse( nodes.end() - 3, nodes.end() );
5563 avoidFaces.insert( foundFaces[ iFaceSelected ]);
5567 twoNodes[1] = twoNodes[0];
5569 } // loop on polygon nodes
5573 //================================================================================
5575 * \brief Divide a polygon into triangles and modify accordingly an adjacent polyhedron
5577 void splitPolygon( const SMDS_MeshElement* polygon,
5578 SMDS_VolumeTool & volume,
5579 const int facetIndex,
5580 const TGeomID faceID,
5581 const TGeomID solidID,
5582 SMESH_MeshEditor::ElemFeatures& face,
5583 SMESH_MeshEditor& editor,
5584 const bool reinitVolume)
5586 SMESH_MeshAlgos::Triangulate divider(/*optimize=*/false);
5587 bool triangulationExist = false;
5588 int nbTrias = findExistingTriangulation( polygon, face.myNodes );
5590 triangulationExist = true;
5592 nbTrias = divider.GetTriangles( polygon, face.myNodes );
5593 face.myNodes.resize( nbTrias * 3 );
5595 SMESH_MeshEditor::ElemFeatures newVolumeDef;
5596 newVolumeDef.Init( volume.Element() );
5597 newVolumeDef.SetID( volume.Element()->GetID() );
5599 newVolumeDef.myPolyhedQuantities.reserve( volume.NbFaces() + nbTrias );
5600 newVolumeDef.myNodes.reserve( volume.NbNodes() + nbTrias * 3 );
5602 SMESHDS_Mesh* meshDS = editor.GetMeshDS();
5603 SMDS_MeshElement* newTriangle;
5604 for ( int iF = 0, nF = volume.NbFaces(); iF < nF; iF++ )
5606 if ( iF == facetIndex )
5608 newVolumeDef.myPolyhedQuantities.push_back( 3 );
5609 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(),
5610 face.myNodes.begin(),
5611 face.myNodes.begin() + 3 );
5612 meshDS->RemoveFreeElement( polygon, 0, false );
5613 if ( !triangulationExist )
5615 newTriangle = meshDS->AddFace( face.myNodes[0], face.myNodes[1], face.myNodes[2] );
5616 meshDS->SetMeshElementOnShape( newTriangle, faceID );
5621 const SMDS_MeshNode** nn = volume.GetFaceNodes( iF );
5622 const size_t nbFaceNodes = volume.NbFaceNodes ( iF );
5623 newVolumeDef.myPolyhedQuantities.push_back( nbFaceNodes );
5624 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(), nn, nn + nbFaceNodes );
5628 for ( size_t iN = 3; iN < face.myNodes.size(); iN += 3 )
5630 newVolumeDef.myPolyhedQuantities.push_back( 3 );
5631 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(),
5632 face.myNodes.begin() + iN,
5633 face.myNodes.begin() + iN + 3 );
5634 if ( !triangulationExist )
5636 newTriangle = meshDS->AddFace( face.myNodes[iN], face.myNodes[iN+1], face.myNodes[iN+2] );
5637 meshDS->SetMeshElementOnShape( newTriangle, faceID );
5641 meshDS->RemoveFreeElement( volume.Element(), 0, false );
5642 SMDS_MeshElement* newVolume = editor.AddElement( newVolumeDef.myNodes, newVolumeDef );
5643 meshDS->SetMeshElementOnShape( newVolume, solidID );
5648 volume.Set( newVolume );
5652 //================================================================================
5654 * \brief Look for a FACE supporting all given nodes made on EDGEs and VERTEXes
5656 TGeomID findCommonFace( const std::vector< const SMDS_MeshNode* > & nn,
5657 const SMESH_Mesh* mesh )
5660 TGeomID shapeIDs[20];
5661 for ( size_t iN = 0; iN < nn.size(); ++iN )
5662 shapeIDs[ iN ] = nn[ iN ]->GetShapeID();
5664 SMESH_subMesh* sm = mesh->GetSubMeshContaining( shapeIDs[ 0 ]);
5665 for ( const SMESH_subMesh * smFace : sm->GetAncestors() )
5667 if ( smFace->GetSubShape().ShapeType() != TopAbs_FACE )
5670 faceID = smFace->GetId();
5672 for ( size_t iN = 1; iN < nn.size() && faceID; ++iN )
5674 if ( !smFace->DependsOn( shapeIDs[ iN ]))
5682 //================================================================================
5684 * \brief Create mesh faces at free facets
5686 void Hexahedron::addFaces( SMESH_MesherHelper& helper,
5687 const vector< const SMDS_MeshElement* > & boundaryVolumes )
5689 if ( !_grid->_toCreateFaces )
5692 SMDS_VolumeTool vTool;
5693 vector<int> bndFacets;
5694 SMESH_MeshEditor editor( helper.GetMesh() );
5695 SMESH_MeshEditor::ElemFeatures face( SMDSAbs_Face );
5696 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
5698 // check if there are internal or shared FACEs
5699 bool hasInternal = ( !_grid->_geometry.IsOneSolid() ||
5700 _grid->_geometry._soleSolid.HasInternalFaces() );
5702 for ( size_t iV = 0; iV < boundaryVolumes.size(); ++iV )
5704 if ( !vTool.Set( boundaryVolumes[ iV ]))
5707 TGeomID solidID = vTool.Element()->GetShapeID();
5708 Solid * solid = _grid->GetOneOfSolids( solidID );
5710 // find boundary facets
5713 for ( int iF = 0, n = vTool.NbFaces(); iF < n; iF++ )
5715 const SMDS_MeshElement* otherVol;
5716 bool isBoundary = vTool.IsFreeFace( iF, &otherVol );
5719 bndFacets.push_back( iF );
5721 else if (( hasInternal ) ||
5722 ( !_grid->IsSolid( otherVol->GetShapeID() )))
5724 // check if all nodes are on internal/shared FACEs
5726 const SMDS_MeshNode** nn = vTool.GetFaceNodes( iF );
5727 const size_t nbFaceNodes = vTool.NbFaceNodes ( iF );
5728 for ( size_t iN = 0; iN < nbFaceNodes && isBoundary; ++iN )
5729 isBoundary = ( nn[ iN ]->GetShapeID() != solidID );
5731 bndFacets.push_back( -( iF+1 )); // !!! minus ==> to check the FACE
5734 if ( bndFacets.empty() )
5739 if ( !vTool.IsPoly() )
5740 vTool.SetExternalNormal();
5741 for ( size_t i = 0; i < bndFacets.size(); ++i ) // loop on boundary facets
5743 const bool isBoundary = ( bndFacets[i] >= 0 );
5744 const int iFacet = isBoundary ? bndFacets[i] : -bndFacets[i]-1;
5745 const SMDS_MeshNode** nn = vTool.GetFaceNodes( iFacet );
5746 const size_t nbFaceNodes = vTool.NbFaceNodes ( iFacet );
5747 face.myNodes.assign( nn, nn + nbFaceNodes );
5750 const SMDS_MeshElement* existFace = 0, *newFace = 0;
5752 if (( existFace = meshDS->FindElement( face.myNodes, SMDSAbs_Face )))
5754 if ( existFace->isMarked() )
5755 continue; // created by this method
5756 faceID = existFace->GetShapeID();
5760 // look for a supporting FACE
5761 for ( size_t iN = 0; iN < nbFaceNodes && !faceID; ++iN ) // look for a node on FACE
5763 if ( nn[ iN ]->GetPosition()->GetDim() == 2 )
5764 faceID = nn[ iN ]->GetShapeID();
5767 faceID = findCommonFace( face.myNodes, helper.GetMesh() );
5769 bool toCheckFace = faceID && (( !isBoundary ) ||
5770 ( hasInternal && _grid->_toUseThresholdForInternalFaces ));
5771 if ( toCheckFace ) // check if all nodes are on the found FACE
5773 SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMeshContaining( faceID );
5774 for ( size_t iN = 0; iN < nbFaceNodes && faceID; ++iN )
5776 TGeomID subID = nn[ iN ]->GetShapeID();
5777 if ( subID != faceID && !faceSM->DependsOn( subID ))
5780 // if ( !faceID && !isBoundary )
5783 if ( !faceID && !isBoundary )
5787 // orient a new face according to supporting FACE orientation in shape_to_mesh
5788 if ( !isBoundary && !solid->IsOutsideOriented( faceID ))
5791 editor.Reorient( existFace );
5793 std::reverse( face.myNodes.begin(), face.myNodes.end() );
5796 if ( ! ( newFace = existFace ))
5798 face.SetPoly( nbFaceNodes > 4 );
5799 newFace = editor.AddElement( face.myNodes, face );
5802 newFace->setIsMarked( true ); // to distinguish from face created in getBoundaryElems()
5805 if ( faceID && _grid->IsBoundaryFace( faceID )) // face is not shared
5807 // set newFace to the found FACE provided that it fully lies on the FACE
5808 for ( size_t iN = 0; iN < nbFaceNodes && faceID; ++iN )
5809 if ( nn[iN]->GetShapeID() == solidID )
5812 meshDS->UnSetMeshElementOnShape( existFace, _grid->Shape( faceID ));
5817 if ( faceID && nbFaceNodes > 4 &&
5818 !_grid->IsInternal( faceID ) &&
5819 !_grid->IsShared( faceID ) &&
5820 !_grid->IsBoundaryFace( faceID ))
5822 // split a polygon that will be used by other 3D algorithm
5824 splitPolygon( newFace, vTool, iFacet, faceID, solidID,
5825 face, editor, i+1 < bndFacets.size() );
5830 meshDS->SetMeshElementOnShape( newFace, faceID );
5832 meshDS->SetMeshElementOnShape( newFace, solidID );
5834 } // loop on bndFacets
5835 } // loop on boundaryVolumes
5838 // Orient coherently mesh faces on INTERNAL FACEs
5842 TopExp_Explorer faceExp( _grid->_geometry._mainShape, TopAbs_FACE );
5843 for ( ; faceExp.More(); faceExp.Next() )
5845 if ( faceExp.Current().Orientation() != TopAbs_INTERNAL )
5848 SMESHDS_SubMesh* sm = meshDS->MeshElements( faceExp.Current() );
5849 if ( !sm ) continue;
5851 TIDSortedElemSet facesToOrient;
5852 for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
5853 facesToOrient.insert( facesToOrient.end(), fIt->next() );
5854 if ( facesToOrient.size() < 2 )
5857 gp_Dir direction(1,0,0);
5858 TIDSortedElemSet refFaces;
5859 editor.Reorient2D( facesToOrient, direction, refFaces, /*allowNonManifold=*/true );
5865 //================================================================================
5867 * \brief Create mesh segments.
5869 void Hexahedron::addSegments( SMESH_MesherHelper& helper,
5870 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap )
5872 SMESHDS_Mesh* mesh = helper.GetMeshDS();
5874 std::vector<const SMDS_MeshNode*> nodes;
5875 std::vector<const SMDS_MeshElement *> elems;
5876 map< TGeomID, vector< TGeomID > >::const_iterator e2ff = edge2faceIDsMap.begin();
5877 for ( ; e2ff != edge2faceIDsMap.end(); ++e2ff )
5879 const TopoDS_Edge& edge = TopoDS::Edge( _grid->Shape( e2ff->first ));
5880 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( e2ff->second[0] ));
5881 StdMeshers_FaceSide side( face, edge, helper.GetMesh(), /*isFwd=*/true, /*skipMed=*/true );
5882 nodes = side.GetOrderedNodes();
5885 if ( nodes.size() == 2 )
5886 // check that there is an element connecting two nodes
5887 if ( !mesh->GetElementsByNodes( nodes, elems ))
5890 for ( size_t i = 1; i < nodes.size(); i++ )
5892 if ( mesh->FindEdge( nodes[i-1], nodes[i] ))
5894 SMDS_MeshElement* segment = mesh->AddEdge( nodes[i-1], nodes[i] );
5895 mesh->SetMeshElementOnShape( segment, e2ff->first );
5901 //================================================================================
5903 * \brief Return created volumes and volumes that can have free facet because of
5904 * skipped small volume. Also create mesh faces on free facets
5905 * of adjacent not-cut volumes if the result volume is too small.
5907 void Hexahedron::getBoundaryElems( vector< const SMDS_MeshElement* > & boundaryElems )
5909 if ( _hasTooSmall /*|| _volumeDefs.IsEmpty()*/ )
5911 // create faces around a missing small volume
5913 SMESH_MeshEditor editor( _grid->_helper->GetMesh() );
5914 SMESH_MeshEditor::ElemFeatures polygon( SMDSAbs_Face );
5915 SMESHDS_Mesh* meshDS = _grid->_helper->GetMeshDS();
5916 std::vector<const SMDS_MeshElement *> adjVolumes(2);
5917 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
5919 const size_t nbLinks = _polygons[ iF ]._links.size();
5920 if ( nbLinks != 4 ) continue;
5921 polygon.myNodes.resize( nbLinks );
5922 polygon.myNodes.back() = 0;
5923 for ( size_t iL = 0, iN = nbLinks - 1; iL < nbLinks; ++iL, --iN )
5924 if ( ! ( polygon.myNodes[iN] = _polygons[ iF ]._links[ iL ].FirstNode()->Node() ))
5926 if ( !polygon.myNodes.back() )
5929 meshDS->GetElementsByNodes( polygon.myNodes, adjVolumes, SMDSAbs_Volume );
5930 if ( adjVolumes.size() != 1 )
5932 if ( !adjVolumes[0]->isMarked() )
5934 boundaryElems.push_back( adjVolumes[0] );
5935 adjVolumes[0]->setIsMarked( true );
5938 bool sameShape = true;
5939 TGeomID shapeID = polygon.myNodes[0]->GetShapeID();
5940 for ( size_t i = 1; i < polygon.myNodes.size() && sameShape; ++i )
5941 sameShape = ( shapeID == polygon.myNodes[i]->GetShapeID() );
5943 if ( !sameShape || !_grid->IsSolid( shapeID ))
5944 continue; // some of shapes must be FACE
5948 faceID = getAnyFace();
5951 if ( _grid->IsInternal( faceID ) ||
5952 _grid->IsShared( faceID ) //||
5953 //_grid->IsBoundaryFace( faceID ) -- commented for #19887
5955 break; // create only if a new face will be used by other 3D algo
5958 Solid * solid = _grid->GetOneOfSolids( adjVolumes[0]->GetShapeID() );
5959 if ( !solid->IsOutsideOriented( faceID ))
5960 std::reverse( polygon.myNodes.begin(), polygon.myNodes.end() );
5962 //polygon.SetPoly( polygon.myNodes.size() > 4 );
5963 const SMDS_MeshElement* newFace = editor.AddElement( polygon.myNodes, polygon );
5964 meshDS->SetMeshElementOnShape( newFace, faceID );
5968 // return created volumes
5969 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
5971 if ( volDef ->_volume &&
5972 !volDef->_volume->IsNull() &&
5973 !volDef->_volume->isMarked() )
5975 volDef->_volume->setIsMarked( true );
5976 boundaryElems.push_back( volDef->_volume );
5978 if ( _grid->IsToCheckNodePos() ) // un-mark nodes marked in addVolumes()
5979 for ( size_t iN = 0; iN < volDef->_nodes.size(); ++iN )
5980 volDef->_nodes[iN].Node()->setIsMarked( false );
5982 if ( volDef->_brotherVolume.size() > 0 )
5984 for (auto _bro : volDef->_brotherVolume )
5986 _bro->setIsMarked( true );
5987 boundaryElems.push_back( _bro );
5993 //================================================================================
5995 * \brief Remove edges and nodes dividing a hexa side in the case if an adjacent
5996 * volume also sharing the dividing edge is missing due to its small side.
5999 //================================================================================
6001 void Hexahedron::removeExcessSideDivision(const vector< Hexahedron* >& allHexa)
6003 if ( ! _volumeDefs.IsPolyhedron() )
6004 return; // not a polyhedron
6006 // look for a divided side adjacent to a small hexahedron
6008 int di[6] = { 0, 0, 0, 0,-1, 1 };
6009 int dj[6] = { 0, 0,-1, 1, 0, 0 };
6010 int dk[6] = {-1, 1, 0, 0, 0, 0 };
6012 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
6014 size_t neighborIndex = _grid->CellIndex( _i + di[iF],
6017 if ( neighborIndex >= allHexa.size() ||
6018 !allHexa[ neighborIndex ] ||
6019 !allHexa[ neighborIndex ]->_hasTooSmall )
6022 // check if a side is divided into several polygons
6023 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
6025 int nbPolygons = 0, nbNodes = 0;
6026 for ( size_t i = 0; i < volDef->_names.size(); ++i )
6027 if ( volDef->_names[ i ] == _hexQuads[ iF ]._name )
6030 nbNodes += volDef->_quantities[ i ];
6032 if ( nbPolygons < 2 )
6035 // construct loops from polygons
6036 typedef _volumeDef::_linkDef TLinkDef;
6037 std::vector< TLinkDef* > loops;
6038 std::vector< TLinkDef > links( nbNodes );
6039 for ( size_t i = 0, iN = 0, iLoop = 0; iLoop < volDef->_quantities.size(); ++iLoop )
6041 size_t nbLinks = volDef->_quantities[ iLoop ];
6042 if ( volDef->_names[ iLoop ] != _hexQuads[ iF ]._name )
6047 loops.push_back( & links[i] );
6048 for ( size_t n = 0; n < nbLinks-1; ++n, ++i, ++iN )
6050 links[i].init( volDef->_nodes[iN], volDef->_nodes[iN+1], iLoop );
6051 links[i].setNext( &links[i+1] );
6053 links[i].init( volDef->_nodes[iN], volDef->_nodes[iN-nbLinks+1], iLoop );
6054 links[i].setNext( &links[i-nbLinks+1] );
6058 // look for equal links in different loops and join such loops
6059 bool loopsJoined = false;
6060 std::set< TLinkDef > linkSet;
6061 for ( size_t iLoop = 0; iLoop < loops.size(); ++iLoop )
6064 for ( TLinkDef* l = loops[ iLoop ]; l != beg; l = l->_next ) // walk around the iLoop
6066 std::pair< std::set< TLinkDef >::iterator, bool > it2new = linkSet.insert( *l );
6067 if ( !it2new.second ) // equal found, join loops
6069 const TLinkDef* equal = &(*it2new.first);
6070 if ( equal->_loopIndex == l->_loopIndex )
6075 for ( size_t i = iLoop - 1; i < loops.size(); --i )
6076 if ( loops[ i ] && loops[ i ]->_loopIndex == equal->_loopIndex )
6079 // exclude l and equal and join two loops
6080 if ( l->_prev != equal )
6081 l->_prev->setNext( equal->_next );
6082 if ( equal->_prev != l )
6083 equal->_prev->setNext( l->_next );
6085 if ( volDef->_quantities[ l->_loopIndex ] > 0 )
6086 volDef->_quantities[ l->_loopIndex ] *= -1;
6087 if ( volDef->_quantities[ equal->_loopIndex ] > 0 )
6088 volDef->_quantities[ equal->_loopIndex ] *= -1;
6090 if ( loops[ iLoop ] == l )
6091 loops[ iLoop ] = l->_prev->_next;
6093 beg = loops[ iLoop ];
6099 // set unchanged polygons
6100 std::vector< int > newQuantities;
6101 std::vector< _volumeDef::_nodeDef > newNodes;
6102 vector< SMESH_Block::TShapeID > newNames;
6103 newQuantities.reserve( volDef->_quantities.size() );
6104 newNodes.reserve ( volDef->_nodes.size() );
6105 newNames.reserve ( volDef->_names.size() );
6106 for ( size_t i = 0, iLoop = 0; iLoop < volDef->_quantities.size(); ++iLoop )
6108 if ( volDef->_quantities[ iLoop ] < 0 )
6110 i -= volDef->_quantities[ iLoop ];
6113 newQuantities.push_back( volDef->_quantities[ iLoop ]);
6114 newNodes.insert( newNodes.end(),
6115 volDef->_nodes.begin() + i,
6116 volDef->_nodes.begin() + i + newQuantities.back() );
6117 newNames.push_back( volDef->_names[ iLoop ]);
6118 i += volDef->_quantities[ iLoop ];
6122 for ( size_t iLoop = 0; iLoop < loops.size(); ++iLoop )
6124 if ( !loops[ iLoop ] )
6126 newQuantities.push_back( 0 );
6128 for ( TLinkDef* l = loops[ iLoop ]; l != beg; l = l->_next, ++newQuantities.back() )
6130 newNodes.push_back( l->_node1 );
6131 beg = loops[ iLoop ];
6133 newNames.push_back( _hexQuads[ iF ]._name );
6135 volDef->_quantities.swap( newQuantities );
6136 volDef->_nodes.swap( newNodes );
6137 volDef->_names.swap( newNames );
6139 } // loop on volDef's
6140 } // loop on hex sides
6143 } // removeExcessSideDivision()
6146 //================================================================================
6148 * \brief Remove nodes splitting Cartesian cell edges in the case if a node
6149 * is used in every cells only by two polygons sharing the edge
6152 //================================================================================
6154 void Hexahedron::removeExcessNodes(vector< Hexahedron* >& allHexa)
6156 if ( ! _volumeDefs.IsPolyhedron() )
6157 return; // not a polyhedron
6159 typedef vector< _volumeDef::_nodeDef >::iterator TNodeIt;
6160 vector< int > nodesInPoly[ 4 ]; // node index in _volumeDefs._nodes
6161 vector< int > volDefInd [ 4 ]; // index of a _volumeDefs
6162 Hexahedron* hexa [ 4 ];
6163 int i,j,k, cellIndex, iLink = 0, iCellLink;
6164 for ( int iDir = 0; iDir < 3; ++iDir )
6166 CellsAroundLink fourCells( _grid, iDir );
6167 for ( int iL = 0; iL < 4; ++iL, ++iLink ) // 4 links in a direction
6169 _Link& link = _hexLinks[ iLink ];
6170 fourCells.Init( _i, _j, _k, iLink );
6172 for ( size_t iP = 0; iP < link._fIntPoints.size(); ++iP ) // loop on nodes on the link
6174 bool nodeRemoved = true;
6175 _volumeDef::_nodeDef node; node._intPoint = link._fIntPoints[iP];
6177 for ( size_t i = 0, nb = _volumeDefs.size(); i < nb && nodeRemoved; ++i )
6178 if ( _volumeDef* vol = _volumeDefs.at( i ))
6180 ( std::find( vol->_nodes.begin(), vol->_nodes.end(), node ) == vol->_nodes.end() );
6182 continue; // node already removed
6184 // check if a node encounters zero or two times in 4 cells sharing iLink
6185 // if so, the node can be removed from the cells
6186 bool nodeIsOnEdge = true;
6187 int nbPolyhedraWithNode = 0;
6188 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing a link
6190 nodesInPoly[ iC ].clear();
6191 volDefInd [ iC ].clear();
6193 if ( !fourCells.GetCell( iC, i,j,k, cellIndex, iCellLink ))
6195 hexa[ iC ] = allHexa[ cellIndex ];
6198 for ( size_t i = 0, nb = hexa[ iC ]->_volumeDefs.size(); i < nb; ++i )
6199 if ( _volumeDef* vol = hexa[ iC ]->_volumeDefs.at( i ))
6201 for ( TNodeIt nIt = vol->_nodes.begin(); nIt != vol->_nodes.end(); ++nIt )
6203 nIt = std::find( nIt, vol->_nodes.end(), node );
6204 if ( nIt != vol->_nodes.end() )
6206 nodesInPoly[ iC ].push_back( std::distance( vol->_nodes.begin(), nIt ));
6207 volDefInd [ iC ].push_back( i );
6212 nbPolyhedraWithNode += ( !nodesInPoly[ iC ].empty() );
6214 if ( nodesInPoly[ iC ].size() != 0 &&
6215 nodesInPoly[ iC ].size() != 2 )
6217 nodeIsOnEdge = false;
6220 } // loop on 4 cells
6222 // remove nodes from polyhedra
6223 if ( nbPolyhedraWithNode > 0 && nodeIsOnEdge )
6225 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing the link
6227 if ( nodesInPoly[ iC ].empty() )
6229 for ( int i = volDefInd[ iC ].size() - 1; i >= 0; --i )
6231 _volumeDef* vol = hexa[ iC ]->_volumeDefs.at( volDefInd[ iC ][ i ]);
6232 int nIndex = nodesInPoly[ iC ][ i ];
6233 // decrement _quantities
6234 for ( size_t iQ = 0; iQ < vol->_quantities.size(); ++iQ )
6235 if ( nIndex < vol->_quantities[ iQ ])
6237 vol->_quantities[ iQ ]--;
6242 nIndex -= vol->_quantities[ iQ ];
6244 vol->_nodes.erase( vol->_nodes.begin() + nodesInPoly[ iC ][ i ]);
6247 vol->_nodes.size() == 6 * 4 &&
6248 vol->_quantities.size() == 6 ) // polyhedron becomes hexahedron?
6250 bool allQuads = true;
6251 for ( size_t iQ = 0; iQ < vol->_quantities.size() && allQuads; ++iQ )
6252 allQuads = ( vol->_quantities[ iQ ] == 4 );
6255 // set side nodes as this: bottom, top, top, ...
6256 int iTop = 0, iBot = 0; // side indices
6257 for ( int iS = 0; iS < 6; ++iS )
6259 if ( vol->_names[ iS ] == SMESH_Block::ID_Fxy0 )
6261 if ( vol->_names[ iS ] == SMESH_Block::ID_Fxy1 )
6268 std::copy( vol->_nodes.begin(),
6269 vol->_nodes.begin() + 4,
6270 vol->_nodes.begin() + 4 );
6273 std::copy( vol->_nodes.begin() + 4 * iBot,
6274 vol->_nodes.begin() + 4 * ( iBot + 1),
6275 vol->_nodes.begin() );
6278 std::copy( vol->_nodes.begin() + 4 * iTop,
6279 vol->_nodes.begin() + 4 * ( iTop + 1),
6280 vol->_nodes.begin() + 4 );
6282 std::copy( vol->_nodes.begin() + 4,
6283 vol->_nodes.begin() + 8,
6284 vol->_nodes.begin() + 8 );
6285 // set up top facet nodes by comparing their uvw with bottom nodes
6286 E_IntersectPoint ip[8];
6287 for ( int iN = 0; iN < 8; ++iN )
6289 SMESH_NodeXYZ p = vol->_nodes[ iN ].Node();
6290 _grid->ComputeUVW( p, ip[ iN ]._uvw );
6292 const double tol2 = _grid->_tol * _grid->_tol;
6293 for ( int iN = 0; iN < 4; ++iN )
6295 gp_Pnt2d pBot( ip[ iN ]._uvw[0], ip[ iN ]._uvw[1] );
6296 for ( int iT = 4; iT < 8; ++iT )
6298 gp_Pnt2d pTop( ip[ iT ]._uvw[0], ip[ iT ]._uvw[1] );
6299 if ( pBot.SquareDistance( pTop ) < tol2 )
6301 // vol->_nodes[ iN + 4 ]._node = ip[ iT ]._node;
6302 // vol->_nodes[ iN + 4 ]._intPoint = 0;
6303 vol->_nodes[ iN + 4 ] = vol->_nodes[ iT + 4 ];
6308 vol->_nodes.resize( 8 );
6309 vol->_quantities.clear();
6310 //vol->_names.clear();
6313 } // loop on _volumeDefs
6314 } // loop on 4 cell abound a link
6315 } // if ( nodeIsOnEdge )
6316 } // loop on intersection points of a link
6317 } // loop on 4 links of a direction
6318 } // loop on 3 directions
6322 } // removeExcessNodes()
6324 //================================================================================
6326 * \brief [Issue #19913] Modify _hexLinks._splits to prevent creating overlapping volumes
6328 //================================================================================
6330 void Hexahedron::preventVolumesOverlapping()
6332 // Cut off a quadrangle corner if two links sharing the corner
6333 // are shared by same two solids, in this case each of solids gets
6334 // a triangle for it-self.
6335 std::vector< TGeomID > soIDs[4];
6336 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
6338 _Face& quad = _hexQuads[ iF ] ;
6340 int iFOpposite = iF + ( iF % 2 ? -1 : 1 );
6341 _Face& quadOpp = _hexQuads[ iFOpposite ] ;
6343 int nbSides = 0, nbSidesOpp = 0;
6344 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
6346 nbSides += ( quad._links [ iE ].NbResultLinks() > 0 );
6347 nbSidesOpp += ( quadOpp._links[ iE ].NbResultLinks() > 0 );
6349 if ( nbSides < 4 || nbSidesOpp != 2 )
6352 for ( int iE = 0; iE < 4; ++iE )
6354 soIDs[ iE ].clear();
6355 _Node* n = quad._links[ iE ].FirstNode();
6356 if ( n->_intPoint && n->_intPoint->_faceIDs.size() )
6357 soIDs[ iE ] = _grid->GetSolidIDs( n->_intPoint->_faceIDs[0] );
6359 if ((( soIDs[0].size() >= 2 ) +
6360 ( soIDs[1].size() >= 2 ) +
6361 ( soIDs[2].size() >= 2 ) +
6362 ( soIDs[3].size() >= 2 ) ) < 3 )
6366 for ( int i = 0; i < 4; ++i )
6368 int i1 = _grid->_helper->WrapIndex( i + 1, 4 );
6369 int i2 = _grid->_helper->WrapIndex( i + 2, 4 );
6370 int i3 = _grid->_helper->WrapIndex( i + 3, 4 );
6371 if ( soIDs[i1].size() == 2 && soIDs[i ] != soIDs[i1] &&
6372 soIDs[i2].size() == 2 && soIDs[i1] == soIDs[i2] &&
6373 soIDs[i3].size() == 2 && soIDs[i2] == soIDs[i3] )
6375 quad._links[ i1 ]._link->_splits.clear();
6376 quad._links[ i2 ]._link->_splits.clear();
6385 } // preventVolumesOverlapping()
6387 //================================================================================
6389 * \brief Set to _hexLinks a next portion of splits located on one side of INTERNAL FACEs
6391 bool Hexahedron::_SplitIterator::Next()
6393 if ( _iterationNb > 0 )
6394 // count used splits
6395 for ( size_t i = 0; i < _splits.size(); ++i )
6397 if ( _splits[i]._iCheckIteration == _iterationNb )
6399 _splits[i]._isUsed = _splits[i]._checkedSplit->_faces[1];
6400 _nbUsed += _splits[i]._isUsed;
6408 bool toTestUsed = ( _nbChecked >= _splits.size() );
6411 // all splits are checked; find all not used splits
6412 for ( size_t i = 0; i < _splits.size(); ++i )
6413 if ( !_splits[i].IsCheckedOrUsed( toTestUsed ))
6414 _splits[i]._iCheckIteration = _iterationNb;
6416 _nbUsed = _splits.size(); // to stop iteration
6420 // get any not used/checked split to start from
6422 for ( size_t i = 0; i < _splits.size(); ++i )
6424 if ( !_splits[i].IsCheckedOrUsed( toTestUsed ))
6426 _freeNodes.push_back( _splits[i]._nodes[0] );
6427 _freeNodes.push_back( _splits[i]._nodes[1] );
6428 _splits[i]._iCheckIteration = _iterationNb;
6432 // find splits connected to the start one via _freeNodes
6433 for ( size_t iN = 0; iN < _freeNodes.size(); ++iN )
6435 for ( size_t iS = 0; iS < _splits.size(); ++iS )
6437 if ( _splits[iS].IsCheckedOrUsed( toTestUsed ))
6440 if ( _freeNodes[iN] == _splits[iS]._nodes[0] )
6442 else if ( _freeNodes[iN] == _splits[iS]._nodes[1] )
6446 if ( _freeNodes[iN]->_isInternalFlags > 0 )
6448 if ( _splits[iS]._nodes[ iN2 ]->_isInternalFlags == 0 )
6450 if ( !_splits[iS]._nodes[ iN2 ]->IsLinked( _freeNodes[iN]->_intPoint ))
6453 _splits[iS]._iCheckIteration = _iterationNb;
6454 _freeNodes.push_back( _splits[iS]._nodes[ iN2 ]);
6458 // set splits to hex links
6460 for ( int iL = 0; iL < 12; ++iL )
6461 _hexLinks[ iL ]._splits.clear();
6464 for ( size_t i = 0; i < _splits.size(); ++i )
6466 if ( _splits[i]._iCheckIteration == _iterationNb )
6468 split._nodes[0] = _splits[i]._nodes[0];
6469 split._nodes[1] = _splits[i]._nodes[1];
6470 _Link & hexLink = _hexLinks[ _splits[i]._linkID ];
6471 hexLink._splits.push_back( split );
6472 _splits[i]._checkedSplit = & hexLink._splits.back();
6479 //================================================================================
6481 * \brief computes exact bounding box with axes parallel to given ones
6483 //================================================================================
6485 void getExactBndBox( const vector< TopoDS_Shape >& faceVec,
6486 const double* axesDirs,
6490 TopoDS_Compound allFacesComp;
6491 b.MakeCompound( allFacesComp );
6492 for ( size_t iF = 0; iF < faceVec.size(); ++iF )
6493 b.Add( allFacesComp, faceVec[ iF ] );
6495 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
6496 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
6498 for ( int i = 0; i < 6; ++i )
6499 farDist = Max( farDist, 10 * sP[i] );
6501 gp_XYZ axis[3] = { gp_XYZ( axesDirs[0], axesDirs[1], axesDirs[2] ),
6502 gp_XYZ( axesDirs[3], axesDirs[4], axesDirs[5] ),
6503 gp_XYZ( axesDirs[6], axesDirs[7], axesDirs[8] ) };
6504 axis[0].Normalize();
6505 axis[1].Normalize();
6506 axis[2].Normalize();
6508 gp_Mat basis( axis[0], axis[1], axis[2] );
6509 gp_Mat bi = basis.Inverted();
6512 for ( int iDir = 0; iDir < 3; ++iDir )
6514 gp_XYZ axis0 = axis[ iDir ];
6515 gp_XYZ axis1 = axis[ ( iDir + 1 ) % 3 ];
6516 gp_XYZ axis2 = axis[ ( iDir + 2 ) % 3 ];
6517 for ( int isMax = 0; isMax < 2; ++isMax )
6519 double shift = isMax ? farDist : -farDist;
6520 gp_XYZ orig = shift * axis0;
6521 gp_XYZ norm = axis1 ^ axis2;
6522 gp_Pln pln( orig, norm );
6523 norm = pln.Axis().Direction().XYZ();
6524 BRepBuilderAPI_MakeFace plane( pln, -farDist, farDist, -farDist, farDist );
6526 gp_Pnt& pAxis = isMax ? pMax : pMin;
6527 gp_Pnt pPlane, pFaces;
6528 double dist = GEOMUtils::GetMinDistance( plane, allFacesComp, pPlane, pFaces );
6533 for ( int i = 0; i < 2; ++i ) {
6534 corner.SetCoord( 1, sP[ i*3 ]);
6535 for ( int j = 0; j < 2; ++j ) {
6536 corner.SetCoord( 2, sP[ i*3 + 1 ]);
6537 for ( int k = 0; k < 2; ++k )
6539 corner.SetCoord( 3, sP[ i*3 + 2 ]);
6545 corner = isMax ? bb.CornerMax() : bb.CornerMin();
6546 pAxis.SetCoord( iDir+1, corner.Coord( iDir+1 ));
6550 gp_XYZ pf = pFaces.XYZ() * bi;
6551 pAxis.SetCoord( iDir+1, pf.Coord( iDir+1 ) );
6557 shapeBox.Add( pMin );
6558 shapeBox.Add( pMax );
6565 //=============================================================================
6567 * \brief Generates 3D structured Cartesian mesh in the internal part of
6568 * solid shapes and polyhedral volumes near the shape boundary.
6569 * \param theMesh - mesh to fill in
6570 * \param theShape - a compound of all SOLIDs to mesh
6571 * \retval bool - true in case of success
6573 //=============================================================================
6575 bool StdMeshers_Cartesian_3D::Compute(SMESH_Mesh & theMesh,
6576 const TopoDS_Shape & theShape)
6578 if ( _hypViscousLayers )
6580 const StdMeshers_ViscousLayers* hypViscousLayers = _hypViscousLayers;
6581 _hypViscousLayers = nullptr;
6583 StdMeshers_Cartesian_VL::ViscousBuilder builder( hypViscousLayers, theMesh, theShape );
6586 TopoDS_Shape offsetShape = builder.MakeOffsetShape( theShape, theMesh, error );
6587 if ( offsetShape.IsNull() )
6588 throw SALOME_Exception( error );
6590 SMESH_Mesh* offsetMesh = new TmpMesh();
6591 offsetMesh->ShapeToMesh( offsetShape );
6592 offsetMesh->GetSubMesh( offsetShape )->DependsOn();
6594 this->_isComputeOffset = true;
6595 if ( ! this->Compute( *offsetMesh, offsetShape ))
6598 return builder.MakeViscousLayers( *offsetMesh, theMesh, theShape );
6601 // The algorithm generates the mesh in following steps:
6603 // 1) Intersection of grid lines with the geometry boundary.
6604 // This step allows to find out if a given node of the initial grid is
6605 // inside or outside the geometry.
6607 // 2) For each cell of the grid, check how many of it's nodes are outside
6608 // of the geometry boundary. Depending on a result of this check
6609 // - skip a cell, if all it's nodes are outside
6610 // - skip a cell, if it is too small according to the size threshold
6611 // - add a hexahedron in the mesh, if all nodes are inside
6612 // - add a polyhedron in the mesh, if some nodes are inside and some outside
6614 _computeCanceled = false;
6616 SMESH_MesherHelper helper( theMesh );
6617 SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
6622 grid._helper = &helper;
6623 grid._toAddEdges = _hyp->GetToAddEdges();
6624 grid._toCreateFaces = _hyp->GetToCreateFaces();
6625 grid._toConsiderInternalFaces = _hyp->GetToConsiderInternalFaces();
6626 grid._toUseThresholdForInternalFaces = _hyp->GetToUseThresholdForInternalFaces();
6627 grid._sizeThreshold = _hyp->GetSizeThreshold();
6628 if ( _isComputeOffset )
6630 grid._toAddEdges = true;
6631 grid._toCreateFaces = true;
6633 grid.InitGeometry( theShape );
6635 vector< TopoDS_Shape > faceVec;
6637 TopTools_MapOfShape faceMap;
6638 TopExp_Explorer fExp;
6639 for ( fExp.Init( theShape, TopAbs_FACE ); fExp.More(); fExp.Next() )
6641 bool isNewFace = faceMap.Add( fExp.Current() );
6642 if ( !grid._toConsiderInternalFaces )
6643 if ( !isNewFace || fExp.Current().Orientation() == TopAbs_INTERNAL )
6644 // remove an internal face
6645 faceMap.Remove( fExp.Current() );
6647 faceVec.reserve( faceMap.Extent() );
6648 faceVec.assign( faceMap.cbegin(), faceMap.cend() );
6650 vector<FaceGridIntersector> facesItersectors( faceVec.size() );
6652 for ( size_t i = 0; i < faceVec.size(); ++i )
6654 facesItersectors[i]._face = TopoDS::Face( faceVec[i] );
6655 facesItersectors[i]._faceID = grid.ShapeID( faceVec[i] );
6656 facesItersectors[i]._grid = &grid;
6657 shapeBox.Add( facesItersectors[i].GetFaceBndBox() );
6659 getExactBndBox( faceVec, _hyp->GetAxisDirs(), shapeBox );
6662 vector<double> xCoords, yCoords, zCoords;
6663 _hyp->GetCoordinates( xCoords, yCoords, zCoords, shapeBox );
6665 grid.SetCoordinates( xCoords, yCoords, zCoords, _hyp->GetAxisDirs(), shapeBox );
6667 if ( _computeCanceled ) return false;
6670 { // copy partner faces and curves of not thread-safe types
6671 set< const Standard_Transient* > tshapes;
6672 BRepBuilderAPI_Copy copier;
6673 for ( size_t i = 0; i < facesItersectors.size(); ++i )
6675 if ( !facesItersectors[i].IsThreadSafe( tshapes ))
6677 copier.Perform( facesItersectors[i]._face );
6678 facesItersectors[i]._face = TopoDS::Face( copier );
6682 // Intersection of grid lines with the geometry boundary.
6683 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, facesItersectors.size() ),
6684 ParallelIntersector( facesItersectors ),
6685 tbb::simple_partitioner());
6687 for ( size_t i = 0; i < facesItersectors.size(); ++i )
6688 facesItersectors[i].Intersect();
6691 // put intersection points onto the GridLine's; this is done after intersection
6692 // to avoid contention of facesItersectors for writing into the same GridLine
6693 // in case of parallel work of facesItersectors
6694 for ( size_t i = 0; i < facesItersectors.size(); ++i )
6695 facesItersectors[i].StoreIntersections();
6697 if ( _computeCanceled ) return false;
6699 // create nodes on the geometry
6700 grid.ComputeNodes( helper );
6702 if ( _computeCanceled ) return false;
6704 // get EDGEs to take into account
6705 map< TGeomID, vector< TGeomID > > edge2faceIDsMap;
6706 grid.GetEdgesToImplement( edge2faceIDsMap, theShape, faceVec );
6708 // create volume elements
6709 Hexahedron hex( &grid );
6710 int nbAdded = hex.MakeElements( helper, edge2faceIDsMap );
6714 if ( !grid._toConsiderInternalFaces )
6716 // make all SOLIDs computed
6717 TopExp_Explorer solidExp( theShape, TopAbs_SOLID );
6718 if ( SMESHDS_SubMesh* sm1 = meshDS->MeshElements( solidExp.Current()) )
6720 SMDS_ElemIteratorPtr volIt = sm1->GetElements();
6721 for ( ; solidExp.More() && volIt->more(); solidExp.Next() )
6723 const SMDS_MeshElement* vol = volIt->next();
6724 sm1->RemoveElement( vol );
6725 meshDS->SetMeshElementOnShape( vol, solidExp.Current() );
6729 // make other sub-shapes computed
6730 setSubmeshesComputed( theMesh, theShape );
6733 // remove free nodes
6734 //if ( SMESHDS_SubMesh * smDS = meshDS->MeshElements( helper.GetSubShapeID() ))
6736 std::vector< const SMDS_MeshNode* > nodesToRemove;
6737 // get intersection nodes
6738 for ( int iDir = 0; iDir < 3; ++iDir )
6740 vector< GridLine >& lines = grid._lines[ iDir ];
6741 for ( size_t i = 0; i < lines.size(); ++i )
6743 multiset< F_IntersectPoint >::iterator ip = lines[i]._intPoints.begin();
6744 for ( ; ip != lines[i]._intPoints.end(); ++ip )
6746 !ip->_node->IsNull() &&
6747 ip->_node->NbInverseElements() == 0 &&
6748 !ip->_node->isMarked() )
6750 nodesToRemove.push_back( ip->_node );
6751 ip->_node->setIsMarked( true );
6756 for ( size_t i = 0; i < grid._nodes.size(); ++i )
6757 if ( grid._nodes[i] &&
6758 !grid._nodes[i]->IsNull() &&
6759 grid._nodes[i]->NbInverseElements() == 0 &&
6760 !grid._nodes[i]->isMarked() )
6762 nodesToRemove.push_back( grid._nodes[i] );
6763 grid._nodes[i]->setIsMarked( true );
6767 for ( size_t i = 0; i < nodesToRemove.size(); ++i )
6768 meshDS->RemoveFreeNode( nodesToRemove[i], /*smD=*/0, /*fromGroups=*/false );
6774 // SMESH_ComputeError is not caught at SMESH_submesh level for an unknown reason
6775 catch ( SMESH_ComputeError& e)
6777 return error( SMESH_ComputeErrorPtr( new SMESH_ComputeError( e )));
6782 //=============================================================================
6786 //=============================================================================
6788 bool StdMeshers_Cartesian_3D::Evaluate(SMESH_Mesh & /*theMesh*/,
6789 const TopoDS_Shape & /*theShape*/,
6790 MapShapeNbElems& /*theResMap*/)
6793 // std::vector<int> aResVec(SMDSEntity_Last);
6794 // for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
6795 // if(IsQuadratic) {
6796 // aResVec[SMDSEntity_Quad_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
6797 // int nb1d_face0_int = ( nb2d_face0*4 - nb1d ) / 2;
6798 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
6801 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
6802 // aResVec[SMDSEntity_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
6804 // SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
6805 // aResMap.insert(std::make_pair(sm,aResVec));
6810 //=============================================================================
6814 * \brief Event listener setting/unsetting _alwaysComputed flag to
6815 * submeshes of inferior levels to prevent their computing
6817 struct _EventListener : public SMESH_subMeshEventListener
6821 _EventListener(const string& algoName):
6822 SMESH_subMeshEventListener(/*isDeletable=*/true,"StdMeshers_Cartesian_3D::_EventListener"),
6825 // --------------------------------------------------------------------------------
6826 // setting/unsetting _alwaysComputed flag to submeshes of inferior levels
6828 static void setAlwaysComputed( const bool isComputed,
6829 SMESH_subMesh* subMeshOfSolid)
6831 SMESH_subMeshIteratorPtr smIt =
6832 subMeshOfSolid->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
6833 while ( smIt->more() )
6835 SMESH_subMesh* sm = smIt->next();
6836 sm->SetIsAlwaysComputed( isComputed );
6838 subMeshOfSolid->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
6841 // --------------------------------------------------------------------------------
6842 // unsetting _alwaysComputed flag if "Cartesian_3D" was removed
6844 virtual void ProcessEvent(const int /*event*/,
6845 const int eventType,
6846 SMESH_subMesh* subMeshOfSolid,
6847 SMESH_subMeshEventListenerData* /*data*/,
6848 const SMESH_Hypothesis* /*hyp*/ = 0)
6850 if ( eventType == SMESH_subMesh::COMPUTE_EVENT )
6852 setAlwaysComputed( subMeshOfSolid->GetComputeState() == SMESH_subMesh::COMPUTE_OK,
6857 SMESH_Algo* algo3D = subMeshOfSolid->GetAlgo();
6858 if ( !algo3D || _algoName != algo3D->GetName() )
6859 setAlwaysComputed( false, subMeshOfSolid );
6863 // --------------------------------------------------------------------------------
6864 // set the event listener
6866 static void SetOn( SMESH_subMesh* subMeshOfSolid, const string& algoName )
6868 subMeshOfSolid->SetEventListener( new _EventListener( algoName ),
6873 }; // struct _EventListener
6877 //================================================================================
6879 * \brief Sets event listener to submeshes if necessary
6880 * \param subMesh - submesh where algo is set
6881 * This method is called when a submesh gets HYP_OK algo_state.
6882 * After being set, event listener is notified on each event of a submesh.
6884 //================================================================================
6886 void StdMeshers_Cartesian_3D::SetEventListener(SMESH_subMesh* subMesh)
6888 _EventListener::SetOn( subMesh, GetName() );
6891 //================================================================================
6893 * \brief Set _alwaysComputed flag to submeshes of inferior levels to avoid their computing
6895 //================================================================================
6897 void StdMeshers_Cartesian_3D::setSubmeshesComputed(SMESH_Mesh& theMesh,
6898 const TopoDS_Shape& theShape)
6900 for ( TopExp_Explorer soExp( theShape, TopAbs_SOLID ); soExp.More(); soExp.Next() )
6901 _EventListener::setAlwaysComputed( true, theMesh.GetSubMesh( soExp.Current() ));