1 // Copyright (C) 2007-2024 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 SMDS_MeshNode* > _allBorderNodes; // mesh nodes between the bounding box and the geometry boundary
475 vector< const F_IntersectPoint* > _gridIntP; // grid node intersection with geometry
476 ObjectPool< E_IntersectPoint > _edgeIntPool; // intersections with EDGEs
477 ObjectPool< F_IntersectPoint > _extIntPool; // intersections with extended INTERNAL FACEs
478 //list< E_IntersectPoint > _edgeIntP; // intersections with EDGEs
483 bool _toConsiderInternalFaces;
484 bool _toUseThresholdForInternalFaces;
485 double _sizeThreshold;
489 SMESH_MesherHelper* _helper;
491 size_t CellIndex( size_t i, size_t j, size_t k ) const
493 return i + j*(_coords[0].size()-1) + k*(_coords[0].size()-1)*(_coords[1].size()-1);
495 size_t NodeIndex( size_t i, size_t j, size_t k ) const
497 return i + j*_coords[0].size() + k*_coords[0].size()*_coords[1].size();
499 size_t NodeIndex( const TIJK& ijk ) const
501 return NodeIndex( ijk[0], ijk[1], ijk[2] );
503 size_t NodeIndexDX() const { return 1; }
504 size_t NodeIndexDY() const { return _coords[0].size(); }
505 size_t NodeIndexDZ() const { return _coords[0].size() * _coords[1].size(); }
507 LineIndexer GetLineIndexer(size_t iDir) const;
508 size_t GetLineDir( const GridLine* line, size_t & index ) const;
510 E_IntersectPoint* Add( const E_IntersectPoint& ip )
512 E_IntersectPoint* eip = _edgeIntPool.getNew();
516 void Remove( E_IntersectPoint* eip ) { _edgeIntPool.destroy( eip ); }
518 TGeomID ShapeID( const TopoDS_Shape& s ) const;
519 const TopoDS_Shape& Shape( TGeomID id ) const;
520 TopAbs_ShapeEnum ShapeType( TGeomID id ) const { return Shape(id).ShapeType(); }
521 void InitGeometry( const TopoDS_Shape& theShape );
522 void InitClassifier( const TopoDS_Shape& mainShape,
523 TopAbs_ShapeEnum shapeType,
524 Controls::ElementsOnShape& classifier );
525 void GetEdgesToImplement( map< TGeomID, vector< TGeomID > > & edge2faceMap,
526 const TopoDS_Shape& shape,
527 const vector< TopoDS_Shape >& faces );
528 void SetSolidFather( const TopoDS_Shape& s, const TopoDS_Shape& theShapeToMesh );
529 bool IsShared( TGeomID faceID ) const;
530 bool IsAnyShared( const std::vector< TGeomID >& faceIDs ) const;
531 bool IsInternal( TGeomID faceID ) const {
532 return ( faceID == PseudoIntExtFaceID() ||
533 Shape( faceID ).Orientation() == TopAbs_INTERNAL ); }
534 bool IsSolid( TGeomID shapeID ) const {
535 if ( _geometry.IsOneSolid() ) return _geometry._soleSolid.ID() == shapeID;
536 else return _geometry._solidByID.count( shapeID ); }
537 bool IsStrangeEdge( TGeomID id ) const { return _geometry._strangeEdges.Contains( id ); }
538 TGeomID PseudoIntExtFaceID() const { return _geometry._extIntFaceID; }
539 Solid* GetSolid( TGeomID solidID = 0 );
540 Solid* GetOneOfSolids( TGeomID solidID );
541 const vector< TGeomID > & GetSolidIDs( TGeomID subShapeID ) const;
542 bool IsCorrectTransition( TGeomID faceID, const Solid* solid );
543 bool IsBoundaryFace( TGeomID face ) const { return _geometry._boundaryFaces.Contains( face ); }
544 void SetOnShape( const SMDS_MeshNode* n, const F_IntersectPoint& ip,
545 TopoDS_Vertex* vertex = nullptr, bool unset = false );
546 void UpdateFacesOfVertex( const B_IntersectPoint& ip, const TopoDS_Vertex& vertex );
547 bool IsToCheckNodePos() const { return !_toAddEdges && _toCreateFaces; }
548 bool IsToRemoveExcessEntities() const { return !_toAddEdges; }
550 void SetCoordinates(const vector<double>& xCoords,
551 const vector<double>& yCoords,
552 const vector<double>& zCoords,
553 const double* axesDirs,
554 const Bnd_Box& bndBox );
555 void ComputeUVW(const gp_XYZ& p, double uvw[3]);
556 void ComputeNodes(SMESH_MesherHelper& helper);
558 // --------------------------------------------------------------------------
560 * \brief Return cells sharing a link
562 struct CellsAroundLink
570 CellsAroundLink( Grid* grid, int iDir ):
572 _dInd{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} },
573 _nbCells{ grid->_coords[0].size() - 1,
574 grid->_coords[1].size() - 1,
575 grid->_coords[2].size() - 1 },
578 const int iDirOther[3][2] = {{ 1,2 },{ 0,2 },{ 0,1 }};
579 _dInd[1][ iDirOther[iDir][0] ] = -1;
580 _dInd[2][ iDirOther[iDir][1] ] = -1;
581 _dInd[3][ iDirOther[iDir][0] ] = -1; _dInd[3][ iDirOther[iDir][1] ] = -1;
583 void Init( int i, int j, int k, int link12 = 0 )
586 _i = i - _dInd[iL][0];
587 _j = j - _dInd[iL][1];
588 _k = k - _dInd[iL][2];
590 bool GetCell( int iL, int& i, int& j, int& k, int& cellIndex, int& linkIndex )
592 i = _i + _dInd[iL][0];
593 j = _j + _dInd[iL][1];
594 k = _k + _dInd[iL][2];
595 if ( i < 0 || i >= (int)_nbCells[0] ||
596 j < 0 || j >= (int)_nbCells[1] ||
597 k < 0 || k >= (int)_nbCells[2] )
599 cellIndex = _grid->CellIndex( i,j,k );
600 linkIndex = iL + _iDir * 4;
604 // --------------------------------------------------------------------------
606 * \brief Intersector of TopoDS_Face with all GridLine's
608 struct FaceGridIntersector
614 IntCurvesFace_Intersector* _surfaceInt;
615 vector< std::pair< GridLine*, F_IntersectPoint > > _intersections;
617 FaceGridIntersector(): _grid(0), _surfaceInt(0) {}
620 void StoreIntersections()
622 for ( size_t i = 0; i < _intersections.size(); ++i )
624 multiset< F_IntersectPoint >::iterator ip =
625 _intersections[i].first->_intPoints.insert( _intersections[i].second );
626 ip->_faceIDs.reserve( 1 );
627 ip->_faceIDs.push_back( _faceID );
630 const Bnd_Box& GetFaceBndBox()
632 GetCurveFaceIntersector();
635 IntCurvesFace_Intersector* GetCurveFaceIntersector()
639 _surfaceInt = new IntCurvesFace_Intersector( _face, Precision::PConfusion() );
640 _bndBox = _surfaceInt->Bounding();
641 if ( _bndBox.IsVoid() )
642 BRepBndLib::Add (_face, _bndBox);
646 bool IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const;
648 // --------------------------------------------------------------------------
650 * \brief Intersector of a surface with a GridLine
652 struct FaceLineIntersector
655 double _u, _v, _w; // params on the face and the line
656 Transition _transition; // transition at intersection (see IntCurveSurface.cdl)
657 Transition _transIn, _transOut; // IN and OUT transitions depending of face orientation
660 gp_Cylinder _cylinder;
664 IntCurvesFace_Intersector* _surfaceInt;
666 vector< F_IntersectPoint > _intPoints;
668 void IntersectWithPlane (const GridLine& gridLine);
669 void IntersectWithCylinder(const GridLine& gridLine);
670 void IntersectWithCone (const GridLine& gridLine);
671 void IntersectWithSphere (const GridLine& gridLine);
672 void IntersectWithTorus (const GridLine& gridLine);
673 void IntersectWithSurface (const GridLine& gridLine);
675 bool UVIsOnFace() const;
676 void addIntPoint(const bool toClassify=true);
677 bool isParamOnLineOK( const double linLength )
679 return -_tol < _w && _w < linLength + _tol;
681 FaceLineIntersector():_surfaceInt(0) {}
682 ~FaceLineIntersector() { if (_surfaceInt ) delete _surfaceInt; _surfaceInt = 0; }
684 // --------------------------------------------------------------------------
686 * \brief Class representing topology of the hexahedron and creating a mesh
687 * volume basing on analysis of hexahedron intersection with geometry
691 // --------------------------------------------------------------------------------
694 enum IsInternalFlag { IS_NOT_INTERNAL, IS_INTERNAL, IS_CUT_BY_INTERNAL_FACE };
695 // --------------------------------------------------------------------------------
696 struct _Node //!< node either at a hexahedron corner or at intersection
698 const SMDS_MeshNode* _node; // mesh node at hexahedron corner
699 const SMDS_MeshNode* _boundaryCornerNode; // missing mesh node due to hex truncation on the boundary
700 const B_IntersectPoint* _intPoint;
701 const _Face* _usedInFace;
702 char _isInternalFlags;
704 _Node(const SMDS_MeshNode* n=0, const B_IntersectPoint* ip=0)
705 :_node(n), _intPoint(ip), _usedInFace(0), _isInternalFlags(0) {}
706 const SMDS_MeshNode* Node() const
707 { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
708 const SMDS_MeshNode* BoundaryNode() const
709 { return _node ? _node : _boundaryCornerNode; }
710 const E_IntersectPoint* EdgeIntPnt() const
711 { return static_cast< const E_IntersectPoint* >( _intPoint ); }
712 const F_IntersectPoint* FaceIntPnt() const
713 { return static_cast< const F_IntersectPoint* >( _intPoint ); }
714 const vector< TGeomID >& faces() const { return _intPoint->_faceIDs; }
715 TGeomID face(size_t i) const { return _intPoint->_faceIDs[ i ]; }
716 void SetInternal( IsInternalFlag intFlag ) { _isInternalFlags |= intFlag; }
717 bool IsCutByInternal() const { return _isInternalFlags & IS_CUT_BY_INTERNAL_FACE; }
718 bool IsUsedInFace( const _Face* polygon = 0 )
720 return polygon ? ( _usedInFace == polygon ) : bool( _usedInFace );
722 TGeomID IsLinked( const B_IntersectPoint* other,
723 TGeomID avoidFace=-1 ) const // returns id of a common face
725 return _intPoint ? _intPoint->HasCommonFace( other, avoidFace ) : 0;
727 bool IsOnFace( TGeomID faceID ) const // returns true if faceID is found
729 return _intPoint ? _intPoint->IsOnFace( faceID ) : false;
731 size_t GetCommonFaces( const B_IntersectPoint * other, TGeomID* common ) const
733 return _intPoint && other ? _intPoint->GetCommonFaces( other, common ) : 0;
737 if ( const SMDS_MeshNode* n = Node() )
738 return SMESH_NodeXYZ( n );
739 if ( const E_IntersectPoint* eip =
740 dynamic_cast< const E_IntersectPoint* >( _intPoint ))
742 return gp_Pnt( 1e100, 0, 0 );
744 TGeomID ShapeID() const
746 if ( const E_IntersectPoint* eip = dynamic_cast< const E_IntersectPoint* >( _intPoint ))
747 return eip->_shapeID;
750 void Add( const E_IntersectPoint* ip )
752 // Possible cases before Add(ip):
753 /// 1) _node != 0 --> _Node at hex corner ( _intPoint == 0 || _intPoint._node == 0 )
754 /// 2) _node == 0 && _intPoint._node != 0 --> link intersected by FACE
755 /// 3) _node == 0 && _intPoint._node == 0 --> _Node at EDGE intersection
757 // If ip is added in cases 1) and 2) _node position must be changed to ip._shapeID
758 // at creation of elements
759 // To recognize this case, set _intPoint._node = Node()
760 const SMDS_MeshNode* node = Node();
765 ip->Add( _intPoint->_faceIDs );
769 _node = _intPoint->_node = node;
772 // --------------------------------------------------------------------------------
773 struct _Link // link connecting two _Node's
776 _Face* _faces[2]; // polygons sharing a link
777 vector< const F_IntersectPoint* > _fIntPoints; // GridLine intersections with FACEs
778 vector< _Node* > _fIntNodes; // _Node's at _fIntPoints
779 vector< _Link > _splits;
780 _Link(): _faces{ 0, 0 } {}
782 // --------------------------------------------------------------------------------
787 _OrientedLink( _Link* link=0, bool reverse=false ): _link(link), _reverse(reverse) {}
788 void Reverse() { _reverse = !_reverse; }
789 size_t NbResultLinks() const { return _link->_splits.size(); }
790 _OrientedLink ResultLink(int i) const
792 return _OrientedLink(&_link->_splits[_reverse ? NbResultLinks()-i-1 : i],_reverse);
794 _Node* FirstNode() const { return _link->_nodes[ _reverse ]; }
795 _Node* LastNode() const { return _link->_nodes[ !_reverse ]; }
796 operator bool() const { return _link; }
797 vector< TGeomID > GetNotUsedFace(const set<TGeomID>& usedIDs ) const // returns supporting FACEs
799 vector< TGeomID > faces;
800 const B_IntersectPoint *ip0, *ip1;
801 if (( ip0 = _link->_nodes[0]->_intPoint ) &&
802 ( ip1 = _link->_nodes[1]->_intPoint ))
804 for ( size_t i = 0; i < ip0->_faceIDs.size(); ++i )
805 if ( ip1->IsOnFace ( ip0->_faceIDs[i] ) &&
806 !usedIDs.count( ip0->_faceIDs[i] ) )
807 faces.push_back( ip0->_faceIDs[i] );
811 bool HasEdgeNodes() const
813 return ( dynamic_cast< const E_IntersectPoint* >( _link->_nodes[0]->_intPoint ) ||
814 dynamic_cast< const E_IntersectPoint* >( _link->_nodes[1]->_intPoint ));
818 return !_link->_faces[0] ? 0 : 1 + bool( _link->_faces[1] );
820 void AddFace( _Face* f )
822 if ( _link->_faces[0] )
824 _link->_faces[1] = f;
828 _link->_faces[0] = f;
829 _link->_faces[1] = 0;
832 void RemoveFace( _Face* f )
834 if ( !_link->_faces[0] ) return;
836 if ( _link->_faces[1] == f )
838 _link->_faces[1] = 0;
840 else if ( _link->_faces[0] == f )
842 _link->_faces[0] = 0;
843 if ( _link->_faces[1] )
845 _link->_faces[0] = _link->_faces[1];
846 _link->_faces[1] = 0;
851 // --------------------------------------------------------------------------------
852 struct _SplitIterator //! set to _hexLinks splits on one side of INTERNAL FACEs
854 struct _Split // data of a link split
856 int _linkID; // hex link ID
858 int _iCheckIteration; // iteration where split is tried as Hexahedron split
859 _Link* _checkedSplit; // split set to hex links
860 bool _isUsed; // used in a volume
862 _Split( _Link & split, int iLink ):
863 _linkID( iLink ), _nodes{ split._nodes[0], split._nodes[1] },
864 _iCheckIteration( 0 ), _isUsed( false )
866 bool IsCheckedOrUsed( bool used ) const { return used ? _isUsed : _iCheckIteration > 0; }
869 std::vector< _Split > _splits;
873 std::vector< _Node* > _freeNodes; // nodes reached while composing a split set
875 _SplitIterator( _Link* hexLinks ):
876 _hexLinks( hexLinks ), _iterationNb(0), _nbChecked(0), _nbUsed(0)
878 _freeNodes.reserve( 12 );
879 _splits.reserve( 24 );
880 for ( int iL = 0; iL < 12; ++iL )
881 for ( size_t iS = 0; iS < _hexLinks[ iL ]._splits.size(); ++iS )
882 _splits.emplace_back( _hexLinks[ iL ]._splits[ iS ], iL );
885 bool More() const { return _nbUsed < _splits.size(); }
888 // --------------------------------------------------------------------------------
891 SMESH_Block::TShapeID _name;
892 vector< _OrientedLink > _links; // links on GridLine's
893 vector< _Link > _polyLinks; // links added to close a polygonal face
894 vector< _Node* > _eIntNodes; // nodes at intersection with EDGEs
896 _Face():_name( SMESH_Block::ID_NONE )
898 bool IsPolyLink( const _OrientedLink& ol )
900 return _polyLinks.empty() ? false :
901 ( &_polyLinks[0] <= ol._link && ol._link <= &_polyLinks.back() );
903 void AddPolyLink(_Node* n0, _Node* n1, _Face* faceToFindEqual=0)
905 if ( faceToFindEqual && faceToFindEqual != this ) {
906 for ( size_t iL = 0; iL < faceToFindEqual->_polyLinks.size(); ++iL )
907 if ( faceToFindEqual->_polyLinks[iL]._nodes[0] == n1 &&
908 faceToFindEqual->_polyLinks[iL]._nodes[1] == n0 )
911 ( _OrientedLink( & faceToFindEqual->_polyLinks[iL], /*reverse=*/true ));
918 _polyLinks.push_back( l );
919 _links.push_back( _OrientedLink( &_polyLinks.back() ));
922 // --------------------------------------------------------------------------------
923 struct _volumeDef // holder of nodes of a volume mesh element
929 const SMDS_MeshNode* _node; // mesh node at hexahedron corner
930 const B_IntersectPoint* _intPoint;
932 _nodeDef(): _node(0), _intPoint(0) {}
933 _nodeDef( _Node* n ): _node( n->_node), _intPoint( n->_intPoint ) {}
934 const SMDS_MeshNode* Node() const
935 { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
936 const E_IntersectPoint* EdgeIntPnt() const
937 { return static_cast< const E_IntersectPoint* >( _intPoint ); }
938 _ptr Ptr() const { return Node() ? (_ptr) Node() : (_ptr) EdgeIntPnt(); }
939 bool operator==(const _nodeDef& other ) const { return Ptr() == other.Ptr(); }
942 vector< _nodeDef > _nodes;
943 vector< int > _quantities;
944 _volumeDef* _next; // to store several _volumeDefs in a chain
947 const SMDS_MeshElement* _volume; // new volume
948 std::vector<const SMDS_MeshElement*> _brotherVolume; // produced due to poly split
950 vector< SMESH_Block::TShapeID > _names; // name of side a polygon originates from
952 _volumeDef(): _next(0), _solidID(0), _size(0), _volume(0) {}
953 ~_volumeDef() { delete _next; }
954 _volumeDef( _volumeDef& other ):
955 _next(0), _solidID( other._solidID ), _size( other._size ), _volume( other._volume )
956 { _nodes.swap( other._nodes ); _quantities.swap( other._quantities ); other._volume = 0;
957 _names.swap( other._names ); }
959 size_t size() const { return 1 + ( _next ? _next->size() : 0 ); } // nb _volumeDef in a chain
960 _volumeDef* at(int index)
961 { return index == 0 ? this : ( _next ? _next->at(index-1) : _next ); }
963 void Set( _Node** nodes, int nb )
964 { _nodes.assign( nodes, nodes + nb ); }
966 void SetNext( _volumeDef* vd )
967 { if ( _next ) { _next->SetNext( vd ); } else { _next = vd; }}
969 bool IsEmpty() const { return (( _nodes.empty() ) &&
970 ( !_next || _next->IsEmpty() )); }
971 bool IsPolyhedron() const { return ( !_quantities.empty() ||
972 ( _next && !_next->_quantities.empty() )); }
975 struct _linkDef: public std::pair<_ptr,_ptr> // to join polygons in removeExcessSideDivision()
977 _nodeDef _node1;//, _node2;
978 mutable /*const */_linkDef *_prev, *_next;
981 _linkDef():_prev(0), _next(0) {}
983 void init( const _nodeDef& n1, const _nodeDef& n2, size_t iLoop )
985 _node1 = n1; //_node2 = n2;
989 if ( first > second ) std::swap( first, second );
991 void setNext( _linkDef* next )
999 // topology of a hexahedron
1000 _Node _hexNodes [8];
1001 _Link _hexLinks [12];
1002 _Face _hexQuads [6];
1004 // faces resulted from hexahedron intersection
1005 vector< _Face > _polygons;
1007 // intresections with EDGEs
1008 vector< const E_IntersectPoint* > _eIntPoints;
1010 // additional nodes created at intersection points
1011 vector< _Node > _intNodes;
1013 // nodes inside the hexahedron (at VERTEXes) refer to _intNodes
1014 vector< _Node* > _vIntNodes;
1016 // computed volume elements
1017 _volumeDef _volumeDefs;
1020 double _sideLength[3];
1021 int _nbCornerNodes, _nbFaceIntNodes, _nbBndNodes;
1022 int _origNodeInd; // index of _hexNodes[0] node within the _grid
1028 Hexahedron(Grid* grid);
1029 int MakeElements(SMESH_MesherHelper& helper,
1030 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
1031 void computeElements( const Solid* solid = 0, int solidIndex = -1 );
1034 Hexahedron(const Hexahedron& other, size_t i, size_t j, size_t k, int cellID );
1035 void init( size_t i, size_t j, size_t k, const Solid* solid=0 );
1036 void init( size_t i );
1037 void setIJK( size_t i );
1038 bool compute( const Solid* solid, const IsInternalFlag intFlag );
1039 size_t getSolids( TGeomID ids[] );
1040 bool isCutByInternalFace( IsInternalFlag & maxFlag );
1041 void addEdges(SMESH_MesherHelper& helper,
1042 vector< Hexahedron* >& intersectedHex,
1043 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
1044 gp_Pnt findIntPoint( double u1, double proj1, double u2, double proj2,
1045 double proj, BRepAdaptor_Curve& curve,
1046 const gp_XYZ& axis, const gp_XYZ& origin );
1047 int getEntity( const E_IntersectPoint* ip, int* facets, int& sub );
1048 bool addIntersection( const E_IntersectPoint* ip,
1049 vector< Hexahedron* >& hexes,
1050 int ijk[], int dIJK[] );
1051 bool isQuadOnFace( const size_t iQuad );
1052 bool findChain( _Node* n1, _Node* n2, _Face& quad, vector<_Node*>& chainNodes );
1053 bool closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const;
1054 bool findChainOnEdge( const vector< _OrientedLink >& splits,
1055 const _OrientedLink& prevSplit,
1056 const _OrientedLink& avoidSplit,
1057 const std::set< TGeomID > & concaveFaces,
1060 vector<_Node*>& chn);
1061 int addVolumes(SMESH_MesherHelper& helper );
1062 void addFaces( SMESH_MesherHelper& helper,
1063 const vector< const SMDS_MeshElement* > & boundaryVolumes );
1064 void addSegments( SMESH_MesherHelper& helper,
1065 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap );
1066 void getVolumes( vector< const SMDS_MeshElement* > & volumes );
1067 void getBoundaryElems( vector< const SMDS_MeshElement* > & boundaryVolumes );
1068 void removeExcessSideDivision(const vector< Hexahedron* >& allHexa);
1069 void removeExcessNodes(vector< Hexahedron* >& allHexa);
1070 void preventVolumesOverlapping();
1071 TGeomID getAnyFace() const;
1072 void cutByExtendedInternal( std::vector< Hexahedron* >& hexes,
1073 const TColStd_MapOfInteger& intEdgeIDs );
1074 gp_Pnt mostDistantInternalPnt( int hexIndex, const gp_Pnt& p1, const gp_Pnt& p2 );
1075 bool isOutPoint( _Link& link, int iP, SMESH_MesherHelper& helper, const Solid* solid ) const;
1076 void sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID face);
1077 bool isInHole() const;
1078 bool hasStrangeEdge() const;
1079 bool checkPolyhedronSize( bool isCutByInternalFace, double & volSize ) const;
1080 int checkPolyhedronValidity( _volumeDef* volDef, std::vector<std::vector<int>>& splitQuantities,
1081 std::vector<std::vector<const SMDS_MeshNode*>>& splitNodes );
1082 const SMDS_MeshElement* addPolyhedronToMesh( _volumeDef* volDef, SMESH_MesherHelper& helper, const std::vector<const SMDS_MeshNode*>& nodes,
1083 const std::vector<int>& quantities );
1088 bool debugDumpLink( _Link* link );
1089 _Node* findEqualNode( vector< _Node* >& nodes,
1090 const E_IntersectPoint* ip,
1093 for ( size_t i = 0; i < nodes.size(); ++i )
1094 if ( nodes[i]->EdgeIntPnt() == ip ||
1095 nodes[i]->Point().SquareDistance( ip->_point ) <= tol2 )
1099 bool isCorner( const _Node* node ) const { return ( node >= &_hexNodes[0] &&
1100 node - &_hexNodes[0] < 8 ); }
1101 bool hasEdgesAround( const ConcaveFace* cf ) const;
1102 bool isImplementEdges() const { return _grid->_edgeIntPool.nbElements(); }
1103 bool isOutParam(const double uvw[3]) const;
1105 typedef boost::container::flat_map< TGeomID, size_t > TID2Nb;
1106 static void insertAndIncrement( TGeomID id, TID2Nb& id2nbMap )
1108 TID2Nb::value_type s0( id, 0 );
1109 TID2Nb::iterator id2nb = id2nbMap.insert( s0 ).first;
1112 }; // class Hexahedron
1115 // --------------------------------------------------------------------------
1117 * \brief Hexahedron computing volumes in one thread
1119 struct ParallelHexahedron
1121 vector< Hexahedron* >& _hexVec;
1122 ParallelHexahedron( vector< Hexahedron* >& hv ): _hexVec(hv) {}
1123 void operator() ( const tbb::blocked_range<size_t>& r ) const
1125 for ( size_t i = r.begin(); i != r.end(); ++i )
1126 if ( Hexahedron* hex = _hexVec[ i ] )
1127 hex->computeElements();
1130 // --------------------------------------------------------------------------
1132 * \brief Structure intersecting certain nb of faces with GridLine's in one thread
1134 struct ParallelIntersector
1136 vector< FaceGridIntersector >& _faceVec;
1137 ParallelIntersector( vector< FaceGridIntersector >& faceVec): _faceVec(faceVec){}
1138 void operator() ( const tbb::blocked_range<size_t>& r ) const
1140 for ( size_t i = r.begin(); i != r.end(); ++i )
1141 _faceVec[i].Intersect();
1146 //=============================================================================
1147 // Implementation of internal utils
1148 //=============================================================================
1150 * \brief adjust \a i to have \a val between values[i] and values[i+1]
1152 inline void locateValue( int & i, double val, const vector<double>& values,
1153 int& di, double tol )
1155 //val += values[0]; // input \a val is measured from 0.
1156 if ( i > (int) values.size()-2 )
1157 i = values.size()-2;
1159 while ( i+2 < (int) values.size() && val > values[ i+1 ])
1161 while ( i > 0 && val < values[ i ])
1164 if ( i > 0 && val - values[ i ] < tol )
1166 else if ( i+2 < (int) values.size() && values[ i+1 ] - val < tol )
1171 //=============================================================================
1173 * Return a vector of SOLIDS sharing given shapes
1175 GeomIDVecHelder Geometry::GetSolidIDsByShapeID( const vector< TGeomID >& theShapeIDs ) const
1177 if ( theShapeIDs.size() == 1 )
1178 return GeomIDVecHelder( _solidIDsByShapeID[ theShapeIDs[ 0 ]], /*owner=*/false );
1180 // look for an empty slot in _solidIDsByShapeID
1181 vector< TGeomID > * resultIDs = 0;
1182 for ( const vector< TGeomID >& vec : _solidIDsByShapeID )
1185 resultIDs = const_cast< vector< TGeomID > * >( & vec );
1188 // fill in resultIDs
1189 for ( const TGeomID& id : theShapeIDs )
1190 for ( const TGeomID& solid : _solidIDsByShapeID[ id ])
1192 if ( std::find( resultIDs->begin(), resultIDs->end(), solid ) == resultIDs->end() )
1193 resultIDs->push_back( solid );
1195 return GeomIDVecHelder( *resultIDs, /*owner=*/true );
1197 //=============================================================================
1199 * Remove coincident intersection points
1201 void GridLine::RemoveExcessIntPoints( const double tol )
1203 if ( _intPoints.size() < 2 ) return;
1205 set< Transition > tranSet;
1206 multiset< F_IntersectPoint >::iterator ip1, ip2 = _intPoints.begin();
1207 while ( ip2 != _intPoints.end() )
1211 while ( ip2 != _intPoints.end() && ip2->_paramOnLine - ip1->_paramOnLine <= tol )
1213 tranSet.insert( ip1->_transition );
1214 tranSet.insert( ip2->_transition );
1215 ip2->Add( ip1->_faceIDs );
1216 _intPoints.erase( ip1 );
1219 if ( tranSet.size() > 1 ) // points with different transition coincide
1221 bool isIN = tranSet.count( Trans_IN );
1222 bool isOUT = tranSet.count( Trans_OUT );
1223 if ( isIN && isOUT )
1224 (*ip1)._transition = Trans_TANGENT;
1226 (*ip1)._transition = isIN ? Trans_IN : Trans_OUT;
1230 //================================================================================
1232 * Return ID of SOLID for nodes before the given intersection point
1234 TGeomID GridLine::GetSolidIDBefore( multiset< F_IntersectPoint >::iterator ip,
1235 const TGeomID prevID,
1236 const Geometry& geom )
1238 if ( ip == _intPoints.begin() )
1241 if ( geom.IsOneSolid() )
1244 switch ( ip->_transition ) {
1245 case Trans_IN: isOut = true; break;
1246 case Trans_OUT: isOut = false; break;
1247 case Trans_TANGENT: isOut = ( prevID != 0 ); break;
1250 // singularity point (apex of a cone)
1251 multiset< F_IntersectPoint >::iterator ipBef = ip, ipAft = ++ip;
1252 if ( ipAft == _intPoints.end() )
1257 if ( ipBef->_transition != ipAft->_transition )
1258 isOut = ( ipBef->_transition == Trans_OUT );
1260 isOut = ( ipBef->_transition != Trans_OUT );
1264 case Trans_INTERNAL: isOut = false;
1267 return isOut ? 0 : geom._soleSolid.ID();
1270 GeomIDVecHelder solids = geom.GetSolidIDsByShapeID( ip->_faceIDs );
1273 if ( ip->_transition == Trans_INTERNAL )
1276 GeomIDVecHelder solidsBef = geom.GetSolidIDsByShapeID( ip->_faceIDs );
1278 if ( ip->_transition == Trans_IN ||
1279 ip->_transition == Trans_OUT )
1281 if ( solidsBef.size() == 1 )
1283 if ( solidsBef[0] == prevID )
1284 return ip->_transition == Trans_OUT ? 0 : solidsBef[0];
1286 return solidsBef[0];
1289 if ( solids.size() == 2 )
1291 if ( solids == solidsBef )
1292 return solids.contain( prevID ) ? solids.otherThan( prevID ) : theUndefID; // bos #29212
1294 return solids.oneCommon( solidsBef );
1297 if ( solidsBef.size() == 1 )
1298 return solidsBef[0];
1300 return solids.oneCommon( solidsBef );
1302 //================================================================================
1306 bool B_IntersectPoint::Add( const vector< TGeomID >& fIDs,
1307 const SMDS_MeshNode* n) const
1309 size_t prevNbF = _faceIDs.size();
1311 if ( _faceIDs.empty() )
1314 for ( size_t i = 0; i < fIDs.size(); ++i )
1316 vector< TGeomID >::iterator it =
1317 std::find( _faceIDs.begin(), _faceIDs.end(), fIDs[i] );
1318 if ( it == _faceIDs.end() )
1319 _faceIDs.push_back( fIDs[i] );
1324 return prevNbF < _faceIDs.size();
1326 //================================================================================
1328 * Return ID of a common face if any, else zero
1330 TGeomID B_IntersectPoint::HasCommonFace( const B_IntersectPoint * other, TGeomID avoidFace ) const
1333 for ( size_t i = 0; i < other->_faceIDs.size(); ++i )
1334 if ( avoidFace != other->_faceIDs[i] &&
1335 IsOnFace ( other->_faceIDs[i] ))
1336 return other->_faceIDs[i];
1339 //================================================================================
1341 * Return faces common with other point
1343 size_t B_IntersectPoint::GetCommonFaces( const B_IntersectPoint * other, TGeomID* common ) const
1348 if ( _faceIDs.size() > other->_faceIDs.size() )
1349 return other->GetCommonFaces( this, common );
1350 for ( const TGeomID& face : _faceIDs )
1351 if ( other->IsOnFace( face ))
1352 common[ nbComm++ ] = face;
1355 //================================================================================
1357 * Return \c true if \a faceID in in this->_faceIDs
1359 bool B_IntersectPoint::IsOnFace( TGeomID faceID ) const // returns true if faceID is found
1361 vector< TGeomID >::const_iterator it =
1362 std::find( _faceIDs.begin(), _faceIDs.end(), faceID );
1363 return ( it != _faceIDs.end() );
1365 //================================================================================
1367 * OneOfSolids initialization
1369 void OneOfSolids::Init( const TopoDS_Shape& solid,
1370 TopAbs_ShapeEnum subType,
1371 const SMESHDS_Mesh* mesh )
1373 SetID( mesh->ShapeToIndex( solid ));
1375 if ( subType == TopAbs_FACE )
1376 SetHasInternalFaces( false );
1378 for ( TopExp_Explorer sub( solid, subType ); sub.More(); sub.Next() )
1380 _subIDs.Add( mesh->ShapeToIndex( sub.Current() ));
1381 if ( subType == TopAbs_FACE )
1383 _faces.Add( sub.Current() );
1384 if ( sub.Current().Orientation() == TopAbs_INTERNAL )
1385 SetHasInternalFaces( true );
1387 TGeomID faceID = mesh->ShapeToIndex( sub.Current() );
1388 if ( sub.Current().Orientation() == TopAbs_INTERNAL ||
1389 sub.Current().Orientation() == mesh->IndexToShape( faceID ).Orientation() )
1390 _outFaceIDs.Add( faceID );
1394 //================================================================================
1396 * Return an iterator on GridLine's in a given direction
1398 LineIndexer Grid::GetLineIndexer(size_t iDir) const
1400 const size_t indices[] = { 1,2,0, 0,2,1, 0,1,2 };
1401 const string s [] = { "X", "Y", "Z" };
1402 LineIndexer li( _coords[0].size(), _coords[1].size(), _coords[2].size(),
1403 indices[iDir*3], indices[iDir*3+1], indices[iDir*3+2],
1404 s[indices[iDir*3]], s[indices[iDir*3+1]], s[indices[iDir*3+2]]);
1407 //================================================================================
1409 * Return direction [0,1,2] of a GridLine
1411 size_t Grid::GetLineDir( const GridLine* line, size_t & index ) const
1413 for ( size_t iDir = 0; iDir < 3; ++iDir )
1414 if ( &_lines[ iDir ][0] <= line && line <= &_lines[ iDir ].back() )
1416 index = line - &_lines[ iDir ][0];
1421 //=============================================================================
1423 * Creates GridLine's of the grid
1425 void Grid::SetCoordinates(const vector<double>& xCoords,
1426 const vector<double>& yCoords,
1427 const vector<double>& zCoords,
1428 const double* axesDirs,
1429 const Bnd_Box& shapeBox)
1431 _coords[0] = xCoords;
1432 _coords[1] = yCoords;
1433 _coords[2] = zCoords;
1435 _axes[0].SetCoord( axesDirs[0],
1438 _axes[1].SetCoord( axesDirs[3],
1441 _axes[2].SetCoord( axesDirs[6],
1444 _axes[0].Normalize();
1445 _axes[1].Normalize();
1446 _axes[2].Normalize();
1448 _invB.SetCols( _axes[0], _axes[1], _axes[2] );
1451 // compute tolerance
1452 _minCellSize = Precision::Infinite();
1453 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1455 for ( size_t i = 1; i < _coords[ iDir ].size(); ++i )
1457 double cellLen = _coords[ iDir ][ i ] - _coords[ iDir ][ i-1 ];
1458 if ( cellLen < _minCellSize )
1459 _minCellSize = cellLen;
1462 if ( _minCellSize < Precision::Confusion() )
1463 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1464 SMESH_Comment("Too small cell size: ") << _minCellSize );
1465 _tol = _minCellSize / 1000.;
1467 // attune grid extremities to shape bounding box
1469 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
1470 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
1471 double* cP[6] = { &_coords[0].front(), &_coords[1].front(), &_coords[2].front(),
1472 &_coords[0].back(), &_coords[1].back(), &_coords[2].back() };
1473 for ( int i = 0; i < 6; ++i )
1474 if ( fabs( sP[i] - *cP[i] ) < _tol )
1475 *cP[i] = sP[i];// + _tol/1000. * ( i < 3 ? +1 : -1 );
1477 for ( int iDir = 0; iDir < 3; ++iDir )
1479 if ( _coords[iDir][0] - sP[iDir] > _tol )
1481 _minCellSize = Min( _minCellSize, _coords[iDir][0] - sP[iDir] );
1482 _coords[iDir].insert( _coords[iDir].begin(), sP[iDir] + _tol/1000.);
1484 if ( sP[iDir+3] - _coords[iDir].back() > _tol )
1486 _minCellSize = Min( _minCellSize, sP[iDir+3] - _coords[iDir].back() );
1487 _coords[iDir].push_back( sP[iDir+3] - _tol/1000.);
1490 _tol = _minCellSize / 1000.;
1492 _origin = ( _coords[0][0] * _axes[0] +
1493 _coords[1][0] * _axes[1] +
1494 _coords[2][0] * _axes[2] );
1497 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1499 LineIndexer li = GetLineIndexer( iDir );
1500 _lines[iDir].resize( li.NbLines() );
1501 double len = _coords[ iDir ].back() - _coords[iDir].front();
1502 for ( ; li.More(); ++li )
1504 GridLine& gl = _lines[iDir][ li.LineIndex() ];
1505 gl._line.SetLocation( _coords[0][li.I()] * _axes[0] +
1506 _coords[1][li.J()] * _axes[1] +
1507 _coords[2][li.K()] * _axes[2] );
1508 gl._line.SetDirection( _axes[ iDir ]);
1513 //================================================================================
1515 * Return local ID of shape
1517 TGeomID Grid::ShapeID( const TopoDS_Shape& s ) const
1519 return _helper->GetMeshDS()->ShapeToIndex( s );
1521 //================================================================================
1523 * Return a shape by its local ID
1525 const TopoDS_Shape& Grid::Shape( TGeomID id ) const
1527 return _helper->GetMeshDS()->IndexToShape( id );
1529 //================================================================================
1531 * Initialize _geometry
1533 void Grid::InitGeometry( const TopoDS_Shape& theShapeToMesh )
1535 SMESH_Mesh* mesh = _helper->GetMesh();
1537 _geometry._mainShape = theShapeToMesh;
1538 _geometry._extIntFaceID = mesh->GetMeshDS()->MaxShapeIndex() * 100;
1539 _geometry._soleSolid.SetID( 0 );
1540 _geometry._soleSolid.SetHasInternalFaces( false );
1542 InitClassifier( theShapeToMesh, TopAbs_VERTEX, _geometry._vertexClassifier );
1543 InitClassifier( theShapeToMesh, TopAbs_EDGE , _geometry._edgeClassifier );
1545 TopExp_Explorer solidExp( theShapeToMesh, TopAbs_SOLID );
1547 bool isSeveralSolids = false;
1548 if ( _toConsiderInternalFaces ) // check nb SOLIDs
1551 isSeveralSolids = solidExp.More();
1552 _toConsiderInternalFaces = isSeveralSolids;
1555 if ( !isSeveralSolids ) // look for an internal FACE
1557 TopExp_Explorer fExp( theShapeToMesh, TopAbs_FACE );
1558 for ( ; fExp.More() && !_toConsiderInternalFaces; fExp.Next() )
1559 _toConsiderInternalFaces = ( fExp.Current().Orientation() == TopAbs_INTERNAL );
1561 _geometry._soleSolid.SetHasInternalFaces( _toConsiderInternalFaces );
1562 _geometry._soleSolid.SetID( ShapeID( solidExp.Current() ));
1564 else // fill Geometry::_solidByID
1566 for ( ; solidExp.More(); solidExp.Next() )
1568 OneOfSolids & solid = _geometry._solidByID[ ShapeID( solidExp.Current() )];
1569 solid.Init( solidExp.Current(), TopAbs_FACE, mesh->GetMeshDS() );
1570 solid.Init( solidExp.Current(), TopAbs_EDGE, mesh->GetMeshDS() );
1571 solid.Init( solidExp.Current(), TopAbs_VERTEX, mesh->GetMeshDS() );
1577 _geometry._soleSolid.SetID( ShapeID( solidExp.Current() ));
1580 if ( !_toCreateFaces )
1582 int nbSolidsGlobal = _helper->Count( mesh->GetShapeToMesh(), TopAbs_SOLID, false );
1583 int nbSolidsLocal = _helper->Count( theShapeToMesh, TopAbs_SOLID, false );
1584 _toCreateFaces = ( nbSolidsLocal < nbSolidsGlobal );
1587 TopTools_IndexedMapOfShape faces;
1588 TopExp::MapShapes( theShapeToMesh, TopAbs_FACE, faces );
1590 // find boundary FACEs on boundary of mesh->ShapeToMesh()
1591 if ( _toCreateFaces )
1592 for ( int i = 1; i <= faces.Size(); ++i )
1593 if ( faces(i).Orientation() != TopAbs_INTERNAL &&
1594 _helper->NbAncestors( faces(i), *mesh, TopAbs_SOLID ) == 1 )
1596 _geometry._boundaryFaces.Add( ShapeID( faces(i) ));
1599 if ( isSeveralSolids )
1600 for ( int i = 1; i <= faces.Size(); ++i )
1602 SetSolidFather( faces(i), theShapeToMesh );
1603 for ( TopExp_Explorer eExp( faces(i), TopAbs_EDGE ); eExp.More(); eExp.Next() )
1605 const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
1606 SetSolidFather( edge, theShapeToMesh );
1607 SetSolidFather( _helper->IthVertex( 0, edge ), theShapeToMesh );
1608 SetSolidFather( _helper->IthVertex( 1, edge ), theShapeToMesh );
1612 // fill in _geometry._shape2NbNodes == find already meshed sub-shapes
1613 _geometry._shape2NbNodes.Clear();
1614 if ( mesh->NbNodes() > 0 )
1616 for ( TopAbs_ShapeEnum type : { TopAbs_FACE, TopAbs_EDGE, TopAbs_VERTEX })
1617 for ( TopExp_Explorer exp( theShapeToMesh, type ); exp.More(); exp.Next() )
1619 if ( _geometry._shape2NbNodes.IsBound( exp.Current() ))
1621 if ( SMESHDS_SubMesh* sm = mesh->GetMeshDS()->MeshElements( exp.Current() ))
1622 if ( sm->NbNodes() > 0 )
1623 _geometry._shape2NbNodes.Bind( exp.Current(), sm->NbNodes() );
1627 // fill in Solid::_concaveVertex
1628 vector< TGeomID > soleSolidID( 1, _geometry._soleSolid.ID() );
1629 for ( int i = 1; i <= faces.Size(); ++i )
1631 const TopoDS_Face& F = TopoDS::Face( faces( i ));
1633 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *mesh, 0, error,
1634 nullptr, nullptr, false );
1635 for ( StdMeshers_FaceSidePtr& wire : wires )
1637 const int nbEdges = wire->NbEdges();
1638 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wire->Edge(0)))
1640 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1642 if ( SMESH_Algo::isDegenerated( wire->Edge( iE1 ))) continue;
1643 int iE2 = ( iE1 + 1 ) % nbEdges;
1644 while ( SMESH_Algo::isDegenerated( wire->Edge( iE2 )))
1645 iE2 = ( iE2 + 1 ) % nbEdges;
1646 TopoDS_Vertex V = wire->FirstVertex( iE2 );
1647 double angle = _helper->GetAngle( wire->Edge( iE1 ),
1648 wire->Edge( iE2 ), F, V );
1649 if ( angle < -5. * M_PI / 180. )
1651 TGeomID faceID = ShapeID( F );
1652 const vector< TGeomID > & solids =
1653 _geometry.IsOneSolid() ? soleSolidID : GetSolidIDs( faceID );
1654 for ( const TGeomID & solidID : solids )
1656 Solid* solid = GetSolid( solidID );
1657 TGeomID V1 = ShapeID( wire->FirstVertex( iE1 ));
1658 TGeomID V2 = ShapeID( wire->LastVertex ( iE2 ));
1659 solid->SetConcave( ShapeID( V ), faceID,
1660 wire->EdgeID( iE1 ), wire->EdgeID( iE2 ), V1, V2 );
1669 //================================================================================
1671 * Store ID of SOLID as father of its child shape ID
1673 void Grid::SetSolidFather( const TopoDS_Shape& s, const TopoDS_Shape& theShapeToMesh )
1675 if ( _geometry._solidIDsByShapeID.empty() )
1676 _geometry._solidIDsByShapeID.resize( _helper->GetMeshDS()->MaxShapeIndex() + 1 );
1678 vector< TGeomID > & solidIDs = _geometry._solidIDsByShapeID[ ShapeID( s )];
1679 if ( !solidIDs.empty() )
1681 solidIDs.reserve(2);
1682 PShapeIteratorPtr solidIt = _helper->GetAncestors( s,
1683 *_helper->GetMesh(),
1686 while ( const TopoDS_Shape* solid = solidIt->next() )
1687 solidIDs.push_back( ShapeID( *solid ));
1689 //================================================================================
1691 * Return IDs of solids given sub-shape belongs to
1693 const vector< TGeomID > & Grid::GetSolidIDs( TGeomID subShapeID ) const
1695 return _geometry._solidIDsByShapeID[ subShapeID ];
1697 //================================================================================
1699 * Check if a sub-shape belongs to several SOLIDs
1701 bool Grid::IsShared( TGeomID shapeID ) const
1703 return !_geometry.IsOneSolid() && ( _geometry._solidIDsByShapeID[ shapeID ].size() > 1 );
1705 //================================================================================
1707 * Check if any of FACEs belongs to several SOLIDs
1709 bool Grid::IsAnyShared( const std::vector< TGeomID >& faceIDs ) const
1711 for ( size_t i = 0; i < faceIDs.size(); ++i )
1712 if ( IsShared( faceIDs[ i ]))
1716 //================================================================================
1718 * Return Solid by ID
1720 Solid* Grid::GetSolid( TGeomID solidID )
1722 if ( !solidID || _geometry.IsOneSolid() || _geometry._solidByID.empty() )
1723 return & _geometry._soleSolid;
1725 return & _geometry._solidByID[ solidID ];
1727 //================================================================================
1729 * Return OneOfSolids by ID
1731 Solid* Grid::GetOneOfSolids( TGeomID solidID )
1733 map< TGeomID, OneOfSolids >::iterator is2s = _geometry._solidByID.find( solidID );
1734 if ( is2s != _geometry._solidByID.end() )
1735 return & is2s->second;
1737 return & _geometry._soleSolid;
1739 //================================================================================
1741 * Check if transition on given FACE is correct for a given SOLID
1743 bool Grid::IsCorrectTransition( TGeomID faceID, const Solid* solid )
1745 if ( _geometry.IsOneSolid() )
1748 const vector< TGeomID >& solidIDs = _geometry._solidIDsByShapeID[ faceID ];
1749 return solidIDs[0] == solid->ID();
1752 //================================================================================
1754 * Assign to geometry a node at FACE intersection
1755 * Return a found supporting VERTEX
1757 void Grid::SetOnShape( const SMDS_MeshNode* n, const F_IntersectPoint& ip,
1758 TopoDS_Vertex* vertex, bool unset )
1761 SMESHDS_Mesh* mesh = _helper->GetMeshDS();
1762 if ( ip._faceIDs.size() == 1 )
1764 mesh->SetNodeOnFace( n, ip._faceIDs[0], ip._u, ip._v );
1766 else if ( _geometry._vertexClassifier.IsSatisfy( n, &s ))
1768 if ( unset ) mesh->UnSetNodeOnShape( n );
1769 mesh->SetNodeOnVertex( n, TopoDS::Vertex( s ));
1771 *vertex = TopoDS::Vertex( s );
1773 else if ( _geometry._edgeClassifier.IsSatisfy( n, &s ))
1775 if ( unset ) mesh->UnSetNodeOnShape( n );
1776 mesh->SetNodeOnEdge( n, TopoDS::Edge( s ));
1778 else if ( ip._faceIDs.size() > 0 )
1780 mesh->SetNodeOnFace( n, ip._faceIDs[0], ip._u, ip._v );
1782 else if ( !unset && _geometry.IsOneSolid() )
1784 mesh->SetNodeInVolume( n, _geometry._soleSolid.ID() );
1787 //================================================================================
1789 * Fill in B_IntersectPoint::_faceIDs with all FACEs sharing a VERTEX
1791 void Grid::UpdateFacesOfVertex( const B_IntersectPoint& ip, const TopoDS_Vertex& vertex )
1793 if ( vertex.IsNull() )
1795 std::vector< int > faceID(1);
1796 PShapeIteratorPtr fIt = _helper->GetAncestors( vertex, *_helper->GetMesh(),
1797 TopAbs_FACE, & _geometry._mainShape );
1798 while ( const TopoDS_Shape* face = fIt->next() )
1800 faceID[ 0 ] = ShapeID( *face );
1804 //================================================================================
1806 * Initialize a classifier
1808 void Grid::InitClassifier( const TopoDS_Shape& mainShape,
1809 TopAbs_ShapeEnum shapeType,
1810 Controls::ElementsOnShape& classifier )
1812 TopTools_IndexedMapOfShape shapes;
1813 TopExp::MapShapes( mainShape, shapeType, shapes );
1815 TopoDS_Compound compound; BRep_Builder builder;
1816 builder.MakeCompound( compound );
1817 for ( int i = 1; i <= shapes.Size(); ++i )
1818 builder.Add( compound, shapes(i) );
1820 classifier.SetMesh( _helper->GetMeshDS() );
1821 //classifier.SetTolerance( _tol ); // _tol is not initialised
1822 classifier.SetShape( compound, SMDSAbs_Node );
1825 //================================================================================
1827 * Return EDGEs with FACEs to implement into the mesh
1829 void Grid::GetEdgesToImplement( map< TGeomID, vector< TGeomID > > & edge2faceIDsMap,
1830 const TopoDS_Shape& shape,
1831 const vector< TopoDS_Shape >& faces )
1833 // check if there are strange EDGEs
1834 TopTools_IndexedMapOfShape faceMap;
1835 TopExp::MapShapes( _helper->GetMesh()->GetShapeToMesh(), TopAbs_FACE, faceMap );
1836 int nbFacesGlobal = faceMap.Size();
1837 faceMap.Clear( false );
1838 TopExp::MapShapes( shape, TopAbs_FACE, faceMap );
1839 int nbFacesLocal = faceMap.Size();
1840 bool hasStrangeEdges = ( nbFacesGlobal > nbFacesLocal );
1841 if ( !_toAddEdges && !hasStrangeEdges )
1842 return; // no FACEs in contact with those meshed by other algo
1844 for ( size_t i = 0; i < faces.size(); ++i )
1846 _helper->SetSubShape( faces[i] );
1847 for ( TopExp_Explorer eExp( faces[i], TopAbs_EDGE ); eExp.More(); eExp.Next() )
1849 const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
1850 if ( hasStrangeEdges )
1852 bool hasStrangeFace = false;
1853 PShapeIteratorPtr faceIt = _helper->GetAncestors( edge, *_helper->GetMesh(), TopAbs_FACE);
1854 while ( const TopoDS_Shape* face = faceIt->next() )
1855 if (( hasStrangeFace = !faceMap.Contains( *face )))
1857 if ( !hasStrangeFace && !_toAddEdges )
1859 _geometry._strangeEdges.Add( ShapeID( edge ));
1860 _geometry._strangeEdges.Add( ShapeID( _helper->IthVertex( 0, edge )));
1861 _geometry._strangeEdges.Add( ShapeID( _helper->IthVertex( 1, edge )));
1863 if ( !SMESH_Algo::isDegenerated( edge ) &&
1864 !_helper->IsRealSeam( edge ))
1866 edge2faceIDsMap[ ShapeID( edge )].push_back( ShapeID( faces[i] ));
1873 //================================================================================
1875 * Computes coordinates of a point in the grid CS
1877 void Grid::ComputeUVW(const gp_XYZ& P, double UVW[3])
1879 gp_XYZ p = P * _invB;
1880 p.Coord( UVW[0], UVW[1], UVW[2] );
1882 //================================================================================
1886 void Grid::ComputeNodes(SMESH_MesherHelper& helper)
1888 // state of each node of the grid relative to the geometry
1889 const size_t nbGridNodes = _coords[0].size() * _coords[1].size() * _coords[2].size();
1890 vector< TGeomID > shapeIDVec( nbGridNodes, theUndefID );
1891 _nodes.resize( nbGridNodes, 0 );
1892 _allBorderNodes.resize( nbGridNodes, 0 );
1893 _gridIntP.resize( nbGridNodes, NULL );
1895 SMESHDS_Mesh* mesh = helper.GetMeshDS();
1897 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1899 LineIndexer li = GetLineIndexer( iDir );
1901 // find out a shift of node index while walking along a GridLine in this direction
1902 li.SetIndexOnLine( 0 );
1903 size_t nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1904 li.SetIndexOnLine( 1 );
1905 const size_t nShift = NodeIndex( li.I(), li.J(), li.K() ) - nIndex0;
1907 const vector<double> & coords = _coords[ iDir ];
1908 for ( ; li.More(); ++li ) // loop on lines in iDir
1910 li.SetIndexOnLine( 0 );
1911 nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1913 GridLine& line = _lines[ iDir ][ li.LineIndex() ];
1914 const gp_XYZ lineLoc = line._line.Location().XYZ();
1915 const gp_XYZ lineDir = line._line.Direction().XYZ();
1917 line.RemoveExcessIntPoints( _tol );
1918 multiset< F_IntersectPoint >& intPnts = line._intPoints;
1919 multiset< F_IntersectPoint >::iterator ip = intPnts.begin();
1921 // Create mesh nodes at intersections with geometry
1922 // and set OUT state of nodes between intersections
1924 TGeomID solidID = 0;
1925 const double* nodeCoord = & coords[0];
1926 const double* coord0 = nodeCoord;
1927 const double* coordEnd = coord0 + coords.size();
1928 double nodeParam = 0;
1929 for ( ; ip != intPnts.end(); ++ip )
1931 solidID = line.GetSolidIDBefore( ip, solidID, _geometry );
1933 // set OUT state or just skip IN nodes before ip
1934 if ( nodeParam < ip->_paramOnLine - _tol )
1936 while ( nodeParam < ip->_paramOnLine - _tol )
1938 TGeomID & nodeShapeID = shapeIDVec[ nIndex0 + nShift * ( nodeCoord-coord0 ) ];
1939 nodeShapeID = Min( solidID, nodeShapeID );
1940 if ( ++nodeCoord < coordEnd )
1941 nodeParam = *nodeCoord - *coord0;
1945 if ( nodeCoord == coordEnd ) break;
1948 // create a mesh node on a GridLine at ip if it does not coincide with a grid node
1949 if ( nodeParam > ip->_paramOnLine + _tol )
1951 gp_XYZ xyz = lineLoc + ip->_paramOnLine * lineDir;
1952 ip->_node = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1953 ip->_indexOnLine = nodeCoord-coord0-1;
1955 SetOnShape( ip->_node, *ip, & v );
1956 UpdateFacesOfVertex( *ip, v );
1958 // create a mesh node at ip coincident with a grid node
1961 int nodeIndex = nIndex0 + nShift * ( nodeCoord-coord0 );
1962 if ( !_nodes[ nodeIndex ] )
1964 gp_XYZ xyz = lineLoc + nodeParam * lineDir;
1965 _nodes [ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1966 //_gridIntP[ nodeIndex ] = & * ip;
1967 //SetOnShape( _nodes[ nodeIndex ], *ip );
1969 if ( _gridIntP[ nodeIndex ] )
1970 _gridIntP[ nodeIndex ]->Add( ip->_faceIDs );
1972 _gridIntP[ nodeIndex ] = & * ip;
1973 // ip->_node = _nodes[ nodeIndex ]; -- to differ from ip on links
1974 ip->_indexOnLine = nodeCoord-coord0;
1975 if ( ++nodeCoord < coordEnd )
1976 nodeParam = *nodeCoord - *coord0;
1979 // set OUT state to nodes after the last ip
1980 for ( ; nodeCoord < coordEnd; ++nodeCoord )
1981 shapeIDVec[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = 0;
1985 // Create mesh nodes at !OUT nodes of the grid
1987 for ( size_t z = 0; z < _coords[2].size(); ++z )
1988 for ( size_t y = 0; y < _coords[1].size(); ++y )
1989 for ( size_t x = 0; x < _coords[0].size(); ++x )
1991 size_t nodeIndex = NodeIndex( x, y, z );
1992 if ( !_nodes[ nodeIndex ] &&
1993 0 < shapeIDVec[ nodeIndex ] && shapeIDVec[ nodeIndex ] < theUndefID )
1995 gp_XYZ xyz = ( _coords[0][x] * _axes[0] +
1996 _coords[1][y] * _axes[1] +
1997 _coords[2][z] * _axes[2] );
1998 _nodes[ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1999 mesh->SetNodeInVolume( _nodes[ nodeIndex ], shapeIDVec[ nodeIndex ]);
2001 else if ( _nodes[ nodeIndex ] && _gridIntP[ nodeIndex ] /*&&
2002 !_nodes[ nodeIndex]->GetShapeID()*/ )
2005 SetOnShape( _nodes[ nodeIndex ], *_gridIntP[ nodeIndex ], & v );
2006 UpdateFacesOfVertex( *_gridIntP[ nodeIndex ], v );
2008 else if ( _toUseQuanta && !_allBorderNodes[ nodeIndex ] /*add all nodes outside the body. Used to reconstruct the hexahedrals when polys are not desired!*/)
2010 gp_XYZ xyz = ( _coords[0][x] * _axes[0] +
2011 _coords[1][y] * _axes[1] +
2012 _coords[2][z] * _axes[2] );
2013 _allBorderNodes[ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
2014 mesh->SetNodeInVolume( _allBorderNodes[ nodeIndex ], shapeIDVec[ nodeIndex ]);
2019 // check validity of transitions
2020 const char* trName[] = { "TANGENT", "IN", "OUT", "APEX" };
2021 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
2023 LineIndexer li = GetLineIndexer( iDir );
2024 for ( ; li.More(); ++li )
2026 multiset< F_IntersectPoint >& intPnts = _lines[ iDir ][ li.LineIndex() ]._intPoints;
2027 if ( intPnts.empty() ) continue;
2028 if ( intPnts.size() == 1 )
2030 if ( intPnts.begin()->_transition != Trans_TANGENT &&
2031 intPnts.begin()->_transition != Trans_APEX )
2032 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
2033 SMESH_Comment("Wrong SOLE transition of GridLine (")
2034 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
2035 << ") along " << li._nameConst
2036 << ": " << trName[ intPnts.begin()->_transition] );
2040 if ( intPnts.begin()->_transition == Trans_OUT )
2041 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
2042 SMESH_Comment("Wrong START transition of GridLine (")
2043 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
2044 << ") along " << li._nameConst
2045 << ": " << trName[ intPnts.begin()->_transition ]);
2046 if ( intPnts.rbegin()->_transition == Trans_IN )
2047 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
2048 SMESH_Comment("Wrong END transition of GridLine (")
2049 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
2050 << ") along " << li._nameConst
2051 << ": " << trName[ intPnts.rbegin()->_transition ]);
2060 //=============================================================================
2062 * Intersects TopoDS_Face with all GridLine's
2064 void FaceGridIntersector::Intersect()
2066 FaceLineIntersector intersector;
2067 intersector._surfaceInt = GetCurveFaceIntersector();
2068 intersector._tol = _grid->_tol;
2069 intersector._transOut = _face.Orientation() == TopAbs_REVERSED ? Trans_IN : Trans_OUT;
2070 intersector._transIn = _face.Orientation() == TopAbs_REVERSED ? Trans_OUT : Trans_IN;
2072 typedef void (FaceLineIntersector::* PIntFun )(const GridLine& gridLine);
2073 PIntFun interFunction;
2075 bool isDirect = true;
2076 BRepAdaptor_Surface surf( _face );
2077 switch ( surf.GetType() ) {
2079 intersector._plane = surf.Plane();
2080 interFunction = &FaceLineIntersector::IntersectWithPlane;
2081 isDirect = intersector._plane.Direct();
2083 case GeomAbs_Cylinder:
2084 intersector._cylinder = surf.Cylinder();
2085 interFunction = &FaceLineIntersector::IntersectWithCylinder;
2086 isDirect = intersector._cylinder.Direct();
2089 intersector._cone = surf.Cone();
2090 interFunction = &FaceLineIntersector::IntersectWithCone;
2091 //isDirect = intersector._cone.Direct();
2093 case GeomAbs_Sphere:
2094 intersector._sphere = surf.Sphere();
2095 interFunction = &FaceLineIntersector::IntersectWithSphere;
2096 isDirect = intersector._sphere.Direct();
2099 intersector._torus = surf.Torus();
2100 interFunction = &FaceLineIntersector::IntersectWithTorus;
2101 //isDirect = intersector._torus.Direct();
2104 interFunction = &FaceLineIntersector::IntersectWithSurface;
2107 std::swap( intersector._transOut, intersector._transIn );
2109 _intersections.clear();
2110 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
2112 if ( surf.GetType() == GeomAbs_Plane )
2114 // check if all lines in this direction are parallel to a plane
2115 if ( intersector._plane.Axis().IsNormal( _grid->_lines[iDir][0]._line.Position(),
2116 Precision::Angular()))
2118 // find out a transition, that is the same for all lines of a direction
2119 gp_Dir plnNorm = intersector._plane.Axis().Direction();
2120 gp_Dir lineDir = _grid->_lines[iDir][0]._line.Direction();
2121 intersector._transition =
2122 ( plnNorm * lineDir < 0 ) ? intersector._transIn : intersector._transOut;
2124 if ( surf.GetType() == GeomAbs_Cylinder )
2126 // check if all lines in this direction are parallel to a cylinder
2127 if ( intersector._cylinder.Axis().IsParallel( _grid->_lines[iDir][0]._line.Position(),
2128 Precision::Angular()))
2132 // intersect the grid lines with the face
2133 for ( size_t iL = 0; iL < _grid->_lines[iDir].size(); ++iL )
2135 GridLine& gridLine = _grid->_lines[iDir][iL];
2136 if ( _bndBox.IsOut( gridLine._line )) continue;
2138 intersector._intPoints.clear();
2139 (intersector.*interFunction)( gridLine ); // <- intersection with gridLine
2140 for ( size_t i = 0; i < intersector._intPoints.size(); ++i )
2141 _intersections.push_back( make_pair( &gridLine, intersector._intPoints[i] ));
2145 if ( _face.Orientation() == TopAbs_INTERNAL )
2147 for ( size_t i = 0; i < _intersections.size(); ++i )
2148 if ( _intersections[i].second._transition == Trans_IN ||
2149 _intersections[i].second._transition == Trans_OUT )
2151 _intersections[i].second._transition = Trans_INTERNAL;
2156 //================================================================================
2158 * Return true if (_u,_v) is on the face
2160 bool FaceLineIntersector::UVIsOnFace() const
2162 TopAbs_State state = _surfaceInt->ClassifyUVPoint(gp_Pnt2d( _u,_v ));
2163 return ( state == TopAbs_IN || state == TopAbs_ON );
2165 //================================================================================
2167 * Store an intersection if it is IN or ON the face
2169 void FaceLineIntersector::addIntPoint(const bool toClassify)
2171 if ( !toClassify || UVIsOnFace() )
2174 p._paramOnLine = _w;
2177 p._transition = _transition;
2178 _intPoints.push_back( p );
2181 //================================================================================
2183 * Intersect a line with a plane
2185 void FaceLineIntersector::IntersectWithPlane(const GridLine& gridLine)
2187 IntAna_IntConicQuad linPlane( gridLine._line, _plane, Precision::Angular());
2188 _w = linPlane.ParamOnConic(1);
2189 if ( isParamOnLineOK( gridLine._length ))
2191 ElSLib::Parameters(_plane, linPlane.Point(1) ,_u,_v);
2195 //================================================================================
2197 * Intersect a line with a cylinder
2199 void FaceLineIntersector::IntersectWithCylinder(const GridLine& gridLine)
2201 IntAna_IntConicQuad linCylinder( gridLine._line, _cylinder );
2202 if ( linCylinder.IsDone() && linCylinder.NbPoints() > 0 )
2204 _w = linCylinder.ParamOnConic(1);
2205 if ( linCylinder.NbPoints() == 1 )
2206 _transition = Trans_TANGENT;
2208 _transition = _w < linCylinder.ParamOnConic(2) ? _transIn : _transOut;
2209 if ( isParamOnLineOK( gridLine._length ))
2211 ElSLib::Parameters(_cylinder, linCylinder.Point(1) ,_u,_v);
2214 if ( linCylinder.NbPoints() > 1 )
2216 _w = linCylinder.ParamOnConic(2);
2217 if ( isParamOnLineOK( gridLine._length ))
2219 ElSLib::Parameters(_cylinder, linCylinder.Point(2) ,_u,_v);
2220 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
2226 //================================================================================
2228 * Intersect a line with a cone
2230 void FaceLineIntersector::IntersectWithCone (const GridLine& gridLine)
2232 IntAna_IntConicQuad linCone(gridLine._line,_cone);
2233 if ( !linCone.IsDone() ) return;
2235 gp_Vec du, dv, norm;
2236 for ( int i = 1; i <= linCone.NbPoints(); ++i )
2238 _w = linCone.ParamOnConic( i );
2239 if ( !isParamOnLineOK( gridLine._length )) continue;
2240 ElSLib::Parameters(_cone, linCone.Point(i) ,_u,_v);
2243 ElSLib::D1( _u, _v, _cone, P, du, dv );
2245 double normSize2 = norm.SquareMagnitude();
2246 if ( normSize2 > Precision::Angular() * Precision::Angular() )
2248 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
2249 cos /= sqrt( normSize2 );
2250 if ( cos < -Precision::Angular() )
2251 _transition = _transIn;
2252 else if ( cos > Precision::Angular() )
2253 _transition = _transOut;
2255 _transition = Trans_TANGENT;
2259 _transition = Trans_APEX;
2261 addIntPoint( /*toClassify=*/false);
2265 //================================================================================
2267 * Intersect a line with a sphere
2269 void FaceLineIntersector::IntersectWithSphere (const GridLine& gridLine)
2271 IntAna_IntConicQuad linSphere(gridLine._line,_sphere);
2272 if ( linSphere.IsDone() && linSphere.NbPoints() > 0 )
2274 _w = linSphere.ParamOnConic(1);
2275 if ( linSphere.NbPoints() == 1 )
2276 _transition = Trans_TANGENT;
2278 _transition = _w < linSphere.ParamOnConic(2) ? _transIn : _transOut;
2279 if ( isParamOnLineOK( gridLine._length ))
2281 ElSLib::Parameters(_sphere, linSphere.Point(1) ,_u,_v);
2284 if ( linSphere.NbPoints() > 1 )
2286 _w = linSphere.ParamOnConic(2);
2287 if ( isParamOnLineOK( gridLine._length ))
2289 ElSLib::Parameters(_sphere, linSphere.Point(2) ,_u,_v);
2290 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
2296 //================================================================================
2298 * Intersect a line with a torus
2300 void FaceLineIntersector::IntersectWithTorus (const GridLine& gridLine)
2302 IntAna_IntLinTorus linTorus(gridLine._line,_torus);
2303 if ( !linTorus.IsDone()) return;
2305 gp_Vec du, dv, norm;
2306 for ( int i = 1; i <= linTorus.NbPoints(); ++i )
2308 _w = linTorus.ParamOnLine( i );
2309 if ( !isParamOnLineOK( gridLine._length )) continue;
2310 linTorus.ParamOnTorus( i, _u,_v );
2313 ElSLib::D1( _u, _v, _torus, P, du, dv );
2315 double normSize = norm.Magnitude();
2316 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
2318 if ( cos < -Precision::Angular() )
2319 _transition = _transIn;
2320 else if ( cos > Precision::Angular() )
2321 _transition = _transOut;
2323 _transition = Trans_TANGENT;
2324 addIntPoint( /*toClassify=*/false);
2328 //================================================================================
2330 * Intersect a line with a non-analytical surface
2332 void FaceLineIntersector::IntersectWithSurface (const GridLine& gridLine)
2334 _surfaceInt->Perform( gridLine._line, 0.0, gridLine._length );
2335 if ( !_surfaceInt->IsDone() ) return;
2336 for ( int i = 1; i <= _surfaceInt->NbPnt(); ++i )
2338 _transition = Transition( _surfaceInt->Transition( i ) );
2339 _w = _surfaceInt->WParameter( i );
2340 addIntPoint(/*toClassify=*/false);
2343 //================================================================================
2345 * check if its face can be safely intersected in a thread
2347 bool FaceGridIntersector::IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const
2352 TopLoc_Location loc;
2353 Handle(Geom_Surface) surf = BRep_Tool::Surface( _face, loc );
2354 Handle(Geom_RectangularTrimmedSurface) ts =
2355 Handle(Geom_RectangularTrimmedSurface)::DownCast( surf );
2356 while( !ts.IsNull() ) {
2357 surf = ts->BasisSurface();
2358 ts = Handle(Geom_RectangularTrimmedSurface)::DownCast(surf);
2360 if ( surf->IsKind( STANDARD_TYPE(Geom_BSplineSurface )) ||
2361 surf->IsKind( STANDARD_TYPE(Geom_BezierSurface )))
2362 if ( !noSafeTShapes.insert( _face.TShape().get() ).second )
2366 TopExp_Explorer exp( _face, TopAbs_EDGE );
2367 for ( ; exp.More(); exp.Next() )
2369 bool edgeIsSafe = true;
2370 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
2373 Handle(Geom_Curve) c = BRep_Tool::Curve( e, loc, f, l);
2376 Handle(Geom_TrimmedCurve) tc = Handle(Geom_TrimmedCurve)::DownCast(c);
2377 while( !tc.IsNull() ) {
2378 c = tc->BasisCurve();
2379 tc = Handle(Geom_TrimmedCurve)::DownCast(c);
2381 if ( c->IsKind( STANDARD_TYPE(Geom_BSplineCurve )) ||
2382 c->IsKind( STANDARD_TYPE(Geom_BezierCurve )))
2389 Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( e, surf, loc, f, l);
2392 Handle(Geom2d_TrimmedCurve) tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
2393 while( !tc.IsNull() ) {
2394 c2 = tc->BasisCurve();
2395 tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
2397 if ( c2->IsKind( STANDARD_TYPE(Geom2d_BSplineCurve )) ||
2398 c2->IsKind( STANDARD_TYPE(Geom2d_BezierCurve )))
2402 if ( !edgeIsSafe && !noSafeTShapes.insert( e.TShape().get() ).second )
2407 //================================================================================
2409 * \brief Creates topology of the hexahedron
2411 Hexahedron::Hexahedron(Grid* grid)
2412 : _grid( grid ), _nbFaceIntNodes(0), _hasTooSmall( false )
2414 _polygons.reserve(100); // to avoid reallocation;
2416 //set nodes shift within grid->_nodes from the node 000
2417 size_t dx = _grid->NodeIndexDX();
2418 size_t dy = _grid->NodeIndexDY();
2419 size_t dz = _grid->NodeIndexDZ();
2421 size_t i100 = i000 + dx;
2422 size_t i010 = i000 + dy;
2423 size_t i110 = i010 + dx;
2424 size_t i001 = i000 + dz;
2425 size_t i101 = i100 + dz;
2426 size_t i011 = i010 + dz;
2427 size_t i111 = i110 + dz;
2428 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V000 )] = i000;
2429 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V100 )] = i100;
2430 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V010 )] = i010;
2431 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V110 )] = i110;
2432 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V001 )] = i001;
2433 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V101 )] = i101;
2434 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V011 )] = i011;
2435 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V111 )] = i111;
2437 vector< int > idVec;
2438 // set nodes to links
2439 for ( int linkID = SMESH_Block::ID_Ex00; linkID <= SMESH_Block::ID_E11z; ++linkID )
2441 SMESH_Block::GetEdgeVertexIDs( linkID, idVec );
2442 _Link& link = _hexLinks[ SMESH_Block::ShapeIndex( linkID )];
2443 link._nodes[0] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[0] )];
2444 link._nodes[1] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[1] )];
2447 // set links to faces
2448 int interlace[4] = { 0, 3, 1, 2 }; // to walk by links around a face: { u0, 1v, u1, 0v }
2449 for ( int faceID = SMESH_Block::ID_Fxy0; faceID <= SMESH_Block::ID_F1yz; ++faceID )
2451 _Face& quad = _hexQuads[ SMESH_Block::ShapeIndex( faceID )];
2452 quad._name = (SMESH_Block::TShapeID) faceID;
2454 SMESH_Block::GetFaceEdgesIDs( faceID, idVec );
2455 bool revFace = ( faceID == SMESH_Block::ID_Fxy0 ||
2456 faceID == SMESH_Block::ID_Fx1z ||
2457 faceID == SMESH_Block::ID_F0yz );
2458 quad._links.resize(4);
2459 vector<_OrientedLink>::iterator frwLinkIt = quad._links.begin();
2460 vector<_OrientedLink>::reverse_iterator revLinkIt = quad._links.rbegin();
2461 for ( int i = 0; i < 4; ++i )
2463 bool revLink = revFace;
2464 if ( i > 1 ) // reverse links u1 and v0
2466 _OrientedLink& link = revFace ? *revLinkIt++ : *frwLinkIt++;
2467 link = _OrientedLink( & _hexLinks[ SMESH_Block::ShapeIndex( idVec[interlace[i]] )],
2472 //================================================================================
2474 * \brief Copy constructor
2476 Hexahedron::Hexahedron( const Hexahedron& other, size_t i, size_t j, size_t k, int cellID )
2477 :_grid( other._grid ), _nbFaceIntNodes(0), _i( i ), _j( j ), _k( k ), _hasTooSmall( false )
2479 _polygons.reserve(100); // to avoid reallocation;
2482 for ( int i = 0; i < 12; ++i )
2484 const _Link& srcLink = other._hexLinks[ i ];
2485 _Link& tgtLink = this->_hexLinks[ i ];
2486 tgtLink._nodes[0] = _hexNodes + ( srcLink._nodes[0] - other._hexNodes );
2487 tgtLink._nodes[1] = _hexNodes + ( srcLink._nodes[1] - other._hexNodes );
2490 for ( int i = 0; i < 6; ++i )
2492 const _Face& srcQuad = other._hexQuads[ i ];
2493 _Face& tgtQuad = this->_hexQuads[ i ];
2494 tgtQuad._name = srcQuad._name;
2495 tgtQuad._links.resize(4);
2496 for ( int j = 0; j < 4; ++j )
2498 const _OrientedLink& srcLink = srcQuad._links[ j ];
2499 _OrientedLink& tgtLink = tgtQuad._links[ j ];
2500 tgtLink._reverse = srcLink._reverse;
2501 tgtLink._link = _hexLinks + ( srcLink._link - other._hexLinks );
2505 if (SALOME::VerbosityActivated())
2509 //================================================================================
2511 * \brief Return IDs of SOLIDs interfering with this Hexahedron
2513 size_t Hexahedron::getSolids( TGeomID ids[] )
2515 if ( _grid->_geometry.IsOneSolid() )
2517 ids[0] = _grid->GetSolid()->ID();
2520 // count intersection points belonging to each SOLID
2522 id2NbPoints.reserve( 3 );
2524 _origNodeInd = _grid->NodeIndex( _i,_j,_k );
2525 for ( int iN = 0; iN < 8; ++iN )
2527 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
2528 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
2530 if ( _hexNodes[iN]._intPoint ) // intersection with a FACE
2532 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2534 const vector< TGeomID > & solidIDs =
2535 _grid->GetSolidIDs( _hexNodes[iN]._intPoint->_faceIDs[iF] );
2536 for ( size_t i = 0; i < solidIDs.size(); ++i )
2537 insertAndIncrement( solidIDs[i], id2NbPoints );
2540 else if ( _hexNodes[iN]._node ) // node inside a SOLID
2542 insertAndIncrement( _hexNodes[iN]._node->GetShapeID(), id2NbPoints );
2546 for ( int iL = 0; iL < 12; ++iL )
2548 const _Link& link = _hexLinks[ iL ];
2549 for ( size_t iP = 0; iP < link._fIntPoints.size(); ++iP )
2551 for ( size_t iF = 0; iF < link._fIntPoints[iP]->_faceIDs.size(); ++iF )
2553 const vector< TGeomID > & solidIDs =
2554 _grid->GetSolidIDs( link._fIntPoints[iP]->_faceIDs[iF] );
2555 for ( size_t i = 0; i < solidIDs.size(); ++i )
2556 insertAndIncrement( solidIDs[i], id2NbPoints );
2561 for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
2563 const vector< TGeomID > & solidIDs = _grid->GetSolidIDs( _eIntPoints[iP]->_shapeID );
2564 for ( size_t i = 0; i < solidIDs.size(); ++i )
2565 insertAndIncrement( solidIDs[i], id2NbPoints );
2568 size_t nbSolids = 0;
2569 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2570 if ( id2nb->second >= 3 )
2571 ids[ nbSolids++ ] = id2nb->first;
2576 //================================================================================
2578 * \brief Count cuts by INTERNAL FACEs and set _Node::_isInternalFlags
2580 bool Hexahedron::isCutByInternalFace( IsInternalFlag & maxFlag )
2583 id2NbPoints.reserve( 3 );
2585 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2586 for ( size_t iF = 0; iF < _intNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2588 if ( _grid->IsInternal( _intNodes[iN]._intPoint->_faceIDs[iF]))
2589 insertAndIncrement( _intNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2591 for ( size_t iN = 0; iN < 8; ++iN )
2592 if ( _hexNodes[iN]._intPoint )
2593 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2595 if ( _grid->IsInternal( _hexNodes[iN]._intPoint->_faceIDs[iF]))
2596 insertAndIncrement( _hexNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2599 maxFlag = IS_NOT_INTERNAL;
2600 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2602 TGeomID intFace = id2nb->first;
2603 IsInternalFlag intFlag = ( id2nb->second >= 3 ? IS_CUT_BY_INTERNAL_FACE : IS_INTERNAL );
2604 if ( intFlag > maxFlag )
2607 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2608 if ( _intNodes[iN].IsOnFace( intFace ))
2609 _intNodes[iN].SetInternal( intFlag );
2611 for ( size_t iN = 0; iN < 8; ++iN )
2612 if ( _hexNodes[iN].IsOnFace( intFace ))
2613 _hexNodes[iN].SetInternal( intFlag );
2619 //================================================================================
2621 * \brief Return any FACE interfering with this Hexahedron
2623 TGeomID Hexahedron::getAnyFace() const
2626 id2NbPoints.reserve( 3 );
2628 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2629 for ( size_t iF = 0; iF < _intNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2630 insertAndIncrement( _intNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2632 for ( size_t iN = 0; iN < 8; ++iN )
2633 if ( _hexNodes[iN]._intPoint )
2634 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2635 insertAndIncrement( _hexNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2637 for ( unsigned int minNb = 3; minNb > 0; --minNb )
2638 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2639 if ( id2nb->second >= minNb )
2640 return id2nb->first;
2645 //================================================================================
2647 * \brief Initializes IJK by Hexahedron index
2649 void Hexahedron::setIJK( size_t iCell )
2651 size_t iNbCell = _grid->_coords[0].size() - 1;
2652 size_t jNbCell = _grid->_coords[1].size() - 1;
2653 _i = iCell % iNbCell;
2654 _j = ( iCell % ( iNbCell * jNbCell )) / iNbCell;
2655 _k = iCell / iNbCell / jNbCell;
2658 //================================================================================
2660 * \brief Initializes its data by given grid cell (countered from zero)
2662 void Hexahedron::init( size_t iCell )
2668 //================================================================================
2670 * \brief Initializes its data by given grid cell nodes and intersections
2672 void Hexahedron::init( size_t i, size_t j, size_t k, const Solid* solid )
2674 _i = i; _j = j; _k = k;
2676 bool isCompute = solid;
2678 solid = _grid->GetSolid();
2680 // set nodes of grid to nodes of the hexahedron and
2681 // count nodes at hexahedron corners located IN and ON geometry
2682 _nbCornerNodes = _nbBndNodes = 0;
2683 _origNodeInd = _grid->NodeIndex( i,j,k );
2684 for ( int iN = 0; iN < 8; ++iN )
2686 _hexNodes[iN]._isInternalFlags = 0;
2689 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
2690 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
2692 if ( _grid->_allBorderNodes[ _origNodeInd + _grid->_nodeShift[iN] ] )
2693 _hexNodes[iN]._boundaryCornerNode = _grid->_allBorderNodes [ _origNodeInd + _grid->_nodeShift[iN] ];
2695 if ( _hexNodes[iN]._node && !solid->Contains( _hexNodes[iN]._node->GetShapeID() ))
2696 _hexNodes[iN]._node = 0;
2698 if ( _hexNodes[iN]._intPoint && !solid->ContainsAny( _hexNodes[iN]._intPoint->_faceIDs ))
2699 _hexNodes[iN]._intPoint = 0;
2701 _nbCornerNodes += bool( _hexNodes[iN]._node );
2702 _nbBndNodes += bool( _hexNodes[iN]._intPoint );
2704 _sideLength[0] = _grid->_coords[0][i+1] - _grid->_coords[0][i];
2705 _sideLength[1] = _grid->_coords[1][j+1] - _grid->_coords[1][j];
2706 _sideLength[2] = _grid->_coords[2][k+1] - _grid->_coords[2][k];
2714 if ( _nbFaceIntNodes + _eIntPoints.size() > 0 &&
2715 _nbFaceIntNodes + _eIntPoints.size() + _nbCornerNodes > 3)
2717 _intNodes.reserve( 3 * ( _nbBndNodes + _nbFaceIntNodes + _eIntPoints.size() ));
2719 // this method can be called in parallel, so use own helper
2720 SMESH_MesherHelper helper( *_grid->_helper->GetMesh() );
2722 // Create sub-links (_Link::_splits) by splitting links with _Link::_fIntPoints
2723 // ---------------------------------------------------------------
2725 for ( int iLink = 0; iLink < 12; ++iLink )
2727 _Link& link = _hexLinks[ iLink ];
2728 link._fIntNodes.clear();
2729 link._fIntNodes.reserve( link._fIntPoints.size() );
2730 for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
2731 if ( solid->ContainsAny( link._fIntPoints[i]->_faceIDs ))
2733 _intNodes.push_back( _Node( 0, link._fIntPoints[i] ));
2734 link._fIntNodes.push_back( & _intNodes.back() );
2737 link._splits.clear();
2738 split._nodes[ 0 ] = link._nodes[0];
2739 bool isOut = ( ! link._nodes[0]->Node() );
2740 bool checkTransition;
2741 for ( size_t i = 0; i < link._fIntNodes.size(); ++i )
2743 const bool isGridNode = ( ! link._fIntNodes[i]->Node() );
2744 if ( !isGridNode ) // intersection non-coincident with a grid node
2746 if ( split._nodes[ 0 ]->Node() && !isOut )
2748 split._nodes[ 1 ] = link._fIntNodes[i];
2749 link._splits.push_back( split );
2751 split._nodes[ 0 ] = link._fIntNodes[i];
2752 checkTransition = true;
2754 else // FACE intersection coincident with a grid node (at link ends)
2756 checkTransition = ( i == 0 && link._nodes[0]->Node() );
2758 if ( checkTransition )
2760 const vector< TGeomID >& faceIDs = link._fIntNodes[i]->_intPoint->_faceIDs;
2761 if ( _grid->IsInternal( faceIDs.back() ))
2763 else if ( faceIDs.size() > 1 || _eIntPoints.size() > 0 )
2764 isOut = isOutPoint( link, i, helper, solid );
2767 bool okTransi = _grid->IsCorrectTransition( faceIDs[0], solid );
2768 switch ( link._fIntNodes[i]->FaceIntPnt()->_transition ) {
2769 case Trans_OUT: isOut = okTransi; break;
2770 case Trans_IN : isOut = !okTransi; break;
2772 isOut = isOutPoint( link, i, helper, solid );
2777 if ( link._nodes[ 1 ]->Node() && split._nodes[ 0 ]->Node() && !isOut )
2779 split._nodes[ 1 ] = link._nodes[1];
2780 link._splits.push_back( split );
2784 // Create _Node's at intersections with EDGEs.
2785 // --------------------------------------------
2786 // 1) add this->_eIntPoints to _Face::_eIntNodes
2787 // 2) fill _intNodes and _vIntNodes
2789 const double tol2 = _grid->_tol * _grid->_tol * 4;
2790 int facets[3], nbFacets, subEntity;
2792 for ( int iF = 0; iF < 6; ++iF )
2793 _hexQuads[ iF ]._eIntNodes.clear();
2795 for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
2797 if ( !solid->ContainsAny( _eIntPoints[iP]->_faceIDs ))
2799 nbFacets = getEntity( _eIntPoints[iP], facets, subEntity );
2800 _Node* equalNode = 0;
2801 switch( nbFacets ) {
2802 case 1: // in a _Face
2804 _Face& quad = _hexQuads[ facets[0] - SMESH_Block::ID_FirstF ];
2805 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2807 equalNode->Add( _eIntPoints[ iP ] );
2810 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2811 quad._eIntNodes.push_back( & _intNodes.back() );
2815 case 2: // on a _Link
2817 _Link& link = _hexLinks[ subEntity - SMESH_Block::ID_FirstE ];
2818 if ( link._splits.size() > 0 )
2820 equalNode = findEqualNode( link._fIntNodes, _eIntPoints[ iP ], tol2 );
2822 equalNode->Add( _eIntPoints[ iP ] );
2823 else if ( link._splits.size() == 1 &&
2824 link._splits[0]._nodes[0] &&
2825 link._splits[0]._nodes[1] )
2826 link._splits.clear(); // hex edge is divided by _eIntPoints[iP]
2831 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2832 bool newNodeUsed = false;
2833 for ( int iF = 0; iF < 2; ++iF )
2835 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
2836 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2838 equalNode->Add( _eIntPoints[ iP ] );
2841 quad._eIntNodes.push_back( & _intNodes.back() );
2846 _intNodes.pop_back();
2850 case 3: // at a corner
2852 _Node& node = _hexNodes[ subEntity - SMESH_Block::ID_FirstV ];
2855 if ( node._intPoint )
2856 node._intPoint->Add( _eIntPoints[ iP ]->_faceIDs, _eIntPoints[ iP ]->_node );
2860 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2861 for ( int iF = 0; iF < 3; ++iF )
2863 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
2864 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2866 equalNode->Add( _eIntPoints[ iP ] );
2869 quad._eIntNodes.push_back( & _intNodes.back() );
2875 } // switch( nbFacets )
2877 if ( nbFacets == 0 ||
2878 _grid->ShapeType( _eIntPoints[ iP ]->_shapeID ) == TopAbs_VERTEX )
2880 equalNode = findEqualNode( _vIntNodes, _eIntPoints[ iP ], tol2 );
2882 equalNode->Add( _eIntPoints[ iP ] );
2884 else if ( nbFacets == 0 ) {
2885 if ( _intNodes.empty() || _intNodes.back().EdgeIntPnt() != _eIntPoints[ iP ])
2886 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2887 _vIntNodes.push_back( & _intNodes.back() );
2890 } // loop on _eIntPoints
2893 else if (( 3 < _nbCornerNodes && _nbCornerNodes < 8 ) || // _nbFaceIntNodes == 0
2894 ( !_grid->_geometry.IsOneSolid() ))
2897 // create sub-links (_splits) of whole links
2898 for ( int iLink = 0; iLink < 12; ++iLink )
2900 _Link& link = _hexLinks[ iLink ];
2901 link._splits.clear();
2902 if ( link._nodes[ 0 ]->Node() && link._nodes[ 1 ]->Node() )
2904 split._nodes[ 0 ] = link._nodes[0];
2905 split._nodes[ 1 ] = link._nodes[1];
2906 link._splits.push_back( split );
2912 } // init( _i, _j, _k )
2914 //================================================================================
2916 * \brief Compute mesh volumes resulted from intersection of the Hexahedron
2918 void Hexahedron::computeElements( const Solid* solid, int solidIndex )
2922 solid = _grid->GetSolid();
2923 if ( !_grid->_geometry.IsOneSolid() )
2925 TGeomID solidIDs[20] = { 0 };
2926 size_t nbSolids = getSolids( solidIDs );
2929 for ( size_t i = 0; i < nbSolids; ++i )
2931 solid = _grid->GetSolid( solidIDs[i] );
2932 computeElements( solid, i );
2933 if ( !_volumeDefs._nodes.empty() && i < nbSolids - 1 )
2934 _volumeDefs.SetNext( new _volumeDef( _volumeDefs ));
2938 solid = _grid->GetSolid( solidIDs[0] );
2942 init( _i, _j, _k, solid ); // get nodes and intersections from grid nodes and split links
2944 int nbIntersections = _nbFaceIntNodes + _eIntPoints.size();
2945 if ( _nbCornerNodes + nbIntersections < 4 )
2948 if ( _nbBndNodes == _nbCornerNodes && nbIntersections == 0 && isInHole() )
2949 return; // cell is in a hole
2951 IsInternalFlag intFlag = IS_NOT_INTERNAL;
2952 if ( solid->HasInternalFaces() && this->isCutByInternalFace( intFlag ))
2954 for ( _SplitIterator it( _hexLinks ); it.More(); it.Next() )
2956 if ( compute( solid, intFlag ))
2957 _volumeDefs.SetNext( new _volumeDef( _volumeDefs ));
2962 if ( solidIndex >= 0 )
2963 intFlag = IS_CUT_BY_INTERNAL_FACE;
2965 compute( solid, intFlag );
2969 //================================================================================
2971 * \brief Compute mesh volumes resulted from intersection of the Hexahedron
2973 bool Hexahedron::compute( const Solid* solid, const IsInternalFlag intFlag )
2976 _polygons.reserve( 20 );
2978 for ( int iN = 0; iN < 8; ++iN )
2979 _hexNodes[iN]._usedInFace = 0;
2981 if ( intFlag & IS_CUT_BY_INTERNAL_FACE && !_grid->_toAddEdges ) // Issue #19913
2982 preventVolumesOverlapping();
2984 std::set< TGeomID > concaveFaces; // to avoid connecting nodes laying on them
2986 if ( solid->HasConcaveVertex() )
2988 for ( const E_IntersectPoint* ip : _eIntPoints )
2990 if ( const ConcaveFace* cf = solid->GetConcave( ip->_shapeID ))
2991 if ( this->hasEdgesAround( cf ))
2992 concaveFaces.insert( cf->_concaveFace );
2994 if ( concaveFaces.empty() || concaveFaces.size() * 3 < _eIntPoints.size() )
2995 for ( const _Node& hexNode: _hexNodes )
2997 if ( hexNode._node && hexNode._intPoint && hexNode._intPoint->_faceIDs.size() >= 3 )
2998 if ( const ConcaveFace* cf = solid->GetConcave( hexNode._node->GetShapeID() ))
2999 if ( this->hasEdgesAround( cf ))
3000 concaveFaces.insert( cf->_concaveFace );
3004 // Create polygons from quadrangles
3005 // --------------------------------
3007 vector< _OrientedLink > splits;
3008 vector<_Node*> chainNodes;
3009 _Face* coplanarPolyg;
3011 const bool hasEdgeIntersections = !_eIntPoints.empty();
3012 const bool toCheckSideDivision = isImplementEdges() || intFlag & IS_CUT_BY_INTERNAL_FACE;
3014 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
3016 _Face& quad = _hexQuads[ iF ] ;
3018 _polygons.resize( _polygons.size() + 1 );
3019 _Face* polygon = &_polygons.back();
3020 polygon->_polyLinks.reserve( 20 );
3021 polygon->_name = quad._name;
3024 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
3025 for ( size_t iS = 0; iS < quad._links[ iE ].NbResultLinks(); ++iS )
3026 splits.push_back( quad._links[ iE ].ResultLink( iS ));
3028 if ( splits.size() == 4 &&
3029 isQuadOnFace( iF )) // check if a quad on FACE is not split
3031 polygon->_links.swap( splits );
3032 continue; // goto the next quad
3035 // add splits of links to a polygon and add _polyLinks to make
3036 // polygon's boundary closed
3038 int nbSplits = splits.size();
3039 if (( nbSplits == 1 ) &&
3040 ( quad._eIntNodes.empty() ||
3041 splits[0].FirstNode()->IsLinked( splits[0].LastNode()->_intPoint )))
3042 //( quad._eIntNodes.empty() || _nbCornerNodes + nbIntersections > 6 ))
3045 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
3046 if ( quad._eIntNodes[ iP ]->IsUsedInFace( polygon ))
3047 quad._eIntNodes[ iP ]->_usedInFace = 0;
3049 size_t nbUsedEdgeNodes = 0;
3050 _Face* prevPolyg = 0; // polygon previously created from this quad
3052 while ( nbSplits > 0 )
3055 while ( !splits[ iS ] )
3058 if ( !polygon->_links.empty() )
3060 _polygons.resize( _polygons.size() + 1 );
3061 polygon = &_polygons.back();
3062 polygon->_polyLinks.reserve( 20 );
3063 polygon->_name = quad._name;
3065 polygon->_links.push_back( splits[ iS ] );
3066 splits[ iS++ ]._link = 0;
3069 _Node* nFirst = polygon->_links.back().FirstNode();
3070 _Node *n1,*n2 = polygon->_links.back().LastNode();
3071 for ( ; nFirst != n2 && iS < splits.size(); ++iS )
3073 _OrientedLink& split = splits[ iS ];
3074 if ( !split ) continue;
3076 n1 = split.FirstNode();
3079 (( n1->_intPoint->_faceIDs.size() > 1 && toCheckSideDivision ) ||
3080 ( n1->_isInternalFlags )))
3082 // n1 is at intersection with EDGE
3083 if ( findChainOnEdge( splits, polygon->_links.back(), split, concaveFaces,
3084 iS, quad, chainNodes ))
3086 for ( size_t i = 1; i < chainNodes.size(); ++i )
3087 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
3088 if ( chainNodes.back() != n1 ) // not a partial cut by INTERNAL FACE
3090 prevPolyg = polygon;
3091 n2 = chainNodes.back();
3096 else if ( n1 != n2 )
3098 // try to connect to intersections with EDGEs
3099 if ( quad._eIntNodes.size() > nbUsedEdgeNodes &&
3100 findChain( n2, n1, quad, chainNodes ))
3102 for ( size_t i = 1; i < chainNodes.size(); ++i )
3104 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i] );
3105 nbUsedEdgeNodes += ( chainNodes[i]->IsUsedInFace( polygon ));
3107 if ( chainNodes.back() != n1 )
3109 n2 = chainNodes.back();
3114 // try to connect to a split ending on the same FACE
3117 _OrientedLink foundSplit;
3118 for ( size_t i = iS; i < splits.size() && !foundSplit; ++i )
3119 if (( foundSplit = splits[ i ]) &&
3120 ( n2->IsLinked( foundSplit.FirstNode()->_intPoint )))
3126 foundSplit._link = 0;
3130 if ( n2 != foundSplit.FirstNode() )
3132 polygon->AddPolyLink( n2, foundSplit.FirstNode() );
3133 n2 = foundSplit.FirstNode();
3139 if ( n2->IsLinked( nFirst->_intPoint ))
3141 polygon->AddPolyLink( n2, n1, prevPolyg );
3144 } // if ( n1 != n2 )
3146 polygon->_links.push_back( split );
3149 n2 = polygon->_links.back().LastNode();
3153 if ( nFirst != n2 ) // close a polygon
3155 if ( !findChain( n2, nFirst, quad, chainNodes ))
3157 if ( !closePolygon( polygon, chainNodes ))
3158 if ( !isImplementEdges() )
3159 chainNodes.push_back( nFirst );
3161 for ( size_t i = 1; i < chainNodes.size(); ++i )
3163 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
3164 nbUsedEdgeNodes += bool( chainNodes[i]->IsUsedInFace( polygon ));
3168 if ( polygon->_links.size() < 3 && nbSplits > 0 )
3170 polygon->_polyLinks.clear();
3171 polygon->_links.clear();
3173 } // while ( nbSplits > 0 )
3175 if ( polygon->_links.size() < 3 )
3177 _polygons.pop_back();
3179 } // loop on 6 hexahedron sides
3181 // Create polygons closing holes in a polyhedron
3182 // ----------------------------------------------
3184 // clear _usedInFace
3185 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
3186 _intNodes[ iN ]._usedInFace = 0;
3188 // add polygons to their links and mark used nodes
3189 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3191 _Face& polygon = _polygons[ iP ];
3192 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3194 polygon._links[ iL ].AddFace( &polygon );
3195 polygon._links[ iL ].FirstNode()->_usedInFace = &polygon;
3199 vector< _OrientedLink* > freeLinks;
3200 freeLinks.reserve(20);
3201 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3203 _Face& polygon = _polygons[ iP ];
3204 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3205 if ( polygon._links[ iL ].NbFaces() < 2 )
3206 freeLinks.push_back( & polygon._links[ iL ]);
3208 int nbFreeLinks = freeLinks.size();
3209 if ( nbFreeLinks == 1 ) return false;
3211 // put not used intersection nodes to _vIntNodes
3212 int nbVertexNodes = 0; // nb not used vertex nodes
3214 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
3215 nbVertexNodes += ( !_vIntNodes[ iN ]->IsUsedInFace() );
3217 const double tol = 1e-3 * Min( Min( _sideLength[0], _sideLength[1] ), _sideLength[0] );
3218 for ( size_t iN = _nbFaceIntNodes; iN < _intNodes.size(); ++iN )
3220 if ( _intNodes[ iN ].IsUsedInFace() ) continue;
3221 if ( dynamic_cast< const F_IntersectPoint* >( _intNodes[ iN ]._intPoint )) continue;
3223 findEqualNode( _vIntNodes, _intNodes[ iN ].EdgeIntPnt(), tol*tol );
3226 _vIntNodes.push_back( &_intNodes[ iN ]);
3232 std::set<TGeomID> usedFaceIDs;
3233 std::vector< TGeomID > faces;
3234 TGeomID curFace = 0;
3235 const size_t nbQuadPolygons = _polygons.size();
3236 E_IntersectPoint ipTmp;
3237 std::map< TGeomID, std::vector< const B_IntersectPoint* > > tmpAddedFace; // face added to _intPoint
3239 // create polygons by making closed chains of free links
3240 size_t iPolygon = _polygons.size();
3241 while ( nbFreeLinks > 0 )
3243 if ( iPolygon == _polygons.size() )
3245 _polygons.resize( _polygons.size() + 1 );
3246 _polygons[ iPolygon ]._polyLinks.reserve( 20 );
3247 _polygons[ iPolygon ]._links.reserve( 20 );
3249 _Face& polygon = _polygons[ iPolygon ];
3251 _OrientedLink* curLink = 0;
3253 if (( !hasEdgeIntersections ) ||
3254 ( nbFreeLinks < 4 && nbVertexNodes == 0 ))
3256 // get a remaining link to start from
3257 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3258 if (( curLink = freeLinks[ iL ] ))
3259 freeLinks[ iL ] = 0;
3260 polygon._links.push_back( *curLink );
3264 // find all links connected to curLink
3265 curNode = curLink->FirstNode();
3267 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3268 if ( freeLinks[ iL ] && freeLinks[ iL ]->LastNode() == curNode )
3270 curLink = freeLinks[ iL ];
3271 freeLinks[ iL ] = 0;
3273 polygon._links.push_back( *curLink );
3275 } while ( curLink );
3277 else // there are intersections with EDGEs
3279 // get a remaining link to start from, one lying on minimal nb of FACEs
3281 typedef pair< TGeomID, int > TFaceOfLink;
3282 TFaceOfLink faceOfLink( -1, -1 );
3283 TFaceOfLink facesOfLink[3] = { faceOfLink, faceOfLink, faceOfLink };
3284 for ( size_t iL = 0; iL < freeLinks.size(); ++iL )
3285 if ( freeLinks[ iL ] )
3287 faces = freeLinks[ iL ]->GetNotUsedFace( usedFaceIDs );
3288 if ( faces.size() == 1 )
3290 faceOfLink = TFaceOfLink( faces[0], iL );
3291 if ( !freeLinks[ iL ]->HasEdgeNodes() )
3293 facesOfLink[0] = faceOfLink;
3295 else if ( facesOfLink[0].first < 0 )
3297 faceOfLink = TFaceOfLink(( faces.empty() ? -1 : faces[0]), iL );
3298 facesOfLink[ 1 + faces.empty() ] = faceOfLink;
3301 for ( int i = 0; faceOfLink.first < 0 && i < 3; ++i )
3302 faceOfLink = facesOfLink[i];
3304 if ( faceOfLink.first < 0 ) // all faces used
3306 for ( size_t iL = 0; iL < freeLinks.size() && faceOfLink.first < 1; ++iL )
3307 if (( curLink = freeLinks[ iL ]))
3310 curLink->FirstNode()->IsLinked( curLink->LastNode()->_intPoint );
3311 faceOfLink.second = iL;
3313 usedFaceIDs.clear();
3315 curFace = faceOfLink.first;
3316 curLink = freeLinks[ faceOfLink.second ];
3317 freeLinks[ faceOfLink.second ] = 0;
3319 usedFaceIDs.insert( curFace );
3320 polygon._links.push_back( *curLink );
3323 // find all links lying on a curFace
3326 // go forward from curLink
3327 curNode = curLink->LastNode();
3329 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3330 if ( freeLinks[ iL ] &&
3331 freeLinks[ iL ]->FirstNode() == curNode &&
3332 freeLinks[ iL ]->LastNode()->IsOnFace( curFace ))
3334 curLink = freeLinks[ iL ];
3335 freeLinks[ iL ] = 0;
3336 polygon._links.push_back( *curLink );
3339 } while ( curLink );
3341 std::reverse( polygon._links.begin(), polygon._links.end() );
3343 curLink = & polygon._links.back();
3346 // go backward from curLink
3347 curNode = curLink->FirstNode();
3349 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3350 if ( freeLinks[ iL ] &&
3351 freeLinks[ iL ]->LastNode() == curNode &&
3352 freeLinks[ iL ]->FirstNode()->IsOnFace( curFace ))
3354 curLink = freeLinks[ iL ];
3355 freeLinks[ iL ] = 0;
3356 polygon._links.push_back( *curLink );
3359 } while ( curLink );
3361 curNode = polygon._links.back().FirstNode();
3363 if ( polygon._links[0].LastNode() != curNode )
3365 if ( nbVertexNodes > 0 )
3367 // add links with _vIntNodes if not already used
3369 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
3370 if ( !_vIntNodes[ iN ]->IsUsedInFace() &&
3371 _vIntNodes[ iN ]->IsOnFace( curFace ))
3373 _vIntNodes[ iN ]->_usedInFace = &polygon;
3374 chainNodes.push_back( _vIntNodes[ iN ] );
3376 if ( chainNodes.size() > 1 &&
3377 curFace != _grid->PseudoIntExtFaceID() ) /////// TODO
3379 sortVertexNodes( chainNodes, curNode, curFace );
3381 for ( size_t i = 0; i < chainNodes.size(); ++i )
3383 polygon.AddPolyLink( chainNodes[ i ], curNode );
3384 curNode = chainNodes[ i ];
3385 freeLinks.push_back( &polygon._links.back() );
3388 nbVertexNodes -= chainNodes.size();
3390 // if ( polygon._links.size() > 1 )
3392 polygon.AddPolyLink( polygon._links[0].LastNode(), curNode );
3393 freeLinks.push_back( &polygon._links.back() );
3397 } // if there are intersections with EDGEs
3399 if ( polygon._links.size() < 2 ||
3400 polygon._links[0].LastNode() != polygon._links.back().FirstNode() )
3403 break; // closed polygon not found -> invalid polyhedron
3406 if ( polygon._links.size() == 2 )
3408 if ( freeLinks.back() == &polygon._links.back() )
3410 freeLinks.pop_back();
3413 if ( polygon._links.front().NbFaces() > 0 )
3414 polygon._links.back().AddFace( polygon._links.front()._link->_faces[0] );
3415 if ( polygon._links.back().NbFaces() > 0 )
3416 polygon._links.front().AddFace( polygon._links.back()._link->_faces[0] );
3418 if ( iPolygon == _polygons.size()-1 )
3419 _polygons.pop_back();
3421 else // polygon._links.size() >= 2
3423 // add polygon to its links
3424 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3426 polygon._links[ iL ].AddFace( &polygon );
3427 polygon._links[ iL ].Reverse();
3429 if ( /*hasEdgeIntersections &&*/ iPolygon == _polygons.size() - 1 )
3431 // check that a polygon does not lie on a hexa side
3433 for ( size_t iL = 0; iL < polygon._links.size() && !coplanarPolyg; ++iL )
3435 if ( polygon._links[ iL ].NbFaces() < 2 )
3436 continue; // it's a just added free link
3437 // look for a polygon made on a hexa side and sharing
3438 // two or more haxa links
3440 coplanarPolyg = polygon._links[ iL ]._link->_faces[0];
3441 for ( iL2 = iL + 1; iL2 < polygon._links.size(); ++iL2 )
3442 if ( polygon._links[ iL2 ]._link->_faces[0] == coplanarPolyg &&
3443 !coplanarPolyg->IsPolyLink( polygon._links[ iL ]) &&
3444 !coplanarPolyg->IsPolyLink( polygon._links[ iL2 ]) &&
3445 coplanarPolyg < & _polygons[ nbQuadPolygons ])
3447 if ( iL2 == polygon._links.size() )
3450 if ( coplanarPolyg ) // coplanar polygon found
3452 freeLinks.resize( freeLinks.size() - polygon._polyLinks.size() );
3453 nbFreeLinks -= polygon._polyLinks.size();
3455 // an E_IntersectPoint used to mark nodes of coplanarPolyg
3456 // as lying on curFace while they are not at intersection with geometry
3457 ipTmp._faceIDs.resize(1);
3458 ipTmp._faceIDs[0] = curFace;
3460 // fill freeLinks with links not shared by coplanarPolyg and polygon
3461 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3462 if ( polygon._links[ iL ]._link->_faces[1] &&
3463 polygon._links[ iL ]._link->_faces[0] != coplanarPolyg )
3465 _Face* p = polygon._links[ iL ]._link->_faces[0];
3466 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
3467 if ( p->_links[ iL2 ]._link == polygon._links[ iL ]._link )
3469 freeLinks.push_back( & p->_links[ iL2 ] );
3471 freeLinks.back()->RemoveFace( &polygon );
3475 for ( size_t iL = 0; iL < coplanarPolyg->_links.size(); ++iL )
3476 if ( coplanarPolyg->_links[ iL ]._link->_faces[1] &&
3477 coplanarPolyg->_links[ iL ]._link->_faces[1] != &polygon )
3479 _Face* p = coplanarPolyg->_links[ iL ]._link->_faces[0];
3480 if ( p == coplanarPolyg )
3481 p = coplanarPolyg->_links[ iL ]._link->_faces[1];
3482 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
3483 if ( p->_links[ iL2 ]._link == coplanarPolyg->_links[ iL ]._link )
3485 // set links of coplanarPolyg in place of used freeLinks
3486 // to re-create coplanarPolyg next
3488 for ( ; iL3 < freeLinks.size() && freeLinks[ iL3 ]; ++iL3 );
3489 if ( iL3 < freeLinks.size() )
3490 freeLinks[ iL3 ] = ( & p->_links[ iL2 ] );
3492 freeLinks.push_back( & p->_links[ iL2 ] );
3494 freeLinks[ iL3 ]->RemoveFace( coplanarPolyg );
3495 // mark nodes of coplanarPolyg as lying on curFace
3496 for ( int iN = 0; iN < 2; ++iN )
3498 _Node* n = freeLinks[ iL3 ]->_link->_nodes[ iN ];
3500 if ( n->_intPoint ) added = n->_intPoint->Add( ipTmp._faceIDs );
3501 else n->_intPoint = &ipTmp;
3503 tmpAddedFace[ ipTmp._faceIDs[0] ].push_back( n->_intPoint );
3508 // set coplanarPolyg to be re-created next
3509 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3510 if ( coplanarPolyg == & _polygons[ iP ] )
3513 _polygons[ iPolygon ]._links.clear();
3514 _polygons[ iPolygon ]._polyLinks.clear();
3517 _polygons.pop_back();
3518 usedFaceIDs.erase( curFace );
3520 } // if ( coplanarPolyg )
3521 } // if ( hasEdgeIntersections ) - search for coplanarPolyg
3523 iPolygon = _polygons.size();
3525 } // end of case ( polygon._links.size() > 2 )
3526 } // while ( nbFreeLinks > 0 )
3528 for ( auto & face_ip : tmpAddedFace )
3530 curFace = face_ip.first;
3531 for ( const B_IntersectPoint* ip : face_ip.second )
3533 auto it = std::find( ip->_faceIDs.begin(), ip->_faceIDs.end(), curFace );
3534 if ( it != ip->_faceIDs.end() )
3535 ip->_faceIDs.erase( it );
3539 if ( _polygons.size() < 3 )
3542 // check volume size
3544 _hasTooSmall = ! checkPolyhedronSize( intFlag & IS_CUT_BY_INTERNAL_FACE, volSize );
3546 for ( size_t i = 0; i < 8; ++i )
3547 if ( _hexNodes[ i ]._intPoint == &ipTmp )
3548 _hexNodes[ i ]._intPoint = 0;
3551 return false; // too small volume
3554 // Try to find out names of no-name polygons (issue # 19887)
3555 if ( _grid->IsToRemoveExcessEntities() && _polygons.back()._name == SMESH_Block::ID_NONE )
3558 0.5 * ( _grid->_coords[0][_i] + _grid->_coords[0][_i+1] ) * _grid->_axes[0] +
3559 0.5 * ( _grid->_coords[1][_j] + _grid->_coords[1][_j+1] ) * _grid->_axes[1] +
3560 0.5 * ( _grid->_coords[2][_k] + _grid->_coords[2][_k+1] ) * _grid->_axes[2];
3561 for ( size_t i = _polygons.size() - 1; _polygons[i]._name == SMESH_Block::ID_NONE; --i )
3563 _Face& face = _polygons[ i ];
3566 for ( size_t iL = 0; iL < face._links.size(); ++iL )
3568 _Node* n = face._links[ iL ].FirstNode();
3569 gp_XYZ p = SMESH_NodeXYZ( n->Node() );
3570 _grid->ComputeUVW( p, uvw.ChangeCoord().ChangeData() );
3573 gp_Pnt pMin = bb.CornerMin();
3574 if ( bb.IsXThin( _grid->_tol ))
3575 face._name = pMin.X() < uvwCenter.X() ? SMESH_Block::ID_F0yz : SMESH_Block::ID_F1yz;
3576 else if ( bb.IsYThin( _grid->_tol ))
3577 face._name = pMin.Y() < uvwCenter.Y() ? SMESH_Block::ID_Fx0z : SMESH_Block::ID_Fx1z;
3578 else if ( bb.IsZThin( _grid->_tol ))
3579 face._name = pMin.Z() < uvwCenter.Z() ? SMESH_Block::ID_Fxy0 : SMESH_Block::ID_Fxy1;
3583 _volumeDefs._nodes.clear();
3584 _volumeDefs._quantities.clear();
3585 _volumeDefs._names.clear();
3586 // create a classic cell if possible
3589 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
3590 nbPolygons += (_polygons[ iF ]._links.size() > 2 );
3592 //const int nbNodes = _nbCornerNodes + nbIntersections;
3594 for ( size_t i = 0; i < 8; ++i )
3595 nbNodes += _hexNodes[ i ].IsUsedInFace();
3596 for ( size_t i = 0; i < _intNodes.size(); ++i )
3597 nbNodes += _intNodes[ i ].IsUsedInFace();
3599 bool isClassicElem = false;
3600 if ( nbNodes == 8 && nbPolygons == 6 ) isClassicElem = addHexa();
3601 else if ( nbNodes == 4 && nbPolygons == 4 ) isClassicElem = addTetra();
3602 else if ( nbNodes == 6 && nbPolygons == 5 ) isClassicElem = addPenta();
3603 else if ( nbNodes == 5 && nbPolygons == 5 ) isClassicElem = addPyra ();
3604 if ( !isClassicElem )
3606 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
3608 const size_t nbLinks = _polygons[ iF ]._links.size();
3609 if ( nbLinks < 3 ) continue;
3610 _volumeDefs._quantities.push_back( nbLinks );
3611 _volumeDefs._names.push_back( _polygons[ iF ]._name );
3612 for ( size_t iL = 0; iL < nbLinks; ++iL )
3613 _volumeDefs._nodes.push_back( _polygons[ iF ]._links[ iL ].FirstNode() );
3616 _volumeDefs._solidID = solid->ID();
3617 _volumeDefs._size = volSize;
3619 return !_volumeDefs._nodes.empty();
3621 //================================================================================
3623 * \brief Create elements in the mesh
3625 int Hexahedron::MakeElements(SMESH_MesherHelper& helper,
3626 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
3628 SMESHDS_Mesh* mesh = helper.GetMeshDS();
3630 CellsAroundLink c( _grid, 0 );
3631 const size_t nbGridCells = c._nbCells[0] * c._nbCells[1] * c._nbCells[2];
3632 vector< Hexahedron* > allHexa( nbGridCells, 0 );
3635 // set intersection nodes from GridLine's to links of allHexa
3636 int i,j,k, cellIndex, iLink;
3637 for ( int iDir = 0; iDir < 3; ++iDir )
3639 // loop on GridLine's parallel to iDir
3640 LineIndexer lineInd = _grid->GetLineIndexer( iDir );
3641 CellsAroundLink fourCells( _grid, iDir );
3642 for ( ; lineInd.More(); ++lineInd )
3644 GridLine& line = _grid->_lines[ iDir ][ lineInd.LineIndex() ];
3645 multiset< F_IntersectPoint >::const_iterator ip = line._intPoints.begin();
3646 for ( ; ip != line._intPoints.end(); ++ip )
3648 // if ( !ip->_node ) continue; // intersection at a grid node
3649 lineInd.SetIndexOnLine( ip->_indexOnLine );
3650 fourCells.Init( lineInd.I(), lineInd.J(), lineInd.K() );
3651 for ( int iL = 0; iL < 4; ++iL ) // loop on 4 cells sharing a link
3653 if ( !fourCells.GetCell( iL, i,j,k, cellIndex, iLink ))
3655 Hexahedron *& hex = allHexa[ cellIndex ];
3658 hex = new Hexahedron( *this, i, j, k, cellIndex );
3661 hex->_hexLinks[iLink]._fIntPoints.push_back( &(*ip) );
3662 hex->_nbFaceIntNodes += bool( ip->_node );
3668 // implement geom edges into the mesh
3669 addEdges( helper, allHexa, edge2faceIDsMap );
3671 // add not split hexahedra to the mesh
3673 TGeomID solidIDs[20];
3674 vector< Hexahedron* > intHexa; intHexa.reserve( nbIntHex );
3675 vector< const SMDS_MeshElement* > boundaryVolumes; boundaryVolumes.reserve( nbIntHex * 1.1 );
3676 for ( size_t i = 0; i < allHexa.size(); ++i )
3678 // initialize this by not cut allHexa[ i ]
3679 Hexahedron * & hex = allHexa[ i ];
3680 if ( hex ) // split hexahedron
3682 intHexa.push_back( hex );
3683 if ( hex->_nbFaceIntNodes > 0 ||
3684 hex->_eIntPoints.size() > 0 ||
3685 hex->getSolids( solidIDs ) > 1 )
3686 continue; // treat intersected hex later in parallel
3687 this->init( hex->_i, hex->_j, hex->_k );
3691 this->init( i ); // == init(i,j,k)
3693 if (( _nbCornerNodes == 8 ) &&
3694 ( _nbBndNodes < _nbCornerNodes || !isInHole() ))
3696 // order of _hexNodes is defined by enum SMESH_Block::TShapeID
3697 SMDS_MeshElement* el =
3698 mesh->AddVolume( _hexNodes[0].Node(), _hexNodes[2].Node(),
3699 _hexNodes[3].Node(), _hexNodes[1].Node(),
3700 _hexNodes[4].Node(), _hexNodes[6].Node(),
3701 _hexNodes[7].Node(), _hexNodes[5].Node() );
3702 TGeomID solidID = 0;
3703 if ( _nbBndNodes < _nbCornerNodes )
3705 for ( int iN = 0; iN < 8 && !solidID; ++iN )
3706 if ( !_hexNodes[iN]._intPoint ) // no intersection
3707 solidID = _hexNodes[iN].Node()->GetShapeID();
3711 getSolids( solidIDs );
3712 solidID = solidIDs[0];
3714 mesh->SetMeshElementOnShape( el, solidID );
3718 if ( _grid->_toCreateFaces && _nbBndNodes >= 3 )
3720 boundaryVolumes.push_back( el );
3721 el->setIsMarked( true );
3724 else if ( _nbCornerNodes > 3 && !hex )
3726 // all intersections of hex with geometry are at grid nodes
3727 hex = new Hexahedron( *this, _i, _j, _k, i );
3728 intHexa.push_back( hex );
3732 // compute definitions of volumes resulted from hexadron intersection
3734 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, intHexa.size() ),
3735 ParallelHexahedron( intHexa ),
3736 tbb::simple_partitioner()); // computeElements() is called here
3738 for ( size_t i = 0; i < intHexa.size(); ++i )
3739 if ( Hexahedron * hex = intHexa[ i ] )
3740 hex->computeElements();
3743 // simplify polyhedrons
3744 if ( _grid->IsToRemoveExcessEntities() )
3746 for ( size_t i = 0; i < intHexa.size(); ++i )
3747 if ( Hexahedron * hex = intHexa[ i ] )
3748 hex->removeExcessSideDivision( allHexa );
3750 for ( size_t i = 0; i < intHexa.size(); ++i )
3751 if ( Hexahedron * hex = intHexa[ i ] )
3752 hex->removeExcessNodes( allHexa );
3756 for ( size_t i = 0; i < intHexa.size(); ++i )
3757 if ( Hexahedron * hex = intHexa[ i ] )
3758 nbAdded += hex->addVolumes( helper );
3760 // fill boundaryVolumes with volumes neighboring too small skipped volumes
3761 if ( _grid->_toCreateFaces )
3763 for ( size_t i = 0; i < intHexa.size(); ++i )
3764 if ( Hexahedron * hex = intHexa[ i ] )
3765 hex->getBoundaryElems( boundaryVolumes );
3768 // merge nodes on outer sub-shapes with pre-existing ones
3769 TopTools_DataMapIteratorOfDataMapOfShapeInteger s2nIt( _grid->_geometry._shape2NbNodes );
3770 for ( ; s2nIt.More(); s2nIt.Next() )
3771 if ( s2nIt.Value() > 0 )
3772 if ( SMESHDS_SubMesh* sm = mesh->MeshElements( s2nIt.Key() ))
3774 TIDSortedNodeSet smNodes( SMDS_MeshElement::iterator( sm->GetNodes() ),
3775 SMDS_MeshElement::iterator() );
3776 SMESH_MeshEditor::TListOfListOfNodes equalNodes;
3777 SMESH_MeshEditor editor( helper.GetMesh() );
3778 editor.FindCoincidentNodes( smNodes, 10 * _grid->_tol, equalNodes,
3779 /*SeparateCornersAndMedium =*/ false);
3780 if ((int) equalNodes.size() <= s2nIt.Value() )
3781 editor.MergeNodes( equalNodes );
3784 // create boundary mesh faces
3785 addFaces( helper, boundaryVolumes );
3787 // create mesh edges
3788 addSegments( helper, edge2faceIDsMap );
3790 for ( size_t i = 0; i < allHexa.size(); ++i )
3792 delete allHexa[ i ];
3797 //================================================================================
3799 * \brief Implements geom edges into the mesh
3801 void Hexahedron::addEdges(SMESH_MesherHelper& helper,
3802 vector< Hexahedron* >& hexes,
3803 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
3805 if ( edge2faceIDsMap.empty() ) return;
3807 // Prepare planes for intersecting with EDGEs
3810 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ ) // iDirZ gives normal direction to planes
3812 GridPlanes& planes = pln[ iDirZ ];
3813 int iDirX = ( iDirZ + 1 ) % 3;
3814 int iDirY = ( iDirZ + 2 ) % 3;
3815 planes._zNorm = ( _grid->_axes[ iDirX ] ^ _grid->_axes[ iDirY ] ).Normalized();
3816 planes._zProjs.resize ( _grid->_coords[ iDirZ ].size() );
3817 planes._zProjs [0] = 0;
3818 const double zFactor = _grid->_axes[ iDirZ ] * planes._zNorm;
3819 const vector< double > & u = _grid->_coords[ iDirZ ];
3820 for ( size_t i = 1; i < planes._zProjs.size(); ++i )
3822 planes._zProjs [i] = zFactor * ( u[i] - u[0] );
3826 const double deflection = _grid->_minCellSize / 20.;
3827 const double tol = _grid->_tol;
3828 E_IntersectPoint ip;
3830 TColStd_MapOfInteger intEdgeIDs; // IDs of not shared INTERNAL EDGES
3832 // Intersect EDGEs with the planes
3833 map< TGeomID, vector< TGeomID > >::const_iterator e2fIt = edge2faceIDsMap.begin();
3834 for ( ; e2fIt != edge2faceIDsMap.end(); ++e2fIt )
3836 const TGeomID edgeID = e2fIt->first;
3837 const TopoDS_Edge & E = TopoDS::Edge( _grid->Shape( edgeID ));
3838 BRepAdaptor_Curve curve( E );
3839 TopoDS_Vertex v1 = helper.IthVertex( 0, E, false );
3840 TopoDS_Vertex v2 = helper.IthVertex( 1, E, false );
3842 ip._faceIDs = e2fIt->second;
3843 ip._shapeID = edgeID;
3845 bool isInternal = ( ip._faceIDs.size() == 1 && _grid->IsInternal( edgeID ));
3848 intEdgeIDs.Add( edgeID );
3849 intEdgeIDs.Add( _grid->ShapeID( v1 ));
3850 intEdgeIDs.Add( _grid->ShapeID( v2 ));
3853 // discretize the EDGE
3854 GCPnts_UniformDeflection discret( curve, deflection, true );
3855 if ( !discret.IsDone() || discret.NbPoints() < 2 )
3858 // perform intersection
3859 E_IntersectPoint* eip, *vip = 0;
3860 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ )
3862 GridPlanes& planes = pln[ iDirZ ];
3863 int iDirX = ( iDirZ + 1 ) % 3;
3864 int iDirY = ( iDirZ + 2 ) % 3;
3865 double xLen = _grid->_coords[ iDirX ].back() - _grid->_coords[ iDirX ][0];
3866 double yLen = _grid->_coords[ iDirY ].back() - _grid->_coords[ iDirY ][0];
3867 double zLen = _grid->_coords[ iDirZ ].back() - _grid->_coords[ iDirZ ][0];
3868 int dIJK[3], d000[3] = { 0,0,0 };
3869 double o[3] = { _grid->_coords[0][0],
3870 _grid->_coords[1][0],
3871 _grid->_coords[2][0] };
3873 // locate the 1st point of a segment within the grid
3874 gp_XYZ p1 = discret.Value( 1 ).XYZ();
3875 double u1 = discret.Parameter( 1 );
3876 double zProj1 = planes._zNorm * ( p1 - _grid->_origin );
3878 _grid->ComputeUVW( p1, ip._uvw );
3879 int iX1 = int(( ip._uvw[iDirX] - o[iDirX]) / xLen * (_grid->_coords[ iDirX ].size() - 1));
3880 int iY1 = int(( ip._uvw[iDirY] - o[iDirY]) / yLen * (_grid->_coords[ iDirY ].size() - 1));
3881 int iZ1 = int(( ip._uvw[iDirZ] - o[iDirZ]) / zLen * (_grid->_coords[ iDirZ ].size() - 1));
3882 locateValue( iX1, ip._uvw[iDirX], _grid->_coords[ iDirX ], dIJK[ iDirX ], tol );
3883 locateValue( iY1, ip._uvw[iDirY], _grid->_coords[ iDirY ], dIJK[ iDirY ], tol );
3884 locateValue( iZ1, ip._uvw[iDirZ], _grid->_coords[ iDirZ ], dIJK[ iDirZ ], tol );
3886 int ijk[3]; // grid index where a segment intersects a plane
3891 // add the 1st vertex point to a hexahedron
3895 ip._shapeID = _grid->ShapeID( v1 );
3896 vip = _grid->Add( ip );
3897 _grid->UpdateFacesOfVertex( *vip, v1 );
3899 vip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3900 if ( !addIntersection( vip, hexes, ijk, d000 ))
3901 _grid->Remove( vip );
3902 ip._shapeID = edgeID;
3904 for ( int iP = 2; iP <= discret.NbPoints(); ++iP )
3906 // locate the 2nd point of a segment within the grid
3907 gp_XYZ p2 = discret.Value( iP ).XYZ();
3908 double u2 = discret.Parameter( iP );
3909 double zProj2 = planes._zNorm * ( p2 - _grid->_origin );
3911 if ( Abs( zProj2 - zProj1 ) > std::numeric_limits<double>::min() )
3913 locateValue( iZ2, zProj2, planes._zProjs, dIJK[ iDirZ ], tol );
3915 // treat intersections with planes between 2 end points of a segment
3916 int dZ = ( iZ1 <= iZ2 ) ? +1 : -1;
3917 int iZ = iZ1 + ( iZ1 < iZ2 );
3918 for ( int i = 0, nb = Abs( iZ1 - iZ2 ); i < nb; ++i, iZ += dZ )
3920 ip._point = findIntPoint( u1, zProj1, u2, zProj2,
3921 planes._zProjs[ iZ ],
3922 curve, planes._zNorm, _grid->_origin );
3923 _grid->ComputeUVW( ip._point.XYZ(), ip._uvw );
3924 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
3925 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
3928 // add ip to hex "above" the plane
3929 eip = _grid->Add( ip );
3931 eip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3933 bool added = addIntersection( eip, hexes, ijk, dIJK);
3935 // add ip to hex "below" the plane
3936 ijk[ iDirZ ] = iZ-1;
3937 if ( !addIntersection( eip, hexes, ijk, dIJK ) &&
3939 _grid->Remove( eip );
3947 // add the 2nd vertex point to a hexahedron
3951 ip._shapeID = _grid->ShapeID( v2 );
3952 _grid->ComputeUVW( p1, ip._uvw );
3953 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
3954 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
3956 bool sameV = ( v1.IsSame( v2 ));
3959 vip = _grid->Add( ip );
3960 _grid->UpdateFacesOfVertex( *vip, v2 );
3962 vip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3964 if ( !addIntersection( vip, hexes, ijk, d000 ) && !sameV )
3965 _grid->Remove( vip );
3966 ip._shapeID = edgeID;
3968 } // loop on 3 grid directions
3972 if ( intEdgeIDs.Size() > 0 )
3973 cutByExtendedInternal( hexes, intEdgeIDs );
3978 //================================================================================
3980 * \brief Fully cut hexes that are partially cut by INTERNAL FACE.
3981 * Cut them by extended INTERNAL FACE.
3983 void Hexahedron::cutByExtendedInternal( std::vector< Hexahedron* >& hexes,
3984 const TColStd_MapOfInteger& intEdgeIDs )
3986 IntAna_IntConicQuad intersection;
3987 SMESHDS_Mesh* meshDS = _grid->_helper->GetMeshDS();
3988 const double tol2 = _grid->_tol * _grid->_tol;
3990 for ( size_t iH = 0; iH < hexes.size(); ++iH )
3992 Hexahedron* hex = hexes[ iH ];
3993 if ( !hex || hex->_eIntPoints.size() < 2 )
3995 if ( !intEdgeIDs.Contains( hex->_eIntPoints.back()->_shapeID ))
3998 // get 3 points on INTERNAL FACE to construct a cutting plane
3999 gp_Pnt p1 = hex->_eIntPoints[0]->_point;
4000 gp_Pnt p2 = hex->_eIntPoints[1]->_point;
4001 gp_Pnt p3 = hex->mostDistantInternalPnt( iH, p1, p2 );
4003 gp_Vec norm = gp_Vec( p1, p2 ) ^ gp_Vec( p1, p3 );
4006 pln = gp_Pln( p1, norm );
4013 TGeomID intFaceID = hex->_eIntPoints.back()->_faceIDs.front(); // FACE being "extended"
4014 TGeomID solidID = _grid->GetSolid( intFaceID )->ID();
4016 // cut links by the plane
4017 //bool isCut = false;
4018 for ( int iLink = 0; iLink < 12; ++iLink )
4020 _Link& link = hex->_hexLinks[ iLink ];
4021 if ( !link._fIntPoints.empty() )
4023 // if ( link._fIntPoints[0]->_faceIDs.back() == _grid->PseudoIntExtFaceID() )
4025 continue; // already cut link
4027 if ( !link._nodes[0]->Node() ||
4028 !link._nodes[1]->Node() )
4029 continue; // outside link
4031 if ( link._nodes[0]->IsOnFace( intFaceID ))
4033 if ( link._nodes[0]->_intPoint->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
4034 if ( p1.SquareDistance( link._nodes[0]->Point() ) < tol2 ||
4035 p2.SquareDistance( link._nodes[0]->Point() ) < tol2 )
4036 link._nodes[0]->_intPoint->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4037 continue; // link is cut by FACE being "extended"
4039 if ( link._nodes[1]->IsOnFace( intFaceID ))
4041 if ( link._nodes[1]->_intPoint->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
4042 if ( p1.SquareDistance( link._nodes[1]->Point() ) < tol2 ||
4043 p2.SquareDistance( link._nodes[1]->Point() ) < tol2 )
4044 link._nodes[1]->_intPoint->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4045 continue; // link is cut by FACE being "extended"
4047 gp_Pnt p4 = link._nodes[0]->Point();
4048 gp_Pnt p5 = link._nodes[1]->Point();
4049 gp_Lin line( p4, gp_Vec( p4, p5 ));
4051 intersection.Perform( line, pln );
4052 if ( !intersection.IsDone() ||
4053 intersection.IsInQuadric() ||
4054 intersection.IsParallel() ||
4055 intersection.NbPoints() < 1 )
4058 double u = intersection.ParamOnConic(1);
4059 if ( u + _grid->_tol < 0 )
4061 int iDir = iLink / 4;
4062 int index = (&hex->_i)[iDir];
4063 double linkLen = _grid->_coords[iDir][index+1] - _grid->_coords[iDir][index];
4064 if ( u - _grid->_tol > linkLen )
4067 if ( u < _grid->_tol ||
4068 u > linkLen - _grid->_tol ) // intersection at grid node
4070 int i = ! ( u < _grid->_tol ); // [0,1]
4071 int iN = link._nodes[ i ] - hex->_hexNodes; // [0-7]
4073 const F_IntersectPoint * & ip = _grid->_gridIntP[ hex->_origNodeInd +
4074 _grid->_nodeShift[iN] ];
4077 ip = _grid->_extIntPool.getNew();
4078 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4079 //ip->_transition = Trans_INTERNAL;
4081 else if ( ip->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
4083 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4085 hex->_nbFaceIntNodes++;
4090 const gp_Pnt& p = intersection.Point( 1 );
4091 F_IntersectPoint* ip = _grid->_extIntPool.getNew();
4092 ip->_node = meshDS->AddNode( p.X(), p.Y(), p.Z() );
4093 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4094 ip->_transition = Trans_INTERNAL;
4095 meshDS->SetNodeInVolume( ip->_node, solidID );
4097 CellsAroundLink fourCells( _grid, iDir );
4098 fourCells.Init( hex->_i, hex->_j, hex->_k, iLink );
4099 int i,j,k, cellIndex;
4100 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing the link
4102 if ( !fourCells.GetCell( iC, i,j,k, cellIndex, iLink ))
4104 Hexahedron * h = hexes[ cellIndex ];
4106 h = hexes[ cellIndex ] = new Hexahedron( *this, i, j, k, cellIndex );
4107 h->_hexLinks[iLink]._fIntPoints.push_back( ip );
4108 h->_nbFaceIntNodes++;
4115 // for ( size_t i = 0; i < hex->_eIntPoints.size(); ++i )
4117 // if ( _grid->IsInternal( hex->_eIntPoints[i]->_shapeID ) &&
4118 // ! hex->_eIntPoints[i]->IsOnFace( _grid->PseudoIntExtFaceID() ))
4119 // hex->_eIntPoints[i]->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4123 } // loop on all hexes
4127 //================================================================================
4129 * \brief Return intersection point on INTERNAL FACE most distant from given ones
4131 gp_Pnt Hexahedron::mostDistantInternalPnt( int hexIndex, const gp_Pnt& p1, const gp_Pnt& p2 )
4133 gp_Pnt resultPnt = p1;
4135 double maxDist2 = 0;
4136 for ( int iLink = 0; iLink < 12; ++iLink ) // check links
4138 _Link& link = _hexLinks[ iLink ];
4139 for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
4140 if ( _grid->PseudoIntExtFaceID() != link._fIntPoints[i]->_faceIDs[0] &&
4141 _grid->IsInternal( link._fIntPoints[i]->_faceIDs[0] ) &&
4142 link._fIntPoints[i]->_node )
4144 gp_Pnt p = SMESH_NodeXYZ( link._fIntPoints[i]->_node );
4145 double d = p1.SquareDistance( p );
4153 d = p2.SquareDistance( p );
4163 _origNodeInd = _grid->NodeIndex( _i,_j,_k );
4165 for ( size_t iN = 0; iN < 8; ++iN ) // check corners
4167 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
4168 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
4169 if ( _hexNodes[iN]._intPoint )
4170 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
4172 if ( _grid->IsInternal( _hexNodes[iN]._intPoint->_faceIDs[iF]))
4174 gp_Pnt p = SMESH_NodeXYZ( _hexNodes[iN]._node );
4175 double d = p1.SquareDistance( p );
4183 d = p2.SquareDistance( p );
4193 if ( maxDist2 < _grid->_tol * _grid->_tol )
4199 //================================================================================
4201 * \brief Finds intersection of a curve with a plane
4202 * \param [in] u1 - parameter of one curve point
4203 * \param [in] proj1 - projection of the curve point to the plane normal
4204 * \param [in] u2 - parameter of another curve point
4205 * \param [in] proj2 - projection of the other curve point to the plane normal
4206 * \param [in] proj - projection of a point where the curve intersects the plane
4207 * \param [in] curve - the curve
4208 * \param [in] axis - the plane normal
4209 * \param [in] origin - the plane origin
4210 * \return gp_Pnt - the found intersection point
4212 gp_Pnt Hexahedron::findIntPoint( double u1, double proj1,
4213 double u2, double proj2,
4215 BRepAdaptor_Curve& curve,
4217 const gp_XYZ& origin)
4219 double r = (( proj - proj1 ) / ( proj2 - proj1 ));
4220 double u = u1 * ( 1 - r ) + u2 * r;
4221 gp_Pnt p = curve.Value( u );
4222 double newProj = axis * ( p.XYZ() - origin );
4223 if ( Abs( proj - newProj ) > _grid->_tol / 10. )
4226 return findIntPoint( u2, proj2, u, newProj, proj, curve, axis, origin );
4228 return findIntPoint( u1, proj2, u, newProj, proj, curve, axis, origin );
4233 //================================================================================
4235 * \brief Returns indices of a hexahedron sub-entities holding a point
4236 * \param [in] ip - intersection point
4237 * \param [out] facets - 0-3 facets holding a point
4238 * \param [out] sub - index of a vertex or an edge holding a point
4239 * \return int - number of facets holding a point
4241 int Hexahedron::getEntity( const E_IntersectPoint* ip, int* facets, int& sub )
4243 enum { X = 1, Y = 2, Z = 4 }; // == 001, 010, 100
4245 int vertex = 0, edgeMask = 0;
4247 if ( Abs( _grid->_coords[0][ _i ] - ip->_uvw[0] ) < _grid->_tol ) {
4248 facets[ nbFacets++ ] = SMESH_Block::ID_F0yz;
4251 else if ( Abs( _grid->_coords[0][ _i+1 ] - ip->_uvw[0] ) < _grid->_tol ) {
4252 facets[ nbFacets++ ] = SMESH_Block::ID_F1yz;
4256 if ( Abs( _grid->_coords[1][ _j ] - ip->_uvw[1] ) < _grid->_tol ) {
4257 facets[ nbFacets++ ] = SMESH_Block::ID_Fx0z;
4260 else if ( Abs( _grid->_coords[1][ _j+1 ] - ip->_uvw[1] ) < _grid->_tol ) {
4261 facets[ nbFacets++ ] = SMESH_Block::ID_Fx1z;
4265 if ( Abs( _grid->_coords[2][ _k ] - ip->_uvw[2] ) < _grid->_tol ) {
4266 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy0;
4269 else if ( Abs( _grid->_coords[2][ _k+1 ] - ip->_uvw[2] ) < _grid->_tol ) {
4270 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy1;
4277 case 0: sub = 0; break;
4278 case 1: sub = facets[0]; break;
4280 const int edge [3][8] = {
4281 { SMESH_Block::ID_E00z, SMESH_Block::ID_E10z,
4282 SMESH_Block::ID_E01z, SMESH_Block::ID_E11z },
4283 { SMESH_Block::ID_E0y0, SMESH_Block::ID_E1y0, 0, 0,
4284 SMESH_Block::ID_E0y1, SMESH_Block::ID_E1y1 },
4285 { SMESH_Block::ID_Ex00, 0, SMESH_Block::ID_Ex10, 0,
4286 SMESH_Block::ID_Ex01, 0, SMESH_Block::ID_Ex11 }
4288 switch ( edgeMask ) {
4289 case X | Y: sub = edge[ 0 ][ vertex ]; break;
4290 case X | Z: sub = edge[ 1 ][ vertex ]; break;
4291 default: sub = edge[ 2 ][ vertex ];
4297 sub = vertex + SMESH_Block::ID_FirstV;
4302 //================================================================================
4304 * \brief Adds intersection with an EDGE
4306 bool Hexahedron::addIntersection( const E_IntersectPoint* ip,
4307 vector< Hexahedron* >& hexes,
4308 int ijk[], int dIJK[] )
4312 size_t hexIndex[4] = {
4313 _grid->CellIndex( ijk[0], ijk[1], ijk[2] ),
4314 dIJK[0] ? _grid->CellIndex( ijk[0]+dIJK[0], ijk[1], ijk[2] ) : -1,
4315 dIJK[1] ? _grid->CellIndex( ijk[0], ijk[1]+dIJK[1], ijk[2] ) : -1,
4316 dIJK[2] ? _grid->CellIndex( ijk[0], ijk[1], ijk[2]+dIJK[2] ) : -1
4318 for ( int i = 0; i < 4; ++i )
4320 if ( hexIndex[i] < hexes.size() && hexes[ hexIndex[i] ] )
4322 Hexahedron* h = hexes[ hexIndex[i] ];
4323 h->_eIntPoints.reserve(2);
4324 h->_eIntPoints.push_back( ip );
4327 // check if ip is really inside the hex
4328 if (SALOME::VerbosityActivated() && h->isOutParam( ip->_uvw ))
4329 throw SALOME_Exception("ip outside a hex");
4334 //================================================================================
4336 * \brief Check if a hexahedron facet lies on a FACE
4337 * Also return true if the facet does not interfere with any FACE
4339 bool Hexahedron::isQuadOnFace( const size_t iQuad )
4341 _Face& quad = _hexQuads[ iQuad ] ;
4343 int nbGridNodesInt = 0; // nb FACE intersections at grid nodes
4344 int nbNoGeomNodes = 0;
4345 for ( int iE = 0; iE < 4; ++iE )
4347 nbNoGeomNodes = ( !quad._links[ iE ].FirstNode()->_intPoint &&
4348 quad._links[ iE ].NbResultLinks() == 1 );
4350 ( quad._links[ iE ].FirstNode()->_intPoint &&
4351 quad._links[ iE ].NbResultLinks() == 1 &&
4352 quad._links[ iE ].ResultLink( 0 ).FirstNode() == quad._links[ iE ].FirstNode() &&
4353 quad._links[ iE ].ResultLink( 0 ).LastNode() == quad._links[ iE ].LastNode() );
4355 if ( nbNoGeomNodes == 4 )
4358 if ( nbGridNodesInt == 4 ) // all quad nodes are at FACE intersection
4360 size_t iEmin = 0, minNbFaces = 1000;
4361 for ( int iE = 0; iE < 4; ++iE ) // look for a node with min nb FACEs
4363 size_t nbFaces = quad._links[ iE ].FirstNode()->faces().size();
4364 if ( minNbFaces > nbFaces )
4367 minNbFaces = nbFaces;
4370 // check if there is a FACE passing through all 4 nodes
4371 for ( const TGeomID& faceID : quad._links[ iEmin ].FirstNode()->faces() )
4373 bool allNodesAtFace = true;
4374 for ( size_t iE = 0; iE < 4 && allNodesAtFace; ++iE )
4375 allNodesAtFace = ( iE == iEmin ||
4376 quad._links[ iE ].FirstNode()->IsOnFace( faceID ));
4377 if ( allNodesAtFace ) // quad if on faceID
4383 //================================================================================
4385 * \brief Finds nodes at a path from one node to another via intersections with EDGEs
4387 bool Hexahedron::findChain( _Node* n1,
4390 vector<_Node*>& chn )
4393 chn.push_back( n1 );
4394 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4395 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
4396 n1->IsLinked( quad._eIntNodes[ iP ]->_intPoint ) &&
4397 n2->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
4399 chn.push_back( quad._eIntNodes[ iP ]);
4400 chn.push_back( n2 );
4401 quad._eIntNodes[ iP ]->_usedInFace = &quad;
4408 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4409 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
4410 chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
4412 chn.push_back( quad._eIntNodes[ iP ]);
4413 found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
4416 } while ( found && ! chn.back()->IsLinked( n2->_intPoint ) );
4418 if ( chn.back() != n2 && chn.back()->IsLinked( n2->_intPoint ))
4419 chn.push_back( n2 );
4421 return chn.size() > 1;
4423 //================================================================================
4425 * \brief Try to heal a polygon whose ends are not connected
4427 bool Hexahedron::closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const
4429 int i = -1, nbLinks = polygon->_links.size();
4432 vector< _OrientedLink > newLinks;
4433 // find a node lying on the same FACE as the last one
4434 _Node* node = polygon->_links.back().LastNode();
4435 TGeomID avoidFace = node->IsLinked( polygon->_links.back().FirstNode()->_intPoint );
4436 for ( i = nbLinks - 2; i >= 0; --i )
4437 if ( node->IsLinked( polygon->_links[i].FirstNode()->_intPoint, avoidFace ))
4441 for ( ; i < nbLinks; ++i )
4442 newLinks.push_back( polygon->_links[i] );
4446 // find a node lying on the same FACE as the first one
4447 node = polygon->_links[0].FirstNode();
4448 avoidFace = node->IsLinked( polygon->_links[0].LastNode()->_intPoint );
4449 for ( i = 1; i < nbLinks; ++i )
4450 if ( node->IsLinked( polygon->_links[i].LastNode()->_intPoint, avoidFace ))
4453 for ( nbLinks = i + 1, i = 0; i < nbLinks; ++i )
4454 newLinks.push_back( polygon->_links[i] );
4456 if ( newLinks.size() > 1 )
4458 polygon->_links.swap( newLinks );
4460 chainNodes.push_back( polygon->_links.back().LastNode() );
4461 chainNodes.push_back( polygon->_links[0].FirstNode() );
4466 //================================================================================
4468 * \brief Finds nodes on the same EDGE as the first node of avoidSplit.
4470 * This function is for
4471 * 1) a case where an EDGE lies on a quad which lies on a FACE
4472 * so that a part of quad in ON and another part is IN
4473 * 2) INTERNAL FACE passes through the 1st node of avoidSplit
4475 bool Hexahedron::findChainOnEdge( const vector< _OrientedLink >& splits,
4476 const _OrientedLink& prevSplit,
4477 const _OrientedLink& avoidSplit,
4478 const std::set< TGeomID > & concaveFaces,
4481 vector<_Node*>& chn )
4483 _Node* pn1 = prevSplit.FirstNode();
4484 _Node* pn2 = prevSplit.LastNode(); // pn2 is on EDGE, if not on INTERNAL FACE
4485 _Node* an3 = avoidSplit.LastNode();
4486 TGeomID avoidFace = pn1->IsLinked( pn2->_intPoint ); // FACE under the quad
4487 if ( avoidFace < 1 && pn1->_intPoint )
4492 if ( !quad._eIntNodes.empty() ) // connect pn2 with EDGE intersections
4494 chn.push_back( pn2 );
4499 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4500 if (( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad )) &&
4501 ( chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint, avoidFace )) &&
4502 ( !avoidFace || quad._eIntNodes[ iP ]->IsOnFace( avoidFace )))
4504 chn.push_back( quad._eIntNodes[ iP ]);
4505 found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
4512 _Node* n = 0, *stopNode = avoidSplit.LastNode();
4514 if ( pn2 == prevSplit.LastNode() && // pn2 is at avoidSplit.FirstNode()
4515 !isCorner( stopNode )) // stopNode is in the middle of a _hexLinks
4517 // move stopNode to a _hexNodes
4518 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
4519 for ( size_t iL = 0; iL < quad._links[ iE ].NbResultLinks(); ++iL )
4521 const _Link* sideSplit = & quad._links[ iE ]._link->_splits[ iL ];
4522 if ( sideSplit == avoidSplit._link )
4524 if ( quad._links[ iE ].LastNode()->Node() )
4525 stopNode = quad._links[ iE ].LastNode();
4532 // connect pn2 (probably new, at _eIntNodes) with a split
4536 TGeomID commonFaces[20];
4537 _Node* nPrev = nullptr;
4538 for ( i = splits.size()-1; i >= 0; --i )
4544 for ( int is1st = 0; is1st < 2; ++is1st )
4546 _Node* nConn = is1st ? splits[i].FirstNode() : splits[i].LastNode();
4547 if ( nConn == nPrev )
4554 if (( stop = ( nConn == stopNode )))
4556 // find a FACE connecting nConn with pn2 but not with an3
4557 if (( nConn != pn1 ) &&
4558 ( nConn->_intPoint && !nConn->_intPoint->_faceIDs.empty() ) &&
4559 ( nbCommon = nConn->GetCommonFaces( pn2->_intPoint, commonFaces )))
4561 bool a3Coonect = true;
4562 for ( size_t iF = 0; iF < nbCommon && a3Coonect; ++iF )
4563 a3Coonect = an3->IsOnFace( commonFaces[ iF ]) || concaveFaces.count( commonFaces[ iF ]);
4572 if ( nbCommon > 1 ) // nConn is linked with pn2 by an EDGE
4588 if ( n && n != stopNode )
4591 chn.push_back( pn2 );
4596 else if ( !chn.empty() && chn.back()->_isInternalFlags )
4598 // INTERNAL FACE partially cuts the quad
4599 for ( int ip = chn.size() - 2; ip >= 0; --ip )
4600 chn.push_back( chn[ ip ]);
4605 //================================================================================
4607 * \brief Checks transition at the ginen intersection node of a link
4609 bool Hexahedron::isOutPoint( _Link& link, int iP,
4610 SMESH_MesherHelper& helper, const Solid* solid ) const
4614 if ( link._fIntNodes[iP]->faces().size() == 1 &&
4615 _grid->IsInternal( link._fIntNodes[iP]->face(0) ))
4618 const bool moreIntPoints = ( iP+1 < (int) link._fIntNodes.size() );
4621 _Node* n1 = link._fIntNodes[ iP ];
4623 n1 = link._nodes[0];
4624 _Node* n2 = moreIntPoints ? link._fIntNodes[ iP+1 ] : 0;
4625 if ( !n2 || !n2->Node() )
4626 n2 = link._nodes[1];
4630 // get all FACEs under n1 and n2
4631 set< TGeomID > faceIDs;
4632 if ( moreIntPoints ) faceIDs.insert( link._fIntNodes[iP+1]->faces().begin(),
4633 link._fIntNodes[iP+1]->faces().end() );
4634 if ( n2->_intPoint ) faceIDs.insert( n2->_intPoint->_faceIDs.begin(),
4635 n2->_intPoint->_faceIDs.end() );
4636 if ( faceIDs.empty() )
4637 return false; // n2 is inside
4638 if ( n1->_intPoint ) faceIDs.insert( n1->_intPoint->_faceIDs.begin(),
4639 n1->_intPoint->_faceIDs.end() );
4640 faceIDs.insert( link._fIntNodes[iP]->faces().begin(),
4641 link._fIntNodes[iP]->faces().end() );
4643 // get a point between 2 nodes
4644 gp_Pnt p1 = n1->Point();
4645 gp_Pnt p2 = n2->Point();
4646 gp_Pnt pOnLink = 0.8 * p1.XYZ() + 0.2 * p2.XYZ();
4648 TopLoc_Location loc;
4650 set< TGeomID >::iterator faceID = faceIDs.begin();
4651 for ( ; faceID != faceIDs.end(); ++faceID )
4653 // project pOnLink on a FACE
4654 if ( *faceID < 1 || !solid->Contains( *faceID )) continue;
4655 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( *faceID ));
4656 GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( face, loc, 0.1*_grid->_tol );
4657 gp_Pnt testPnt = pOnLink.Transformed( loc.Transformation().Inverted() );
4658 proj.Perform( testPnt );
4659 if ( proj.IsDone() && proj.NbPoints() > 0 )
4662 proj.LowerDistanceParameters( u,v );
4664 if ( proj.LowerDistance() <= 0.1 * _grid->_tol )
4670 // find isOut by normals
4672 if ( GeomLib::NormEstim( BRep_Tool::Surface( face, loc ),
4677 if ( solid->Orientation( face ) == TopAbs_REVERSED )
4679 gp_Vec v( proj.NearestPoint(), testPnt );
4680 isOut = ( v * normal > 0 );
4685 // classify a projection
4686 if ( !n1->IsOnFace( *faceID ) || !n2->IsOnFace( *faceID ))
4688 BRepTopAdaptor_FClass2d cls( face, Precision::Confusion() );
4689 TopAbs_State state = cls.Perform( gp_Pnt2d( u,v ));
4690 if ( state == TopAbs_OUT )
4702 //================================================================================
4704 * \brief Sort nodes on a FACE
4706 void Hexahedron::sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID faceID)
4708 if ( nodes.size() > 20 ) return;
4710 // get shapes under nodes
4711 TGeomID nShapeIds[20], *nShapeIdsEnd = &nShapeIds[0] + nodes.size();
4712 for ( size_t i = 0; i < nodes.size(); ++i )
4713 if ( !( nShapeIds[i] = nodes[i]->ShapeID() ))
4716 // get shapes of the FACE
4717 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( faceID ));
4718 list< TopoDS_Edge > edges;
4719 list< int > nbEdges;
4720 int nbW = SMESH_Block::GetOrderedEdges (face, edges, nbEdges);
4722 // select a WIRE - remove EDGEs of irrelevant WIREs from edges
4723 list< TopoDS_Edge >::iterator e = edges.begin(), eEnd = e;
4724 list< int >::iterator nE = nbEdges.begin();
4725 for ( ; nbW > 0; ++nE, --nbW )
4727 std::advance( eEnd, *nE );
4728 for ( ; e != eEnd; ++e )
4729 for ( int i = 0; i < 2; ++i )
4732 _grid->ShapeID( *e ) :
4733 _grid->ShapeID( SMESH_MesherHelper::IthVertex( 0, *e ));
4735 ( std::find( &nShapeIds[0], nShapeIdsEnd, id ) != nShapeIdsEnd ))
4737 edges.erase( eEnd, edges.end() ); // remove rest wires
4738 e = eEnd = edges.end();
4745 edges.erase( edges.begin(), eEnd ); // remove a current irrelevant wire
4748 // rotate edges to have the first one at least partially out of the hexa
4749 list< TopoDS_Edge >::iterator e = edges.begin(), eMidOut = edges.end();
4750 for ( ; e != edges.end(); ++e )
4752 if ( !_grid->ShapeID( *e ))
4757 for ( int i = 0; i < 2 && !isOut; ++i )
4761 TopoDS_Vertex v = SMESH_MesherHelper::IthVertex( 0, *e );
4762 p = BRep_Tool::Pnt( v );
4764 else if ( eMidOut == edges.end() )
4766 TopLoc_Location loc;
4767 Handle(Geom_Curve) c = BRep_Tool::Curve( *e, loc, f, l);
4768 if ( c.IsNull() ) break;
4769 p = c->Value( 0.5 * ( f + l )).Transformed( loc );
4776 _grid->ComputeUVW( p.XYZ(), uvw );
4777 if ( isOutParam( uvw ))
4788 if ( e != edges.end() )
4789 edges.splice( edges.end(), edges, edges.begin(), e );
4790 else if ( eMidOut != edges.end() )
4791 edges.splice( edges.end(), edges, edges.begin(), eMidOut );
4793 // sort nodes according to the order of edges
4794 _Node* orderNodes [20];
4795 //TGeomID orderShapeIDs[20];
4797 TGeomID id, *pID = 0;
4798 for ( e = edges.begin(); e != edges.end(); ++e )
4800 if (( id = _grid->ShapeID( SMESH_MesherHelper::IthVertex( 0, *e ))) &&
4801 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
4803 //orderShapeIDs[ nbN ] = id;
4804 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
4807 if (( id = _grid->ShapeID( *e )) &&
4808 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
4810 //orderShapeIDs[ nbN ] = id;
4811 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
4815 if ( nbN != nodes.size() )
4818 bool reverse = ( orderNodes[0 ]->Point().SquareDistance( curNode->Point() ) >
4819 orderNodes[nbN-1]->Point().SquareDistance( curNode->Point() ));
4821 for ( size_t i = 0; i < nodes.size(); ++i )
4822 nodes[ i ] = orderNodes[ reverse ? nbN-1-i : i ];
4825 //================================================================================
4827 * \brief Adds computed elements to the mesh
4829 int Hexahedron::addVolumes( SMESH_MesherHelper& helper )
4831 F_IntersectPoint noIntPnt;
4832 const bool toCheckNodePos = _grid->IsToCheckNodePos();
4833 const bool useQuanta = _grid->_toUseQuanta;
4836 // add elements resulted from hexahedron intersection
4837 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4839 vector< const SMDS_MeshNode* > nodes( volDef->_nodes.size() );
4840 for ( size_t iN = 0; iN < nodes.size(); ++iN )
4842 if ( !( nodes[iN] = volDef->_nodes[iN].Node() ))
4844 if ( const E_IntersectPoint* eip = volDef->_nodes[iN].EdgeIntPnt() )
4846 nodes[iN] = volDef->_nodes[iN]._intPoint->_node =
4847 helper.AddNode( eip->_point.X(),
4850 if ( _grid->ShapeType( eip->_shapeID ) == TopAbs_VERTEX )
4851 helper.GetMeshDS()->SetNodeOnVertex( nodes[iN], eip->_shapeID );
4853 helper.GetMeshDS()->SetNodeOnEdge( nodes[iN], eip->_shapeID );
4856 throw SALOME_Exception("Bug: no node at intersection point");
4858 else if ( volDef->_nodes[iN]._intPoint &&
4859 volDef->_nodes[iN]._intPoint->_node == volDef->_nodes[iN]._node )
4861 // Update position of node at EDGE intersection;
4862 // see comment to _Node::Add( E_IntersectPoint )
4863 SMESHDS_Mesh* mesh = helper.GetMeshDS();
4864 TGeomID shapeID = volDef->_nodes[iN].EdgeIntPnt()->_shapeID;
4865 mesh->UnSetNodeOnShape( nodes[iN] );
4866 if ( _grid->ShapeType( shapeID ) == TopAbs_VERTEX )
4867 mesh->SetNodeOnVertex( nodes[iN], shapeID );
4869 mesh->SetNodeOnEdge( nodes[iN], shapeID );
4871 else if ( toCheckNodePos &&
4872 !nodes[iN]->isMarked() &&
4873 _grid->ShapeType( nodes[iN]->GetShapeID() ) == TopAbs_FACE )
4875 _grid->SetOnShape( nodes[iN], noIntPnt, /*v=*/nullptr,/*unset=*/true );
4876 nodes[iN]->setIsMarked( true );
4878 } // loop to get nodes
4880 const SMDS_MeshElement* v = 0;
4881 if ( !volDef->_quantities.empty() )
4885 // split polyhedrons of with disjoint volumes
4886 std::vector<std::vector<int>> splitQuantities;
4887 std::vector<std::vector< const SMDS_MeshNode* > > splitNodes;
4888 if ( checkPolyhedronValidity( volDef, splitQuantities, splitNodes ) == 1 )
4889 v = addPolyhedronToMesh( volDef, helper, nodes, volDef->_quantities );
4893 for (size_t id = 0; id < splitQuantities.size(); id++)
4895 v = addPolyhedronToMesh( volDef, helper, splitNodes[ id ], splitQuantities[ id ] );
4896 if ( id < splitQuantities.size()-1 )
4897 volDef->_brotherVolume.push_back( v );
4905 const double quanta = _grid->_quanta;
4906 double polyVol = volDef->_size;
4907 double hexaVolume = _sideLength[0] * _sideLength[1] * _sideLength[2];
4908 if ( hexaVolume > 0.0 && polyVol/hexaVolume >= quanta /*set the volume if the relation is satisfied*/)
4909 v = helper.AddVolume( _hexNodes[0].BoundaryNode(), _hexNodes[2].BoundaryNode(),
4910 _hexNodes[3].BoundaryNode(), _hexNodes[1].BoundaryNode(),
4911 _hexNodes[4].BoundaryNode(), _hexNodes[6].BoundaryNode(),
4912 _hexNodes[7].BoundaryNode(), _hexNodes[5].BoundaryNode() );
4918 switch ( nodes.size() )
4920 case 8: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],
4921 nodes[4],nodes[5],nodes[6],nodes[7] );
4923 case 4: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3] );
4925 case 6: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4],nodes[5] );
4927 case 5: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4] );
4931 volDef->_volume = v;
4932 nbAdded += bool( v );
4934 } // loop on _volumeDefs chain
4936 // avoid creating overlapping volumes (bos #24052)
4939 double sumSize = 0, maxSize = 0;
4940 _volumeDef* maxSizeDef = nullptr;
4941 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4943 if ( !volDef->_volume )
4945 sumSize += volDef->_size;
4946 if ( volDef->_size > maxSize )
4948 maxSize = volDef->_size;
4949 maxSizeDef = volDef;
4952 if ( sumSize > _sideLength[0] * _sideLength[1] * _sideLength[2] * 1.05 )
4954 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4955 if ( volDef != maxSizeDef && volDef->_volume )
4957 helper.GetMeshDS()->RemoveFreeElement( volDef->_volume, /*sm=*/nullptr,
4958 /*fromGroups=*/false );
4959 volDef->_volume = nullptr;
4960 //volDef->_nodes.clear();
4966 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4968 if ( volDef->_volume )
4970 helper.GetMeshDS()->SetMeshElementOnShape( volDef->_volume, volDef->_solidID );
4971 for (auto broVol : volDef->_brotherVolume )
4973 helper.GetMeshDS()->SetMeshElementOnShape( broVol, volDef->_solidID );
4980 //================================================================================
4982 * \brief Return true if the element is in a hole
4983 * \remark consider a cell to be in a hole if all links in any direction
4984 * comes OUT of geometry
4986 bool Hexahedron::isInHole() const
4988 if ( !_vIntNodes.empty() )
4991 const size_t ijk[3] = { _i, _j, _k };
4992 F_IntersectPoint curIntPnt;
4994 // consider a cell to be in a hole if all links in any direction
4995 // comes OUT of geometry
4996 for ( int iDir = 0; iDir < 3; ++iDir )
4998 const vector<double>& coords = _grid->_coords[ iDir ];
4999 LineIndexer li = _grid->GetLineIndexer( iDir );
5000 li.SetIJK( _i,_j,_k );
5001 size_t lineIndex[4] = { li.LineIndex (),
5005 bool allLinksOut = true, hasLinks = false;
5006 for ( int iL = 0; iL < 4 && allLinksOut; ++iL ) // loop on 4 links parallel to iDir
5008 const _Link& link = _hexLinks[ iL + 4*iDir ];
5009 // check transition of the first node of a link
5010 const F_IntersectPoint* firstIntPnt = 0;
5011 if ( link._nodes[0]->Node() ) // 1st node is a hexa corner
5013 curIntPnt._paramOnLine = coords[ ijk[ iDir ]] - coords[0] + _grid->_tol;
5014 const GridLine& line = _grid->_lines[ iDir ][ lineIndex[ iL ]];
5015 if ( !line._intPoints.empty() )
5017 multiset< F_IntersectPoint >::const_iterator ip =
5018 line._intPoints.upper_bound( curIntPnt );
5020 firstIntPnt = &(*ip);
5023 else if ( !link._fIntPoints.empty() )
5025 firstIntPnt = link._fIntPoints[0];
5031 allLinksOut = ( firstIntPnt->_transition == Trans_OUT &&
5032 !_grid->IsShared( firstIntPnt->_faceIDs[0] ));
5035 if ( hasLinks && allLinksOut )
5041 //================================================================================
5043 * \brief Check if a polyherdon has an edge lying on EDGE shared by strange FACE
5044 * that will be meshed by other algo
5046 bool Hexahedron::hasStrangeEdge() const
5048 if ( _eIntPoints.size() < 2 )
5051 TopTools_MapOfShape edges;
5052 for ( size_t i = 0; i < _eIntPoints.size(); ++i )
5054 if ( !_grid->IsStrangeEdge( _eIntPoints[i]->_shapeID ))
5056 const TopoDS_Shape& s = _grid->Shape( _eIntPoints[i]->_shapeID );
5057 if ( s.ShapeType() == TopAbs_EDGE )
5059 if ( ! edges.Add( s ))
5060 return true; // an EDGE encounters twice
5064 PShapeIteratorPtr edgeIt = _grid->_helper->GetAncestors( s,
5065 *_grid->_helper->GetMesh(),
5067 while ( const TopoDS_Shape* edge = edgeIt->next() )
5068 if ( ! edges.Add( *edge ))
5069 return true; // an EDGE encounters twice
5075 //================================================================================
5077 * \brief Return true if a polyhedron passes _sizeThreshold criterion
5079 bool Hexahedron::checkPolyhedronSize( bool cutByInternalFace, double & volume) const
5083 if ( cutByInternalFace && !_grid->_toUseThresholdForInternalFaces )
5085 // check if any polygon fully lies on shared/internal FACEs
5086 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
5088 const _Face& polygon = _polygons[iP];
5089 if ( polygon._links.empty() )
5091 bool allNodesInternal = true;
5092 for ( size_t iL = 0; iL < polygon._links.size() && allNodesInternal; ++iL )
5094 _Node* n = polygon._links[ iL ].FirstNode();
5095 allNodesInternal = (( n->IsCutByInternal() ) ||
5096 ( n->_intPoint && _grid->IsAnyShared( n->_intPoint->_faceIDs )));
5098 if ( allNodesInternal )
5102 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
5104 const _Face& polygon = _polygons[iP];
5105 if ( polygon._links.empty() )
5107 gp_XYZ area (0,0,0);
5108 gp_XYZ p1 = polygon._links[ 0 ].FirstNode()->Point().XYZ();
5109 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
5111 gp_XYZ p2 = polygon._links[ iL ].LastNode()->Point().XYZ();
5115 volume += p1 * area;
5119 if ( this->hasStrangeEdge() && volume > 1e-13 )
5122 double initVolume = _sideLength[0] * _sideLength[1] * _sideLength[2];
5124 return volume > initVolume / _grid->_sizeThreshold;
5127 //================================================================================
5129 * \brief Check that all faces in polyhedron are connected so a unique volume is defined.
5130 * We test that it is possible to go from any node to all nodes in the polyhedron.
5131 * The set of nodes that can be visit within then defines a unique element.
5132 * In case more than one polyhedron is detected. The function return the set of quantities and nodes defining separates elements.
5133 * Reference to issue #bos[38521][EDF] Generate polyhedron with separate volume.
5135 int Hexahedron::checkPolyhedronValidity( _volumeDef* volDef, std::vector<std::vector<int>>& splitQuantities,
5136 std::vector<std::vector<const SMDS_MeshNode*>>& splitNodes )
5139 std::map<int,int> numberOfSets; // define set id with the number of faces associated!
5140 if ( !volDef->_quantities.empty() )
5142 auto connectivity = volDef->_quantities;
5144 std::vector<bool> allFaces( connectivity.size(), false );
5145 std::set<int> elementSet;
5146 allFaces[ 0 ] = true; // the first node below to the first face
5147 size_t connectedFaces = 1;
5148 // Start filling the set with the nodes of the first face
5149 splitQuantities.push_back( { connectivity[ 0 ] } );
5150 splitNodes.push_back( { volDef->_nodes[ 0 ].Node() } );
5151 elementSet.insert( volDef->_nodes[ 0 ].Node()->GetID() );
5152 for (int n = 1; n < connectivity[ 0 ]; n++)
5154 elementSet.insert( volDef->_nodes[ n ].Node()->GetID() );
5155 splitNodes.back().push_back( volDef->_nodes[ n ].Node() );
5158 numberOfSets.insert( std::pair<int,int>(mySet,1) );
5159 while ( connectedFaces != allFaces.size() )
5161 for (size_t innerId = 1; innerId < connectivity.size(); innerId++)
5164 accum = connectivity[ 0 ];
5166 if ( !allFaces[ innerId ] )
5168 int faceCounter = 0;
5169 for (int n = 0; n < connectivity[ innerId ]; n++)
5171 int nodeId = volDef->_nodes[ accum + n ].Node()->GetID();
5172 if ( elementSet.count( nodeId ) != 0 )
5175 if ( faceCounter >= 2 ) // found coincidences nodes
5177 for (int n = 0; n < connectivity[ innerId ]; n++)
5179 int nodeId = volDef->_nodes[ accum + n ].Node()->GetID();
5180 // insert new nodes so other faces can be identified as belowing to the element
5181 splitNodes.back().push_back( volDef->_nodes[ accum + n ].Node() );
5182 elementSet.insert( nodeId );
5184 allFaces[ innerId ] = true;
5185 splitQuantities.back().push_back( connectivity[ innerId ] );
5186 numberOfSets[ mySet ]++;
5188 innerId = 0; // to restart searching!
5191 accum += connectivity[ innerId ];
5194 if ( connectedFaces != allFaces.size() )
5196 // empty the set, and fill it with nodes of a unvisited face!
5198 accum = connectivity[ 0 ];
5199 for (size_t faceId = 1; faceId < connectivity.size(); faceId++)
5201 if ( !allFaces[ faceId ] )
5203 splitNodes.push_back( { volDef->_nodes[ accum ].Node() } );
5204 elementSet.insert( volDef->_nodes[ accum ].Node()->GetID() );
5205 for (int n = 1; n < connectivity[ faceId ]; n++)
5207 elementSet.insert( volDef->_nodes[ accum + n ].Node()->GetID() );
5208 splitNodes.back().push_back( volDef->_nodes[ accum + n ].Node() );
5211 splitQuantities.push_back( { connectivity[ faceId ] } );
5212 allFaces[ faceId ] = true;
5216 accum += connectivity[ faceId ];
5219 numberOfSets.insert( std::pair<int,int>(mySet,1) );
5223 if ( numberOfSets.size() > 1 )
5225 bool allMoreThan2Faces = true;
5226 for( auto k : numberOfSets )
5228 if ( k.second <= 2 )
5229 allMoreThan2Faces &= false;
5232 if ( allMoreThan2Faces )
5234 // The separate objects are suspect to be closed
5235 return numberOfSets.size();
5239 // Have to index the last face nodes to the final set
5240 // contrary case return as it were a valid polyhedron for backward compatibility
5245 return numberOfSets.size();
5249 //================================================================================
5251 * \brief add original or separated polyhedrons to the mesh
5253 const SMDS_MeshElement* Hexahedron::addPolyhedronToMesh( _volumeDef* volDef, SMESH_MesherHelper& helper, const std::vector<const SMDS_MeshNode*>& nodes,
5254 const std::vector<int>& quantities )
5256 const SMDS_MeshElement* v = helper.AddPolyhedralVolume( nodes, quantities );
5258 volDef->_size = SMDS_VolumeTool( v ).GetSize();
5259 if ( volDef->_size < 0 ) // invalid polyhedron
5261 if ( ! SMESH_MeshEditor( helper.GetMesh() ).Reorient( v ) || // try to fix
5262 SMDS_VolumeTool( v ).GetSize() < 0 )
5264 helper.GetMeshDS()->RemoveFreeElement( v, /*sm=*/nullptr, /*fromGroups=*/false );
5266 //_hasTooSmall = true;
5268 if (SALOME::VerbosityActivated())
5270 std::cout << "Remove INVALID polyhedron, _cellID = " << _cellID
5271 << " ijk = ( " << _i << " " << _j << " " << _k << " ) "
5272 << " solid " << volDef->_solidID << std::endl;
5279 //================================================================================
5281 * \brief Tries to create a hexahedron
5283 bool Hexahedron::addHexa()
5285 int nbQuad = 0, iQuad = -1;
5286 for ( size_t i = 0; i < _polygons.size(); ++i )
5288 if ( _polygons[i]._links.empty() )
5290 if ( _polygons[i]._links.size() != 4 )
5301 for ( int iL = 0; iL < 4; ++iL )
5304 nodes[iL] = _polygons[iQuad]._links[iL].FirstNode();
5307 // find a top node above the base node
5308 _Link* link = _polygons[iQuad]._links[iL]._link;
5309 if ( !link->_faces[0] || !link->_faces[1] )
5310 return debugDumpLink( link );
5311 // a quadrangle sharing <link> with _polygons[iQuad]
5312 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[iQuad] )];
5313 for ( int i = 0; i < 4; ++i )
5314 if ( quad->_links[i]._link == link )
5316 // 1st node of a link opposite to <link> in <quad>
5317 nodes[iL+4] = quad->_links[(i+2)%4].FirstNode();
5323 _volumeDefs.Set( &nodes[0], 8 );
5327 //================================================================================
5329 * \brief Tries to create a tetrahedron
5331 bool Hexahedron::addTetra()
5334 for ( size_t i = 0; i < _polygons.size() && iTria < 0; ++i )
5335 if ( _polygons[i]._links.size() == 3 )
5341 nodes[0] = _polygons[iTria]._links[0].FirstNode();
5342 nodes[1] = _polygons[iTria]._links[1].FirstNode();
5343 nodes[2] = _polygons[iTria]._links[2].FirstNode();
5345 _Link* link = _polygons[iTria]._links[0]._link;
5346 if ( !link->_faces[0] || !link->_faces[1] )
5347 return debugDumpLink( link );
5349 // a triangle sharing <link> with _polygons[0]
5350 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[iTria] )];
5351 for ( int i = 0; i < 3; ++i )
5352 if ( tria->_links[i]._link == link )
5354 nodes[3] = tria->_links[(i+1)%3].LastNode();
5355 _volumeDefs.Set( &nodes[0], 4 );
5361 //================================================================================
5363 * \brief Tries to create a pentahedron
5365 bool Hexahedron::addPenta()
5367 // find a base triangular face
5369 for ( int iF = 0; iF < 5 && iTri < 0; ++iF )
5370 if ( _polygons[ iF ]._links.size() == 3 )
5372 if ( iTri < 0 ) return false;
5377 for ( int iL = 0; iL < 3; ++iL )
5380 nodes[iL] = _polygons[ iTri ]._links[iL].FirstNode();
5383 // find a top node above the base node
5384 _Link* link = _polygons[ iTri ]._links[iL]._link;
5385 if ( !link->_faces[0] || !link->_faces[1] )
5386 return debugDumpLink( link );
5387 // a quadrangle sharing <link> with a base triangle
5388 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[ iTri ] )];
5389 if ( quad->_links.size() != 4 ) return false;
5390 for ( int i = 0; i < 4; ++i )
5391 if ( quad->_links[i]._link == link )
5393 // 1st node of a link opposite to <link> in <quad>
5394 nodes[iL+3] = quad->_links[(i+2)%4].FirstNode();
5400 _volumeDefs.Set( &nodes[0], 6 );
5402 return ( nbN == 6 );
5404 //================================================================================
5406 * \brief Tries to create a pyramid
5408 bool Hexahedron::addPyra()
5410 // find a base quadrangle
5412 for ( int iF = 0; iF < 5 && iQuad < 0; ++iF )
5413 if ( _polygons[ iF ]._links.size() == 4 )
5415 if ( iQuad < 0 ) return false;
5419 nodes[0] = _polygons[iQuad]._links[0].FirstNode();
5420 nodes[1] = _polygons[iQuad]._links[1].FirstNode();
5421 nodes[2] = _polygons[iQuad]._links[2].FirstNode();
5422 nodes[3] = _polygons[iQuad]._links[3].FirstNode();
5424 _Link* link = _polygons[iQuad]._links[0]._link;
5425 if ( !link->_faces[0] || !link->_faces[1] )
5426 return debugDumpLink( link );
5428 // a triangle sharing <link> with a base quadrangle
5429 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[ iQuad ] )];
5430 if ( tria->_links.size() != 3 ) return false;
5431 for ( int i = 0; i < 3; ++i )
5432 if ( tria->_links[i]._link == link )
5434 nodes[4] = tria->_links[(i+1)%3].LastNode();
5435 _volumeDefs.Set( &nodes[0], 5 );
5441 //================================================================================
5443 * \brief Return true if there are _eIntPoints at EDGEs forming a concave corner
5445 bool Hexahedron::hasEdgesAround( const ConcaveFace* cf ) const
5448 ConcaveFace foundGeomHolder;
5449 for ( const E_IntersectPoint* ip : _eIntPoints )
5451 if ( cf->HasEdge( ip->_shapeID ))
5453 if ( ++nbEdges == 2 )
5455 foundGeomHolder.SetEdge( ip->_shapeID );
5457 else if ( ip->_faceIDs.size() >= 3 )
5459 const TGeomID & vID = ip->_shapeID;
5460 if ( cf->HasVertex( vID ) && !foundGeomHolder.HasVertex( vID ))
5462 if ( ++nbEdges == 2 )
5464 foundGeomHolder.SetVertex( vID );
5469 for ( const _Node& hexNode: _hexNodes )
5471 if ( !hexNode._node || !hexNode._intPoint )
5473 const B_IntersectPoint* ip = hexNode._intPoint;
5474 if ( ip->_faceIDs.size() == 2 ) // EDGE
5476 TGeomID edgeID = hexNode._node->GetShapeID();
5477 if ( cf->HasEdge( edgeID ) && !foundGeomHolder.HasEdge( edgeID ))
5479 foundGeomHolder.SetEdge( edgeID );
5480 if ( ++nbEdges == 2 )
5484 else if ( ip->_faceIDs.size() >= 3 ) // VERTEX
5486 TGeomID vID = hexNode._node->GetShapeID();
5487 if ( cf->HasVertex( vID ) && !foundGeomHolder.HasVertex( vID ))
5489 if ( ++nbEdges == 2 )
5491 foundGeomHolder.SetVertex( vID );
5498 //================================================================================
5500 * \brief Dump a link and return \c false
5502 bool Hexahedron::debugDumpLink( Hexahedron::_Link* link )
5504 if (SALOME::VerbosityActivated())
5506 gp_Pnt p1 = link->_nodes[0]->Point(), p2 = link->_nodes[1]->Point();
5507 cout << "BUG: not shared link. IKJ = ( "<< _i << " " << _j << " " << _k << " )" << endl
5508 << "n1 (" << p1.X() << ", "<< p1.Y() << ", "<< p1.Z() << " )" << endl
5509 << "n2 (" << p2.X() << ", "<< p2.Y() << ", "<< p2.Z() << " )" << endl;
5514 //================================================================================
5516 * \brief Classify a point by grid parameters
5518 bool Hexahedron::isOutParam(const double uvw[3]) const
5520 return (( _grid->_coords[0][ _i ] - _grid->_tol > uvw[0] ) ||
5521 ( _grid->_coords[0][ _i+1 ] + _grid->_tol < uvw[0] ) ||
5522 ( _grid->_coords[1][ _j ] - _grid->_tol > uvw[1] ) ||
5523 ( _grid->_coords[1][ _j+1 ] + _grid->_tol < uvw[1] ) ||
5524 ( _grid->_coords[2][ _k ] - _grid->_tol > uvw[2] ) ||
5525 ( _grid->_coords[2][ _k+1 ] + _grid->_tol < uvw[2] ));
5527 //================================================================================
5529 * \brief Find existing triangulation of a polygon
5531 int findExistingTriangulation( const SMDS_MeshElement* polygon,
5532 //const SMDS_Mesh* mesh,
5533 std::vector< const SMDS_MeshNode* >& nodes )
5537 std::vector<const SMDS_MeshNode *> twoNodes(2);
5538 std::vector<const SMDS_MeshElement *> foundFaces; foundFaces.reserve(10);
5539 std::set< const SMDS_MeshElement * > avoidFaces; avoidFaces.insert( polygon );
5541 const int nbPolyNodes = polygon->NbCornerNodes();
5542 twoNodes[1] = polygon->GetNode( nbPolyNodes - 1 );
5543 for ( int iN = 0; iN < nbPolyNodes; ++iN ) // loop on border links of polygon
5545 twoNodes[0] = polygon->GetNode( iN );
5547 int nbFaces = SMDS_Mesh::GetElementsByNodes( twoNodes, foundFaces, SMDSAbs_Face );
5549 for ( int iF = 0; iF < nbFaces; ++iF ) // keep faces lying over polygon
5551 if ( avoidFaces.count( foundFaces[ iF ]))
5553 int i, nbFaceNodes = foundFaces[ iF ]->NbCornerNodes();
5554 for ( i = 0; i < nbFaceNodes; ++i )
5556 const SMDS_MeshNode* n = foundFaces[ iF ]->GetNode( i );
5557 bool isCommonNode = ( n == twoNodes[0] ||
5559 polygon->GetNodeIndex( n ) >= 0 );
5560 if ( !isCommonNode )
5563 if ( i == nbFaceNodes ) // all nodes of foundFaces[iF] are shared with polygon
5564 if ( nbOkFaces++ != iF )
5565 foundFaces[ nbOkFaces-1 ] = foundFaces[ iF ];
5567 if ( nbOkFaces > 0 )
5569 int iFaceSelected = 0;
5570 if ( nbOkFaces > 1 ) // select a face with minimal distance from polygon
5572 double minDist = Precision::Infinite();
5573 for ( int iF = 0; iF < nbOkFaces; ++iF )
5575 int i, nbFaceNodes = foundFaces[ iF ]->NbCornerNodes();
5576 gp_XYZ gc = SMESH_NodeXYZ( foundFaces[ iF ]->GetNode( 0 ));
5577 for ( i = 1; i < nbFaceNodes; ++i )
5578 gc += SMESH_NodeXYZ( foundFaces[ iF ]->GetNode( i ));
5581 double dist = SMESH_MeshAlgos::GetDistance( polygon, gc );
5582 if ( dist < minDist )
5589 if ( foundFaces[ iFaceSelected ]->NbCornerNodes() != 3 )
5591 nodes.insert( nodes.end(),
5592 foundFaces[ iFaceSelected ]->begin_nodes(),
5593 foundFaces[ iFaceSelected ]->end_nodes());
5594 if ( !SMESH_MeshAlgos::IsRightOrder( foundFaces[ iFaceSelected ],
5595 twoNodes[0], twoNodes[1] ))
5597 // reverse just added nodes
5598 std::reverse( nodes.end() - 3, nodes.end() );
5600 avoidFaces.insert( foundFaces[ iFaceSelected ]);
5604 twoNodes[1] = twoNodes[0];
5606 } // loop on polygon nodes
5610 //================================================================================
5612 * \brief Divide a polygon into triangles and modify accordingly an adjacent polyhedron
5614 void splitPolygon( const SMDS_MeshElement* polygon,
5615 SMDS_VolumeTool & volume,
5616 const int facetIndex,
5617 const TGeomID faceID,
5618 const TGeomID solidID,
5619 SMESH_MeshEditor::ElemFeatures& face,
5620 SMESH_MeshEditor& editor,
5621 const bool reinitVolume)
5623 SMESH_MeshAlgos::Triangulate divider(/*optimize=*/false);
5624 bool triangulationExist = false;
5625 int nbTrias = findExistingTriangulation( polygon, face.myNodes );
5627 triangulationExist = true;
5629 nbTrias = divider.GetTriangles( polygon, face.myNodes );
5630 face.myNodes.resize( nbTrias * 3 );
5632 SMESH_MeshEditor::ElemFeatures newVolumeDef;
5633 newVolumeDef.Init( volume.Element() );
5634 newVolumeDef.SetID( volume.Element()->GetID() );
5636 newVolumeDef.myPolyhedQuantities.reserve( volume.NbFaces() + nbTrias );
5637 newVolumeDef.myNodes.reserve( volume.NbNodes() + nbTrias * 3 );
5639 SMESHDS_Mesh* meshDS = editor.GetMeshDS();
5640 SMDS_MeshElement* newTriangle;
5641 for ( int iF = 0, nF = volume.NbFaces(); iF < nF; iF++ )
5643 if ( iF == facetIndex )
5645 newVolumeDef.myPolyhedQuantities.push_back( 3 );
5646 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(),
5647 face.myNodes.begin(),
5648 face.myNodes.begin() + 3 );
5649 meshDS->RemoveFreeElement( polygon, 0, false );
5650 if ( !triangulationExist )
5652 newTriangle = meshDS->AddFace( face.myNodes[0], face.myNodes[1], face.myNodes[2] );
5653 meshDS->SetMeshElementOnShape( newTriangle, faceID );
5658 const SMDS_MeshNode** nn = volume.GetFaceNodes( iF );
5659 const size_t nbFaceNodes = volume.NbFaceNodes ( iF );
5660 newVolumeDef.myPolyhedQuantities.push_back( nbFaceNodes );
5661 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(), nn, nn + nbFaceNodes );
5665 for ( size_t iN = 3; iN < face.myNodes.size(); iN += 3 )
5667 newVolumeDef.myPolyhedQuantities.push_back( 3 );
5668 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(),
5669 face.myNodes.begin() + iN,
5670 face.myNodes.begin() + iN + 3 );
5671 if ( !triangulationExist )
5673 newTriangle = meshDS->AddFace( face.myNodes[iN], face.myNodes[iN+1], face.myNodes[iN+2] );
5674 meshDS->SetMeshElementOnShape( newTriangle, faceID );
5678 meshDS->RemoveFreeElement( volume.Element(), 0, false );
5679 SMDS_MeshElement* newVolume = editor.AddElement( newVolumeDef.myNodes, newVolumeDef );
5680 meshDS->SetMeshElementOnShape( newVolume, solidID );
5685 volume.Set( newVolume );
5689 //================================================================================
5691 * \brief Look for a FACE supporting all given nodes made on EDGEs and VERTEXes
5693 TGeomID findCommonFace( const std::vector< const SMDS_MeshNode* > & nn,
5694 const SMESH_Mesh* mesh )
5697 TGeomID shapeIDs[20];
5698 for ( size_t iN = 0; iN < nn.size(); ++iN )
5699 shapeIDs[ iN ] = nn[ iN ]->GetShapeID();
5701 SMESH_subMesh* sm = mesh->GetSubMeshContaining( shapeIDs[ 0 ]);
5702 for ( const SMESH_subMesh * smFace : sm->GetAncestors() )
5704 if ( smFace->GetSubShape().ShapeType() != TopAbs_FACE )
5707 faceID = smFace->GetId();
5709 for ( size_t iN = 1; iN < nn.size() && faceID; ++iN )
5711 if ( !smFace->DependsOn( shapeIDs[ iN ]))
5719 //================================================================================
5721 * \brief Create mesh faces at free facets
5723 void Hexahedron::addFaces( SMESH_MesherHelper& helper,
5724 const vector< const SMDS_MeshElement* > & boundaryVolumes )
5726 if ( !_grid->_toCreateFaces )
5729 SMDS_VolumeTool vTool;
5730 vector<int> bndFacets;
5731 SMESH_MeshEditor editor( helper.GetMesh() );
5732 SMESH_MeshEditor::ElemFeatures face( SMDSAbs_Face );
5733 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
5735 bool isQuantaSet = _grid->_toUseQuanta;
5736 // check if there are internal or shared FACEs
5737 bool hasInternal = ( !_grid->_geometry.IsOneSolid() ||
5738 _grid->_geometry._soleSolid.HasInternalFaces() );
5740 for ( size_t iV = 0; iV < boundaryVolumes.size(); ++iV )
5742 if ( !vTool.Set( boundaryVolumes[ iV ]))
5744 TGeomID solidID = vTool.Element()->GetShapeID();
5745 Solid * solid = _grid->GetOneOfSolids( solidID );
5747 // find boundary facets
5749 for ( int iF = 0, n = vTool.NbFaces(); iF < n; iF++ )
5751 const SMDS_MeshElement* otherVol;
5752 bool isBoundary = isQuantaSet ? vTool.IsFreeFaceCheckAllNodes( iF, &otherVol ) : vTool.IsFreeFace( iF, &otherVol );
5755 bndFacets.push_back( iF );
5757 else if (( hasInternal ) ||
5758 ( !_grid->IsSolid( otherVol->GetShapeID() )))
5760 // check if all nodes are on internal/shared FACEs
5762 const SMDS_MeshNode** nn = vTool.GetFaceNodes( iF );
5763 const size_t nbFaceNodes = vTool.NbFaceNodes ( iF );
5764 for ( size_t iN = 0; iN < nbFaceNodes && isBoundary; ++iN )
5765 isBoundary = ( nn[ iN ]->GetShapeID() != solidID );
5767 bndFacets.push_back( -( iF+1 )); // !!! minus ==> to check the FACE
5770 if ( bndFacets.empty() )
5774 if ( !vTool.IsPoly() )
5775 vTool.SetExternalNormal();
5776 for ( size_t i = 0; i < bndFacets.size(); ++i ) // loop on boundary facets
5778 const bool isBoundary = ( bndFacets[i] >= 0 );
5779 const int iFacet = isBoundary ? bndFacets[i] : -bndFacets[i]-1;
5780 const SMDS_MeshNode** nn = vTool.GetFaceNodes( iFacet );
5781 const size_t nbFaceNodes = vTool.NbFaceNodes ( iFacet );
5782 face.myNodes.assign( nn, nn + nbFaceNodes );
5785 const SMDS_MeshElement* existFace = 0, *newFace = 0;
5787 if (( existFace = meshDS->FindElement( face.myNodes, SMDSAbs_Face )))
5789 if ( existFace->isMarked() )
5790 continue; // created by this method
5791 faceID = existFace->GetShapeID();
5795 // look for a supporting FACE
5796 for ( size_t iN = 0; iN < nbFaceNodes && !faceID; ++iN ) // look for a node on FACE
5798 if ( nn[ iN ]->GetPosition()->GetDim() == 2 )
5799 faceID = nn[ iN ]->GetShapeID();
5801 if ( faceID == 0 && !isQuantaSet /*if quanta is set boundary nodes at boundary does not coincide with any geometrical face */ )
5802 faceID = findCommonFace( face.myNodes, helper.GetMesh() );
5804 bool toCheckFace = faceID && (( !isBoundary ) ||
5805 ( hasInternal && _grid->_toUseThresholdForInternalFaces ));
5806 if ( toCheckFace ) // check if all nodes are on the found FACE
5808 SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMeshContaining( faceID );
5809 for ( size_t iN = 0; iN < nbFaceNodes && faceID; ++iN )
5811 TGeomID subID = nn[ iN ]->GetShapeID();
5812 if ( subID != faceID && !faceSM->DependsOn( subID ))
5815 // if ( !faceID && !isBoundary )
5818 if ( !faceID && !isBoundary && !isQuantaSet )
5822 // orient a new face according to supporting FACE orientation in shape_to_mesh
5823 if ( !isBoundary && !solid->IsOutsideOriented( faceID ))
5826 editor.Reorient( existFace );
5828 std::reverse( face.myNodes.begin(), face.myNodes.end() );
5831 if ( ! ( newFace = existFace ))
5833 face.SetPoly( nbFaceNodes > 4 );
5834 newFace = editor.AddElement( face.myNodes, face );
5837 newFace->setIsMarked( true ); // to distinguish from face created in getBoundaryElems()
5840 if ( faceID && _grid->IsBoundaryFace( faceID )) // face is not shared
5842 // set newFace to the found FACE provided that it fully lies on the FACE
5843 for ( size_t iN = 0; iN < nbFaceNodes && faceID; ++iN )
5844 if ( nn[iN]->GetShapeID() == solidID )
5847 meshDS->UnSetMeshElementOnShape( existFace, _grid->Shape( faceID ));
5852 if ( faceID && nbFaceNodes > 4 &&
5853 !_grid->IsInternal( faceID ) &&
5854 !_grid->IsShared( faceID ) &&
5855 !_grid->IsBoundaryFace( faceID ))
5857 // split a polygon that will be used by other 3D algorithm
5859 splitPolygon( newFace, vTool, iFacet, faceID, solidID,
5860 face, editor, i+1 < bndFacets.size() );
5865 meshDS->SetMeshElementOnShape( newFace, faceID );
5867 meshDS->SetMeshElementOnShape( newFace, solidID );
5869 } // loop on bndFacets
5870 } // loop on boundaryVolumes
5873 // Orient coherently mesh faces on INTERNAL FACEs
5877 TopExp_Explorer faceExp( _grid->_geometry._mainShape, TopAbs_FACE );
5878 for ( ; faceExp.More(); faceExp.Next() )
5880 if ( faceExp.Current().Orientation() != TopAbs_INTERNAL )
5883 SMESHDS_SubMesh* sm = meshDS->MeshElements( faceExp.Current() );
5884 if ( !sm ) continue;
5886 TIDSortedElemSet facesToOrient;
5887 for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
5888 facesToOrient.insert( facesToOrient.end(), fIt->next() );
5889 if ( facesToOrient.size() < 2 )
5892 gp_Dir direction(1,0,0);
5893 TIDSortedElemSet refFaces;
5894 editor.Reorient2D( facesToOrient, direction, refFaces, /*allowNonManifold=*/true );
5900 //================================================================================
5902 * \brief Create mesh segments.
5904 void Hexahedron::addSegments( SMESH_MesherHelper& helper,
5905 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap )
5907 SMESHDS_Mesh* mesh = helper.GetMeshDS();
5909 std::vector<const SMDS_MeshNode*> nodes;
5910 std::vector<const SMDS_MeshElement *> elems;
5911 map< TGeomID, vector< TGeomID > >::const_iterator e2ff = edge2faceIDsMap.begin();
5912 for ( ; e2ff != edge2faceIDsMap.end(); ++e2ff )
5914 const TopoDS_Edge& edge = TopoDS::Edge( _grid->Shape( e2ff->first ));
5915 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( e2ff->second[0] ));
5916 StdMeshers_FaceSide side( face, edge, helper.GetMesh(), /*isFwd=*/true, /*skipMed=*/true );
5917 nodes = side.GetOrderedNodes();
5920 if ( nodes.size() == 2 )
5921 // check that there is an element connecting two nodes
5922 if ( !mesh->GetElementsByNodes( nodes, elems ))
5925 for ( size_t i = 1; i < nodes.size(); i++ )
5927 if ( mesh->FindEdge( nodes[i-1], nodes[i] ))
5929 SMDS_MeshElement* segment = mesh->AddEdge( nodes[i-1], nodes[i] );
5930 mesh->SetMeshElementOnShape( segment, e2ff->first );
5936 //================================================================================
5938 * \brief Return created volumes and volumes that can have free facet because of
5939 * skipped small volume. Also create mesh faces on free facets
5940 * of adjacent not-cut volumes if the result volume is too small.
5942 void Hexahedron::getBoundaryElems( vector< const SMDS_MeshElement* > & boundaryElems )
5944 if ( _hasTooSmall /*|| _volumeDefs.IsEmpty()*/ )
5946 // create faces around a missing small volume
5948 SMESH_MeshEditor editor( _grid->_helper->GetMesh() );
5949 SMESH_MeshEditor::ElemFeatures polygon( SMDSAbs_Face );
5950 SMESHDS_Mesh* meshDS = _grid->_helper->GetMeshDS();
5951 std::vector<const SMDS_MeshElement *> adjVolumes(2);
5952 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
5954 const size_t nbLinks = _polygons[ iF ]._links.size();
5955 if ( nbLinks != 4 ) continue;
5956 polygon.myNodes.resize( nbLinks );
5957 polygon.myNodes.back() = 0;
5958 for ( size_t iL = 0, iN = nbLinks - 1; iL < nbLinks; ++iL, --iN )
5959 if ( ! ( polygon.myNodes[iN] = _polygons[ iF ]._links[ iL ].FirstNode()->Node() ))
5961 if ( !polygon.myNodes.back() )
5964 meshDS->GetElementsByNodes( polygon.myNodes, adjVolumes, SMDSAbs_Volume );
5965 if ( adjVolumes.size() != 1 )
5967 if ( !adjVolumes[0]->isMarked() )
5969 boundaryElems.push_back( adjVolumes[0] );
5970 adjVolumes[0]->setIsMarked( true );
5973 bool sameShape = true;
5974 TGeomID shapeID = polygon.myNodes[0]->GetShapeID();
5975 for ( size_t i = 1; i < polygon.myNodes.size() && sameShape; ++i )
5976 sameShape = ( shapeID == polygon.myNodes[i]->GetShapeID() );
5978 if ( !sameShape || !_grid->IsSolid( shapeID ))
5979 continue; // some of shapes must be FACE
5983 faceID = getAnyFace();
5986 if ( _grid->IsInternal( faceID ) ||
5987 _grid->IsShared( faceID ) //||
5988 //_grid->IsBoundaryFace( faceID ) -- commented for #19887
5990 break; // create only if a new face will be used by other 3D algo
5993 Solid * solid = _grid->GetOneOfSolids( adjVolumes[0]->GetShapeID() );
5994 if ( !solid->IsOutsideOriented( faceID ))
5995 std::reverse( polygon.myNodes.begin(), polygon.myNodes.end() );
5997 //polygon.SetPoly( polygon.myNodes.size() > 4 );
5998 const SMDS_MeshElement* newFace = editor.AddElement( polygon.myNodes, polygon );
5999 meshDS->SetMeshElementOnShape( newFace, faceID );
6003 // return created volumes
6004 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
6006 if ( volDef ->_volume &&
6007 !volDef->_volume->IsNull() &&
6008 !volDef->_volume->isMarked() )
6010 volDef->_volume->setIsMarked( true );
6011 boundaryElems.push_back( volDef->_volume );
6013 if ( _grid->IsToCheckNodePos() ) // un-mark nodes marked in addVolumes()
6014 for ( size_t iN = 0; iN < volDef->_nodes.size(); ++iN )
6015 volDef->_nodes[iN].Node()->setIsMarked( false );
6017 if ( volDef->_brotherVolume.size() > 0 )
6019 for (auto _bro : volDef->_brotherVolume )
6021 _bro->setIsMarked( true );
6022 boundaryElems.push_back( _bro );
6028 //================================================================================
6030 * \brief Remove edges and nodes dividing a hexa side in the case if an adjacent
6031 * volume also sharing the dividing edge is missing due to its small side.
6034 //================================================================================
6036 void Hexahedron::removeExcessSideDivision(const vector< Hexahedron* >& allHexa)
6038 if ( ! _volumeDefs.IsPolyhedron() )
6039 return; // not a polyhedron
6041 // look for a divided side adjacent to a small hexahedron
6043 int di[6] = { 0, 0, 0, 0,-1, 1 };
6044 int dj[6] = { 0, 0,-1, 1, 0, 0 };
6045 int dk[6] = {-1, 1, 0, 0, 0, 0 };
6047 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
6049 size_t neighborIndex = _grid->CellIndex( _i + di[iF],
6052 if ( neighborIndex >= allHexa.size() ||
6053 !allHexa[ neighborIndex ] ||
6054 !allHexa[ neighborIndex ]->_hasTooSmall )
6057 // check if a side is divided into several polygons
6058 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
6060 int nbPolygons = 0, nbNodes = 0;
6061 for ( size_t i = 0; i < volDef->_names.size(); ++i )
6062 if ( volDef->_names[ i ] == _hexQuads[ iF ]._name )
6065 nbNodes += volDef->_quantities[ i ];
6067 if ( nbPolygons < 2 )
6070 // construct loops from polygons
6071 typedef _volumeDef::_linkDef TLinkDef;
6072 std::vector< TLinkDef* > loops;
6073 std::vector< TLinkDef > links( nbNodes );
6074 for ( size_t i = 0, iN = 0, iLoop = 0; iLoop < volDef->_quantities.size(); ++iLoop )
6076 size_t nbLinks = volDef->_quantities[ iLoop ];
6077 if ( volDef->_names[ iLoop ] != _hexQuads[ iF ]._name )
6082 loops.push_back( & links[i] );
6083 for ( size_t n = 0; n < nbLinks-1; ++n, ++i, ++iN )
6085 links[i].init( volDef->_nodes[iN], volDef->_nodes[iN+1], iLoop );
6086 links[i].setNext( &links[i+1] );
6088 links[i].init( volDef->_nodes[iN], volDef->_nodes[iN-nbLinks+1], iLoop );
6089 links[i].setNext( &links[i-nbLinks+1] );
6093 // look for equal links in different loops and join such loops
6094 bool loopsJoined = false;
6095 std::set< TLinkDef > linkSet;
6096 for ( size_t iLoop = 0; iLoop < loops.size(); ++iLoop )
6099 for ( TLinkDef* l = loops[ iLoop ]; l != beg; l = l->_next ) // walk around the iLoop
6101 std::pair< std::set< TLinkDef >::iterator, bool > it2new = linkSet.insert( *l );
6102 if ( !it2new.second ) // equal found, join loops
6104 const TLinkDef* equal = &(*it2new.first);
6105 if ( equal->_loopIndex == l->_loopIndex )
6110 for ( size_t i = iLoop - 1; i < loops.size(); --i )
6111 if ( loops[ i ] && loops[ i ]->_loopIndex == equal->_loopIndex )
6114 // exclude l and equal and join two loops
6115 if ( l->_prev != equal )
6116 l->_prev->setNext( equal->_next );
6117 if ( equal->_prev != l )
6118 equal->_prev->setNext( l->_next );
6120 if ( volDef->_quantities[ l->_loopIndex ] > 0 )
6121 volDef->_quantities[ l->_loopIndex ] *= -1;
6122 if ( volDef->_quantities[ equal->_loopIndex ] > 0 )
6123 volDef->_quantities[ equal->_loopIndex ] *= -1;
6125 if ( loops[ iLoop ] == l )
6126 loops[ iLoop ] = l->_prev->_next;
6128 beg = loops[ iLoop ];
6134 // set unchanged polygons
6135 std::vector< int > newQuantities;
6136 std::vector< _volumeDef::_nodeDef > newNodes;
6137 vector< SMESH_Block::TShapeID > newNames;
6138 newQuantities.reserve( volDef->_quantities.size() );
6139 newNodes.reserve ( volDef->_nodes.size() );
6140 newNames.reserve ( volDef->_names.size() );
6141 for ( size_t i = 0, iLoop = 0; iLoop < volDef->_quantities.size(); ++iLoop )
6143 if ( volDef->_quantities[ iLoop ] < 0 )
6145 i -= volDef->_quantities[ iLoop ];
6148 newQuantities.push_back( volDef->_quantities[ iLoop ]);
6149 newNodes.insert( newNodes.end(),
6150 volDef->_nodes.begin() + i,
6151 volDef->_nodes.begin() + i + newQuantities.back() );
6152 newNames.push_back( volDef->_names[ iLoop ]);
6153 i += volDef->_quantities[ iLoop ];
6157 for ( size_t iLoop = 0; iLoop < loops.size(); ++iLoop )
6159 if ( !loops[ iLoop ] )
6161 newQuantities.push_back( 0 );
6163 for ( TLinkDef* l = loops[ iLoop ]; l != beg; l = l->_next, ++newQuantities.back() )
6165 newNodes.push_back( l->_node1 );
6166 beg = loops[ iLoop ];
6168 newNames.push_back( _hexQuads[ iF ]._name );
6170 volDef->_quantities.swap( newQuantities );
6171 volDef->_nodes.swap( newNodes );
6172 volDef->_names.swap( newNames );
6174 } // loop on volDef's
6175 } // loop on hex sides
6178 } // removeExcessSideDivision()
6181 //================================================================================
6183 * \brief Remove nodes splitting Cartesian cell edges in the case if a node
6184 * is used in every cells only by two polygons sharing the edge
6187 //================================================================================
6189 void Hexahedron::removeExcessNodes(vector< Hexahedron* >& allHexa)
6191 if ( ! _volumeDefs.IsPolyhedron() )
6192 return; // not a polyhedron
6194 typedef vector< _volumeDef::_nodeDef >::iterator TNodeIt;
6195 vector< int > nodesInPoly[ 4 ]; // node index in _volumeDefs._nodes
6196 vector< int > volDefInd [ 4 ]; // index of a _volumeDefs
6197 Hexahedron* hexa [ 4 ];
6198 int i,j,k, cellIndex, iLink = 0, iCellLink;
6199 for ( int iDir = 0; iDir < 3; ++iDir )
6201 CellsAroundLink fourCells( _grid, iDir );
6202 for ( int iL = 0; iL < 4; ++iL, ++iLink ) // 4 links in a direction
6204 _Link& link = _hexLinks[ iLink ];
6205 fourCells.Init( _i, _j, _k, iLink );
6207 for ( size_t iP = 0; iP < link._fIntPoints.size(); ++iP ) // loop on nodes on the link
6209 bool nodeRemoved = true;
6210 _volumeDef::_nodeDef node; node._intPoint = link._fIntPoints[iP];
6212 for ( size_t i = 0, nb = _volumeDefs.size(); i < nb && nodeRemoved; ++i )
6213 if ( _volumeDef* vol = _volumeDefs.at( i ))
6215 ( std::find( vol->_nodes.begin(), vol->_nodes.end(), node ) == vol->_nodes.end() );
6217 continue; // node already removed
6219 // check if a node encounters zero or two times in 4 cells sharing iLink
6220 // if so, the node can be removed from the cells
6221 bool nodeIsOnEdge = true;
6222 int nbPolyhedraWithNode = 0;
6223 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing a link
6225 nodesInPoly[ iC ].clear();
6226 volDefInd [ iC ].clear();
6228 if ( !fourCells.GetCell( iC, i,j,k, cellIndex, iCellLink ))
6230 hexa[ iC ] = allHexa[ cellIndex ];
6233 for ( size_t i = 0, nb = hexa[ iC ]->_volumeDefs.size(); i < nb; ++i )
6234 if ( _volumeDef* vol = hexa[ iC ]->_volumeDefs.at( i ))
6236 for ( TNodeIt nIt = vol->_nodes.begin(); nIt != vol->_nodes.end(); ++nIt )
6238 nIt = std::find( nIt, vol->_nodes.end(), node );
6239 if ( nIt != vol->_nodes.end() )
6241 nodesInPoly[ iC ].push_back( std::distance( vol->_nodes.begin(), nIt ));
6242 volDefInd [ iC ].push_back( i );
6247 nbPolyhedraWithNode += ( !nodesInPoly[ iC ].empty() );
6249 if ( nodesInPoly[ iC ].size() != 0 &&
6250 nodesInPoly[ iC ].size() != 2 )
6252 nodeIsOnEdge = false;
6255 } // loop on 4 cells
6257 // remove nodes from polyhedra
6258 if ( nbPolyhedraWithNode > 0 && nodeIsOnEdge )
6260 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing the link
6262 if ( nodesInPoly[ iC ].empty() )
6264 for ( int i = volDefInd[ iC ].size() - 1; i >= 0; --i )
6266 _volumeDef* vol = hexa[ iC ]->_volumeDefs.at( volDefInd[ iC ][ i ]);
6267 int nIndex = nodesInPoly[ iC ][ i ];
6268 // decrement _quantities
6269 for ( size_t iQ = 0; iQ < vol->_quantities.size(); ++iQ )
6270 if ( nIndex < vol->_quantities[ iQ ])
6272 vol->_quantities[ iQ ]--;
6277 nIndex -= vol->_quantities[ iQ ];
6279 vol->_nodes.erase( vol->_nodes.begin() + nodesInPoly[ iC ][ i ]);
6282 vol->_nodes.size() == 6 * 4 &&
6283 vol->_quantities.size() == 6 ) // polyhedron becomes hexahedron?
6285 bool allQuads = true;
6286 for ( size_t iQ = 0; iQ < vol->_quantities.size() && allQuads; ++iQ )
6287 allQuads = ( vol->_quantities[ iQ ] == 4 );
6290 // set side nodes as this: bottom, top, top, ...
6291 int iTop = 0, iBot = 0; // side indices
6292 for ( int iS = 0; iS < 6; ++iS )
6294 if ( vol->_names[ iS ] == SMESH_Block::ID_Fxy0 )
6296 if ( vol->_names[ iS ] == SMESH_Block::ID_Fxy1 )
6303 std::copy( vol->_nodes.begin(),
6304 vol->_nodes.begin() + 4,
6305 vol->_nodes.begin() + 4 );
6308 std::copy( vol->_nodes.begin() + 4 * iBot,
6309 vol->_nodes.begin() + 4 * ( iBot + 1),
6310 vol->_nodes.begin() );
6313 std::copy( vol->_nodes.begin() + 4 * iTop,
6314 vol->_nodes.begin() + 4 * ( iTop + 1),
6315 vol->_nodes.begin() + 4 );
6317 std::copy( vol->_nodes.begin() + 4,
6318 vol->_nodes.begin() + 8,
6319 vol->_nodes.begin() + 8 );
6320 // set up top facet nodes by comparing their uvw with bottom nodes
6321 E_IntersectPoint ip[8];
6322 for ( int iN = 0; iN < 8; ++iN )
6324 SMESH_NodeXYZ p = vol->_nodes[ iN ].Node();
6325 _grid->ComputeUVW( p, ip[ iN ]._uvw );
6327 const double tol2 = _grid->_tol * _grid->_tol;
6328 for ( int iN = 0; iN < 4; ++iN )
6330 gp_Pnt2d pBot( ip[ iN ]._uvw[0], ip[ iN ]._uvw[1] );
6331 for ( int iT = 4; iT < 8; ++iT )
6333 gp_Pnt2d pTop( ip[ iT ]._uvw[0], ip[ iT ]._uvw[1] );
6334 if ( pBot.SquareDistance( pTop ) < tol2 )
6336 // vol->_nodes[ iN + 4 ]._node = ip[ iT ]._node;
6337 // vol->_nodes[ iN + 4 ]._intPoint = 0;
6338 vol->_nodes[ iN + 4 ] = vol->_nodes[ iT + 4 ];
6343 vol->_nodes.resize( 8 );
6344 vol->_quantities.clear();
6345 //vol->_names.clear();
6348 } // loop on _volumeDefs
6349 } // loop on 4 cell abound a link
6350 } // if ( nodeIsOnEdge )
6351 } // loop on intersection points of a link
6352 } // loop on 4 links of a direction
6353 } // loop on 3 directions
6357 } // removeExcessNodes()
6359 //================================================================================
6361 * \brief [Issue #19913] Modify _hexLinks._splits to prevent creating overlapping volumes
6363 //================================================================================
6365 void Hexahedron::preventVolumesOverlapping()
6367 // Cut off a quadrangle corner if two links sharing the corner
6368 // are shared by same two solids, in this case each of solids gets
6369 // a triangle for it-self.
6370 std::vector< TGeomID > soIDs[4];
6371 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
6373 _Face& quad = _hexQuads[ iF ] ;
6375 int iFOpposite = iF + ( iF % 2 ? -1 : 1 );
6376 _Face& quadOpp = _hexQuads[ iFOpposite ] ;
6378 int nbSides = 0, nbSidesOpp = 0;
6379 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
6381 nbSides += ( quad._links [ iE ].NbResultLinks() > 0 );
6382 nbSidesOpp += ( quadOpp._links[ iE ].NbResultLinks() > 0 );
6384 if ( nbSides < 4 || nbSidesOpp != 2 )
6387 for ( int iE = 0; iE < 4; ++iE )
6389 soIDs[ iE ].clear();
6390 _Node* n = quad._links[ iE ].FirstNode();
6391 if ( n->_intPoint && n->_intPoint->_faceIDs.size() )
6392 soIDs[ iE ] = _grid->GetSolidIDs( n->_intPoint->_faceIDs[0] );
6394 if ((( soIDs[0].size() >= 2 ) +
6395 ( soIDs[1].size() >= 2 ) +
6396 ( soIDs[2].size() >= 2 ) +
6397 ( soIDs[3].size() >= 2 ) ) < 3 )
6401 for ( int i = 0; i < 4; ++i )
6403 int i1 = _grid->_helper->WrapIndex( i + 1, 4 );
6404 int i2 = _grid->_helper->WrapIndex( i + 2, 4 );
6405 int i3 = _grid->_helper->WrapIndex( i + 3, 4 );
6406 if ( soIDs[i1].size() == 2 && soIDs[i ] != soIDs[i1] &&
6407 soIDs[i2].size() == 2 && soIDs[i1] == soIDs[i2] &&
6408 soIDs[i3].size() == 2 && soIDs[i2] == soIDs[i3] )
6410 quad._links[ i1 ]._link->_splits.clear();
6411 quad._links[ i2 ]._link->_splits.clear();
6420 } // preventVolumesOverlapping()
6422 //================================================================================
6424 * \brief Set to _hexLinks a next portion of splits located on one side of INTERNAL FACEs
6426 bool Hexahedron::_SplitIterator::Next()
6428 if ( _iterationNb > 0 )
6429 // count used splits
6430 for ( size_t i = 0; i < _splits.size(); ++i )
6432 if ( _splits[i]._iCheckIteration == _iterationNb )
6434 _splits[i]._isUsed = _splits[i]._checkedSplit->_faces[1];
6435 _nbUsed += _splits[i]._isUsed;
6443 bool toTestUsed = ( _nbChecked >= _splits.size() );
6446 // all splits are checked; find all not used splits
6447 for ( size_t i = 0; i < _splits.size(); ++i )
6448 if ( !_splits[i].IsCheckedOrUsed( toTestUsed ))
6449 _splits[i]._iCheckIteration = _iterationNb;
6451 _nbUsed = _splits.size(); // to stop iteration
6455 // get any not used/checked split to start from
6457 for ( size_t i = 0; i < _splits.size(); ++i )
6459 if ( !_splits[i].IsCheckedOrUsed( toTestUsed ))
6461 _freeNodes.push_back( _splits[i]._nodes[0] );
6462 _freeNodes.push_back( _splits[i]._nodes[1] );
6463 _splits[i]._iCheckIteration = _iterationNb;
6467 // find splits connected to the start one via _freeNodes
6468 for ( size_t iN = 0; iN < _freeNodes.size(); ++iN )
6470 for ( size_t iS = 0; iS < _splits.size(); ++iS )
6472 if ( _splits[iS].IsCheckedOrUsed( toTestUsed ))
6475 if ( _freeNodes[iN] == _splits[iS]._nodes[0] )
6477 else if ( _freeNodes[iN] == _splits[iS]._nodes[1] )
6481 if ( _freeNodes[iN]->_isInternalFlags > 0 )
6483 if ( _splits[iS]._nodes[ iN2 ]->_isInternalFlags == 0 )
6485 if ( !_splits[iS]._nodes[ iN2 ]->IsLinked( _freeNodes[iN]->_intPoint ))
6488 _splits[iS]._iCheckIteration = _iterationNb;
6489 _freeNodes.push_back( _splits[iS]._nodes[ iN2 ]);
6493 // set splits to hex links
6495 for ( int iL = 0; iL < 12; ++iL )
6496 _hexLinks[ iL ]._splits.clear();
6499 for ( size_t i = 0; i < _splits.size(); ++i )
6501 if ( _splits[i]._iCheckIteration == _iterationNb )
6503 split._nodes[0] = _splits[i]._nodes[0];
6504 split._nodes[1] = _splits[i]._nodes[1];
6505 _Link & hexLink = _hexLinks[ _splits[i]._linkID ];
6506 hexLink._splits.push_back( split );
6507 _splits[i]._checkedSplit = & hexLink._splits.back();
6514 //================================================================================
6516 * \brief computes exact bounding box with axes parallel to given ones
6518 //================================================================================
6520 void getExactBndBox( const vector< TopoDS_Shape >& faceVec,
6521 const double* axesDirs,
6525 TopoDS_Compound allFacesComp;
6526 b.MakeCompound( allFacesComp );
6527 for ( size_t iF = 0; iF < faceVec.size(); ++iF )
6528 b.Add( allFacesComp, faceVec[ iF ] );
6530 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
6531 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
6533 for ( int i = 0; i < 6; ++i )
6534 farDist = Max( farDist, 10 * sP[i] );
6536 gp_XYZ axis[3] = { gp_XYZ( axesDirs[0], axesDirs[1], axesDirs[2] ),
6537 gp_XYZ( axesDirs[3], axesDirs[4], axesDirs[5] ),
6538 gp_XYZ( axesDirs[6], axesDirs[7], axesDirs[8] ) };
6539 axis[0].Normalize();
6540 axis[1].Normalize();
6541 axis[2].Normalize();
6543 gp_Mat basis( axis[0], axis[1], axis[2] );
6544 gp_Mat bi = basis.Inverted();
6547 for ( int iDir = 0; iDir < 3; ++iDir )
6549 gp_XYZ axis0 = axis[ iDir ];
6550 gp_XYZ axis1 = axis[ ( iDir + 1 ) % 3 ];
6551 gp_XYZ axis2 = axis[ ( iDir + 2 ) % 3 ];
6552 for ( int isMax = 0; isMax < 2; ++isMax )
6554 double shift = isMax ? farDist : -farDist;
6555 gp_XYZ orig = shift * axis0;
6556 gp_XYZ norm = axis1 ^ axis2;
6557 gp_Pln pln( orig, norm );
6558 norm = pln.Axis().Direction().XYZ();
6559 BRepBuilderAPI_MakeFace plane( pln, -farDist, farDist, -farDist, farDist );
6561 gp_Pnt& pAxis = isMax ? pMax : pMin;
6562 gp_Pnt pPlane, pFaces;
6563 double dist = GEOMUtils::GetMinDistance( plane, allFacesComp, pPlane, pFaces );
6568 for ( int i = 0; i < 2; ++i ) {
6569 corner.SetCoord( 1, sP[ i*3 ]);
6570 for ( int j = 0; j < 2; ++j ) {
6571 corner.SetCoord( 2, sP[ i*3 + 1 ]);
6572 for ( int k = 0; k < 2; ++k )
6574 corner.SetCoord( 3, sP[ i*3 + 2 ]);
6580 corner = isMax ? bb.CornerMax() : bb.CornerMin();
6581 pAxis.SetCoord( iDir+1, corner.Coord( iDir+1 ));
6585 gp_XYZ pf = pFaces.XYZ() * bi;
6586 pAxis.SetCoord( iDir+1, pf.Coord( iDir+1 ) );
6592 shapeBox.Add( pMin );
6593 shapeBox.Add( pMax );
6600 //=============================================================================
6602 * \brief Generates 3D structured Cartesian mesh in the internal part of
6603 * solid shapes and polyhedral volumes near the shape boundary.
6604 * \param theMesh - mesh to fill in
6605 * \param theShape - a compound of all SOLIDs to mesh
6606 * \retval bool - true in case of success
6608 //=============================================================================
6610 bool StdMeshers_Cartesian_3D::Compute(SMESH_Mesh & theMesh,
6611 const TopoDS_Shape & theShape)
6613 if ( _hypViscousLayers )
6615 const StdMeshers_ViscousLayers* hypViscousLayers = _hypViscousLayers;
6616 _hypViscousLayers = nullptr;
6618 StdMeshers_Cartesian_VL::ViscousBuilder builder( hypViscousLayers, theMesh, theShape );
6621 TopoDS_Shape offsetShape = builder.MakeOffsetShape( theShape, theMesh, error );
6622 if ( offsetShape.IsNull() )
6623 throw SALOME_Exception( error );
6625 SMESH_Mesh* offsetMesh = new TmpMesh();
6626 offsetMesh->ShapeToMesh( offsetShape );
6627 offsetMesh->GetSubMesh( offsetShape )->DependsOn();
6629 this->_isComputeOffset = true;
6630 if ( ! this->Compute( *offsetMesh, offsetShape ))
6633 return builder.MakeViscousLayers( *offsetMesh, theMesh, theShape );
6636 // The algorithm generates the mesh in following steps:
6638 // 1) Intersection of grid lines with the geometry boundary.
6639 // This step allows to find out if a given node of the initial grid is
6640 // inside or outside the geometry.
6642 // 2) For each cell of the grid, check how many of it's nodes are outside
6643 // of the geometry boundary. Depending on a result of this check
6644 // - skip a cell, if all it's nodes are outside
6645 // - skip a cell, if it is too small according to the size threshold
6646 // - add a hexahedron in the mesh, if all nodes are inside
6647 // - add a polyhedron in the mesh, if some nodes are inside and some outside
6649 _computeCanceled = false;
6651 SMESH_MesherHelper helper( theMesh );
6652 SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
6657 grid._helper = &helper;
6658 grid._toAddEdges = _hyp->GetToAddEdges();
6659 grid._toCreateFaces = _hyp->GetToCreateFaces();
6660 grid._toConsiderInternalFaces = _hyp->GetToConsiderInternalFaces();
6661 grid._toUseThresholdForInternalFaces = _hyp->GetToUseThresholdForInternalFaces();
6662 grid._sizeThreshold = _hyp->GetSizeThreshold();
6663 grid._toUseQuanta = _hyp->GetToUseQuanta();
6664 grid._quanta = _hyp->GetQuanta();
6665 if ( _isComputeOffset )
6667 grid._toAddEdges = true;
6668 grid._toCreateFaces = true;
6670 grid.InitGeometry( theShape );
6672 vector< TopoDS_Shape > faceVec;
6674 TopTools_MapOfShape faceMap;
6675 TopExp_Explorer fExp;
6676 for ( fExp.Init( theShape, TopAbs_FACE ); fExp.More(); fExp.Next() )
6678 bool isNewFace = faceMap.Add( fExp.Current() );
6679 if ( !grid._toConsiderInternalFaces )
6680 if ( !isNewFace || fExp.Current().Orientation() == TopAbs_INTERNAL )
6681 // remove an internal face
6682 faceMap.Remove( fExp.Current() );
6684 faceVec.reserve( faceMap.Extent() );
6685 faceVec.assign( faceMap.cbegin(), faceMap.cend() );
6687 vector<FaceGridIntersector> facesItersectors( faceVec.size() );
6689 for ( size_t i = 0; i < faceVec.size(); ++i )
6691 facesItersectors[i]._face = TopoDS::Face( faceVec[i] );
6692 facesItersectors[i]._faceID = grid.ShapeID( faceVec[i] );
6693 facesItersectors[i]._grid = &grid;
6694 shapeBox.Add( facesItersectors[i].GetFaceBndBox() );
6696 getExactBndBox( faceVec, _hyp->GetAxisDirs(), shapeBox );
6699 vector<double> xCoords, yCoords, zCoords;
6700 _hyp->GetCoordinates( xCoords, yCoords, zCoords, shapeBox );
6702 grid.SetCoordinates( xCoords, yCoords, zCoords, _hyp->GetAxisDirs(), shapeBox );
6704 if ( _computeCanceled ) return false;
6707 { // copy partner faces and curves of not thread-safe types
6708 set< const Standard_Transient* > tshapes;
6709 BRepBuilderAPI_Copy copier;
6710 for ( size_t i = 0; i < facesItersectors.size(); ++i )
6712 if ( !facesItersectors[i].IsThreadSafe( tshapes ))
6714 copier.Perform( facesItersectors[i]._face );
6715 facesItersectors[i]._face = TopoDS::Face( copier );
6719 // Intersection of grid lines with the geometry boundary.
6720 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, facesItersectors.size() ),
6721 ParallelIntersector( facesItersectors ),
6722 tbb::simple_partitioner());
6724 for ( size_t i = 0; i < facesItersectors.size(); ++i )
6725 facesItersectors[i].Intersect();
6728 // put intersection points onto the GridLine's; this is done after intersection
6729 // to avoid contention of facesItersectors for writing into the same GridLine
6730 // in case of parallel work of facesItersectors
6731 for ( size_t i = 0; i < facesItersectors.size(); ++i )
6732 facesItersectors[i].StoreIntersections();
6734 if ( _computeCanceled ) return false;
6736 // create nodes on the geometry
6737 grid.ComputeNodes( helper );
6739 if ( _computeCanceled ) return false;
6741 // get EDGEs to take into account
6742 map< TGeomID, vector< TGeomID > > edge2faceIDsMap;
6743 grid.GetEdgesToImplement( edge2faceIDsMap, theShape, faceVec );
6745 // create volume elements
6746 Hexahedron hex( &grid );
6747 int nbAdded = hex.MakeElements( helper, edge2faceIDsMap );
6751 if ( !grid._toConsiderInternalFaces )
6753 // make all SOLIDs computed
6754 TopExp_Explorer solidExp( theShape, TopAbs_SOLID );
6755 if ( SMESHDS_SubMesh* sm1 = meshDS->MeshElements( solidExp.Current()) )
6757 SMDS_ElemIteratorPtr volIt = sm1->GetElements();
6758 for ( ; solidExp.More() && volIt->more(); solidExp.Next() )
6760 const SMDS_MeshElement* vol = volIt->next();
6761 sm1->RemoveElement( vol );
6762 meshDS->SetMeshElementOnShape( vol, solidExp.Current() );
6766 // make other sub-shapes computed
6767 setSubmeshesComputed( theMesh, theShape );
6770 // remove free nodes
6771 //if ( SMESHDS_SubMesh * smDS = meshDS->MeshElements( helper.GetSubShapeID() ))
6773 std::vector< const SMDS_MeshNode* > nodesToRemove;
6774 // get intersection nodes
6775 for ( int iDir = 0; iDir < 3; ++iDir )
6777 vector< GridLine >& lines = grid._lines[ iDir ];
6778 for ( size_t i = 0; i < lines.size(); ++i )
6780 multiset< F_IntersectPoint >::iterator ip = lines[i]._intPoints.begin();
6781 for ( ; ip != lines[i]._intPoints.end(); ++ip )
6783 !ip->_node->IsNull() &&
6784 ip->_node->NbInverseElements() == 0 &&
6785 !ip->_node->isMarked() )
6787 nodesToRemove.push_back( ip->_node );
6788 ip->_node->setIsMarked( true );
6793 for ( size_t i = 0; i < grid._nodes.size(); ++i )
6794 if ( grid._nodes[i] &&
6795 !grid._nodes[i]->IsNull() &&
6796 grid._nodes[i]->NbInverseElements() == 0 &&
6797 !grid._nodes[i]->isMarked() )
6799 nodesToRemove.push_back( grid._nodes[i] );
6800 grid._nodes[i]->setIsMarked( true );
6803 for ( size_t i = 0; i < grid._allBorderNodes.size(); ++i )
6804 if ( grid._allBorderNodes[i] &&
6805 !grid._allBorderNodes[i]->IsNull() &&
6806 grid._allBorderNodes[i]->NbInverseElements() == 0 )
6808 nodesToRemove.push_back( grid._allBorderNodes[i] );
6809 grid._allBorderNodes[i]->setIsMarked( true );
6813 for ( size_t i = 0; i < nodesToRemove.size(); ++i )
6814 meshDS->RemoveFreeNode( nodesToRemove[i], /*smD=*/0, /*fromGroups=*/false );
6820 // SMESH_ComputeError is not caught at SMESH_submesh level for an unknown reason
6821 catch ( SMESH_ComputeError& e)
6823 return error( SMESH_ComputeErrorPtr( new SMESH_ComputeError( e )));
6828 //=============================================================================
6832 //=============================================================================
6834 bool StdMeshers_Cartesian_3D::Evaluate(SMESH_Mesh & /*theMesh*/,
6835 const TopoDS_Shape & /*theShape*/,
6836 MapShapeNbElems& /*theResMap*/)
6839 // std::vector<int> aResVec(SMDSEntity_Last);
6840 // for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
6841 // if(IsQuadratic) {
6842 // aResVec[SMDSEntity_Quad_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
6843 // int nb1d_face0_int = ( nb2d_face0*4 - nb1d ) / 2;
6844 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
6847 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
6848 // aResVec[SMDSEntity_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
6850 // SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
6851 // aResMap.insert(std::make_pair(sm,aResVec));
6856 //=============================================================================
6860 * \brief Event listener setting/unsetting _alwaysComputed flag to
6861 * submeshes of inferior levels to prevent their computing
6863 struct _EventListener : public SMESH_subMeshEventListener
6867 _EventListener(const string& algoName):
6868 SMESH_subMeshEventListener(/*isDeletable=*/true,"StdMeshers_Cartesian_3D::_EventListener"),
6871 // --------------------------------------------------------------------------------
6872 // setting/unsetting _alwaysComputed flag to submeshes of inferior levels
6874 static void setAlwaysComputed( const bool isComputed,
6875 SMESH_subMesh* subMeshOfSolid)
6877 SMESH_subMeshIteratorPtr smIt =
6878 subMeshOfSolid->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
6879 while ( smIt->more() )
6881 SMESH_subMesh* sm = smIt->next();
6882 sm->SetIsAlwaysComputed( isComputed );
6884 subMeshOfSolid->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
6887 // --------------------------------------------------------------------------------
6888 // unsetting _alwaysComputed flag if "Cartesian_3D" was removed
6890 virtual void ProcessEvent(const int /*event*/,
6891 const int eventType,
6892 SMESH_subMesh* subMeshOfSolid,
6893 SMESH_subMeshEventListenerData* /*data*/,
6894 const SMESH_Hypothesis* /*hyp*/ = 0)
6896 if ( eventType == SMESH_subMesh::COMPUTE_EVENT )
6898 setAlwaysComputed( subMeshOfSolid->GetComputeState() == SMESH_subMesh::COMPUTE_OK,
6903 SMESH_Algo* algo3D = subMeshOfSolid->GetAlgo();
6904 if ( !algo3D || _algoName != algo3D->GetName() )
6905 setAlwaysComputed( false, subMeshOfSolid );
6909 // --------------------------------------------------------------------------------
6910 // set the event listener
6912 static void SetOn( SMESH_subMesh* subMeshOfSolid, const string& algoName )
6914 subMeshOfSolid->SetEventListener( new _EventListener( algoName ),
6919 }; // struct _EventListener
6923 //================================================================================
6925 * \brief Sets event listener to submeshes if necessary
6926 * \param subMesh - submesh where algo is set
6927 * This method is called when a submesh gets HYP_OK algo_state.
6928 * After being set, event listener is notified on each event of a submesh.
6930 //================================================================================
6932 void StdMeshers_Cartesian_3D::SetEventListener(SMESH_subMesh* subMesh)
6934 _EventListener::SetOn( subMesh, GetName() );
6937 //================================================================================
6939 * \brief Set _alwaysComputed flag to submeshes of inferior levels to avoid their computing
6941 //================================================================================
6943 void StdMeshers_Cartesian_3D::setSubmeshesComputed(SMESH_Mesh& theMesh,
6944 const TopoDS_Shape& theShape)
6946 for ( TopExp_Explorer soExp( theShape, TopAbs_SOLID ); soExp.More(); soExp.Next() )
6947 _EventListener::setAlwaysComputed( true, theMesh.GetSubMesh( soExp.Current() ));