1 // Copyright (C) 2007-2023 CEA, EDF, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : StdMeshers_Cartesian_3D.cxx
25 #include "StdMeshers_Cartesian_3D.hxx"
26 #include "StdMeshers_CartesianParameters3D.hxx"
27 #include "StdMeshers_Cartesian_VL.hxx"
28 #include "StdMeshers_FaceSide.hxx"
29 #include "StdMeshers_ViscousLayers.hxx"
31 #include <ObjectPool.hxx>
32 #include <SMDS_LinearEdge.hxx>
33 #include <SMDS_MeshNode.hxx>
34 #include <SMDS_VolumeOfNodes.hxx>
35 #include <SMDS_VolumeTool.hxx>
36 #include <SMESHDS_Mesh.hxx>
37 #include <SMESH_Block.hxx>
38 #include <SMESH_Comment.hxx>
39 #include <SMESH_ControlsDef.hxx>
40 #include <SMESH_Mesh.hxx>
41 #include <SMESH_MeshAlgos.hxx>
42 #include <SMESH_MeshEditor.hxx>
43 #include <SMESH_MesherHelper.hxx>
44 #include <SMESH_subMesh.hxx>
45 #include <SMESH_subMeshEventListener.hxx>
47 #include <utilities.h>
48 #include <Utils_ExceptHandlers.hxx>
50 #include <GEOMUtils.hxx>
52 #include <BRepAdaptor_Curve.hxx>
53 #include <BRepAdaptor_Surface.hxx>
54 #include <BRepBndLib.hxx>
55 #include <BRepBuilderAPI_Copy.hxx>
56 #include <BRepBuilderAPI_MakeFace.hxx>
57 #include <BRepTools.hxx>
58 #include <BRepTopAdaptor_FClass2d.hxx>
59 #include <BRep_Builder.hxx>
60 #include <BRep_Tool.hxx>
61 #include <Bnd_B3d.hxx>
62 #include <Bnd_Box.hxx>
64 #include <GCPnts_UniformDeflection.hxx>
65 #include <Geom2d_BSplineCurve.hxx>
66 #include <Geom2d_BezierCurve.hxx>
67 #include <Geom2d_TrimmedCurve.hxx>
68 #include <GeomAPI_ProjectPointOnSurf.hxx>
69 #include <GeomLib.hxx>
70 #include <Geom_BSplineCurve.hxx>
71 #include <Geom_BSplineSurface.hxx>
72 #include <Geom_BezierCurve.hxx>
73 #include <Geom_BezierSurface.hxx>
74 #include <Geom_RectangularTrimmedSurface.hxx>
75 #include <Geom_TrimmedCurve.hxx>
76 #include <IntAna_IntConicQuad.hxx>
77 #include <IntAna_IntLinTorus.hxx>
78 #include <IntAna_Quadric.hxx>
79 #include <IntCurveSurface_TransitionOnCurve.hxx>
80 #include <IntCurvesFace_Intersector.hxx>
81 #include <Poly_Triangulation.hxx>
82 #include <Precision.hxx>
84 #include <TopExp_Explorer.hxx>
85 #include <TopLoc_Location.hxx>
86 #include <TopTools_DataMapOfShapeInteger.hxx>
87 #include <TopTools_IndexedMapOfShape.hxx>
88 #include <TopTools_MapOfShape.hxx>
90 #include <TopoDS_Compound.hxx>
91 #include <TopoDS_Face.hxx>
92 #include <TopoDS_TShape.hxx>
93 #include <gp_Cone.hxx>
94 #include <gp_Cylinder.hxx>
97 #include <gp_Pnt2d.hxx>
98 #include <gp_Sphere.hxx>
99 #include <gp_Torus.hxx>
103 #include <boost/container/flat_map.hpp>
106 // #define _MY_DEBUG_
113 // See https://docs.microsoft.com/en-gb/cpp/porting/modifying-winver-and-win32-winnt?view=vs-2019
114 // Windows 10 = 0x0A00
115 #define WINVER 0x0A00
116 #define _WIN32_WINNT 0x0A00
119 #include <tbb/parallel_for.h>
120 //#include <tbb/enumerable_thread_specific.h>
124 using namespace SMESH;
126 //=============================================================================
130 //=============================================================================
132 StdMeshers_Cartesian_3D::StdMeshers_Cartesian_3D(int hypId, SMESH_Gen * gen)
133 :SMESH_3D_Algo(hypId, gen)
135 _name = "Cartesian_3D";
136 _shapeType = (1 << TopAbs_SOLID); // 1 bit /shape type
137 _compatibleHypothesis.push_back( "CartesianParameters3D" );
138 _compatibleHypothesis.push_back( StdMeshers_ViscousLayers::GetHypType() );
140 _onlyUnaryInput = false; // to mesh all SOLIDs at once
141 _requireDiscreteBoundary = false; // 2D mesh not needed
142 _supportSubmeshes = false; // do not use any existing mesh
145 //=============================================================================
147 * Check presence of a hypothesis
149 //=============================================================================
151 bool StdMeshers_Cartesian_3D::CheckHypothesis (SMESH_Mesh& aMesh,
152 const TopoDS_Shape& aShape,
153 Hypothesis_Status& aStatus)
155 aStatus = SMESH_Hypothesis::HYP_MISSING;
157 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape, /*skipAux=*/false);
158 list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
159 if ( h == hyps.end())
165 _hypViscousLayers = nullptr;
166 _isComputeOffset = false;
168 for ( ; h != hyps.end(); ++h )
170 if ( !_hyp && ( _hyp = dynamic_cast<const StdMeshers_CartesianParameters3D*>( *h )))
172 aStatus = _hyp->IsDefined() ? HYP_OK : HYP_BAD_PARAMETER;
176 _hypViscousLayers = dynamic_cast<const StdMeshers_ViscousLayers*>( *h );
180 return aStatus == HYP_OK;
186 * \brief Temporary mesh to hold
188 struct TmpMesh: public SMESH_Mesh
191 _isShapeToMesh = (_id = 0);
192 _meshDS = new SMESHDS_Mesh( _id, true );
196 typedef int TGeomID; // IDs of sub-shapes
197 typedef TopTools_ShapeMapHasher TShapeHasher; // non-oriented shape hasher
198 typedef std::array< int, 3 > TIJK;
200 const TGeomID theUndefID = 1e+9;
202 //=============================================================================
203 // Definitions of internal utils
204 // --------------------------------------------------------------------------
206 Trans_TANGENT = IntCurveSurface_Tangent,
207 Trans_IN = IntCurveSurface_In,
208 Trans_OUT = IntCurveSurface_Out,
210 Trans_INTERNAL // for INTERNAL FACE
212 // --------------------------------------------------------------------------
214 * \brief Sub-entities of a FACE neighboring its concave VERTEX.
215 * Help to avoid linking nodes on EDGEs that seem connected
216 * by the concave FACE but the link actually lies outside the FACE
220 TGeomID _concaveFace;
221 TGeomID _edge1, _edge2;
223 ConcaveFace( int f=0, int e1=0, int e2=0, int v1=0, int v2=0 )
224 : _concaveFace(f), _edge1(e1), _edge2(e2), _v1(v1), _v2(v2) {}
225 bool HasEdge( TGeomID edge ) const { return edge == _edge1 || edge == _edge2; }
226 bool HasVertex( TGeomID v ) const { return v == _v1 || v == _v2; }
227 void SetEdge( TGeomID edge ) { ( _edge1 ? _edge2 : _edge1 ) = edge; }
228 void SetVertex( TGeomID v ) { ( _v1 ? _v2 : _v1 ) = v; }
230 typedef NCollection_DataMap< TGeomID, ConcaveFace > TConcaveVertex2Face;
231 // --------------------------------------------------------------------------
233 * \brief Container of IDs of SOLID sub-shapes
235 class Solid // sole SOLID contains all sub-shapes
237 TGeomID _id; // SOLID id
238 bool _hasInternalFaces;
239 TConcaveVertex2Face _concaveVertex; // concave VERTEX -> ConcaveFace
242 virtual bool Contains( TGeomID /*subID*/ ) const { return true; }
243 virtual bool ContainsAny( const vector< TGeomID>& /*subIDs*/ ) const { return true; }
244 virtual TopAbs_Orientation Orientation( const TopoDS_Shape& s ) const { return s.Orientation(); }
245 virtual bool IsOutsideOriented( TGeomID /*faceID*/ ) const { return true; }
246 void SetID( TGeomID id ) { _id = id; }
247 TGeomID ID() const { return _id; }
248 void SetHasInternalFaces( bool has ) { _hasInternalFaces = has; }
249 bool HasInternalFaces() const { return _hasInternalFaces; }
250 void SetConcave( TGeomID V, TGeomID F, TGeomID E1, TGeomID E2, TGeomID V1, TGeomID V2 )
251 { _concaveVertex.Bind( V, ConcaveFace{ F, E1, E2, V1, V2 }); }
252 bool HasConcaveVertex() const { return !_concaveVertex.IsEmpty(); }
253 const ConcaveFace* GetConcave( TGeomID V ) const { return _concaveVertex.Seek( V ); }
255 // --------------------------------------------------------------------------
256 class OneOfSolids : public Solid
258 TColStd_MapOfInteger _subIDs;
259 TopTools_MapOfShape _faces; // keep FACE orientation
260 TColStd_MapOfInteger _outFaceIDs; // FACEs of shape_to_mesh oriented outside the SOLID
262 void Init( const TopoDS_Shape& solid,
263 TopAbs_ShapeEnum subType,
264 const SMESHDS_Mesh* mesh );
265 virtual bool Contains( TGeomID i ) const { return i == ID() || _subIDs.Contains( i ); }
266 virtual bool ContainsAny( const vector< TGeomID>& subIDs ) const
268 for ( size_t i = 0; i < subIDs.size(); ++i ) if ( Contains( subIDs[ i ])) return true;
271 virtual TopAbs_Orientation Orientation( const TopoDS_Shape& face ) const
273 const TopoDS_Shape& sInMap = const_cast< OneOfSolids* >(this)->_faces.Added( face );
274 return sInMap.Orientation();
276 virtual bool IsOutsideOriented( TGeomID faceID ) const
278 return faceID == 0 || _outFaceIDs.Contains( faceID );
281 // --------------------------------------------------------------------------
283 * \brief Hold a vector of TGeomID and clear it at destruction
285 class GeomIDVecHelder
287 typedef std::vector< TGeomID > TVector;
288 const TVector& myVec;
292 GeomIDVecHelder( const TVector& idVec, bool isOwner ): myVec( idVec ), myOwn( isOwner ) {}
293 GeomIDVecHelder( const GeomIDVecHelder& holder ): myVec( holder.myVec ), myOwn( holder.myOwn )
295 const_cast< bool& >( holder.myOwn ) = false;
297 ~GeomIDVecHelder() { if ( myOwn ) const_cast<TVector&>( myVec ).clear(); }
298 size_t size() const { return myVec.size(); }
299 TGeomID operator[]( size_t i ) const { return i < size() ? myVec[i] : theUndefID; }
300 bool operator==( const GeomIDVecHelder& other ) const { return myVec == other.myVec; }
301 bool contain( const TGeomID& id ) const {
302 return std::find( myVec.begin(), myVec.end(), id ) != myVec.end();
304 TGeomID otherThan( const TGeomID& id ) const {
305 for ( const TGeomID& id2 : myVec )
310 TGeomID oneCommon( const GeomIDVecHelder& other ) const {
311 TGeomID common = theUndefID;
312 for ( const TGeomID& id : myVec )
313 if ( other.contain( id ))
315 if ( common != theUndefID )
322 // --------------------------------------------------------------------------
328 TopoDS_Shape _mainShape;
329 vector< vector< TGeomID > > _solidIDsByShapeID;// V/E/F ID -> SOLID IDs
331 map< TGeomID, OneOfSolids > _solidByID;
332 TColStd_MapOfInteger _boundaryFaces; // FACEs on boundary of mesh->ShapeToMesh()
333 TColStd_MapOfInteger _strangeEdges; // EDGEs shared by strange FACEs
334 TGeomID _extIntFaceID; // pseudo FACE - extension of INTERNAL FACE
336 TopTools_DataMapOfShapeInteger _shape2NbNodes; // nb of pre-existing nodes on shapes
338 Controls::ElementsOnShape _edgeClassifier;
339 Controls::ElementsOnShape _vertexClassifier;
341 bool IsOneSolid() const { return _solidByID.size() < 2; }
342 GeomIDVecHelder GetSolidIDsByShapeID( const vector< TGeomID >& shapeIDs ) const;
344 // --------------------------------------------------------------------------
346 * \brief Common data of any intersection between a Grid and a shape
348 struct B_IntersectPoint
350 mutable const SMDS_MeshNode* _node;
351 mutable vector< TGeomID > _faceIDs;
353 B_IntersectPoint(): _node(NULL) {}
354 bool Add( const vector< TGeomID >& fIDs, const SMDS_MeshNode* n=0 ) const;
355 TGeomID HasCommonFace( const B_IntersectPoint * other, TGeomID avoidFace=-1 ) const;
356 size_t GetCommonFaces( const B_IntersectPoint * other, TGeomID * commonFaces ) const;
357 bool IsOnFace( TGeomID faceID ) const;
358 virtual ~B_IntersectPoint() {}
360 // --------------------------------------------------------------------------
362 * \brief Data of intersection between a GridLine and a TopoDS_Face
364 struct F_IntersectPoint : public B_IntersectPoint
368 mutable Transition _transition;
369 mutable size_t _indexOnLine;
371 bool operator< ( const F_IntersectPoint& o ) const { return _paramOnLine < o._paramOnLine; }
373 // --------------------------------------------------------------------------
375 * \brief Data of intersection between GridPlanes and a TopoDS_EDGE
377 struct E_IntersectPoint : public B_IntersectPoint
381 TGeomID _shapeID; // ID of EDGE or VERTEX
383 // --------------------------------------------------------------------------
385 * \brief A line of the grid and its intersections with 2D geometry
390 double _length; // line length
391 multiset< F_IntersectPoint > _intPoints;
393 void RemoveExcessIntPoints( const double tol );
394 TGeomID GetSolidIDBefore( multiset< F_IntersectPoint >::iterator ip,
395 const TGeomID prevID,
396 const Geometry& geom);
398 // --------------------------------------------------------------------------
400 * \brief Planes of the grid used to find intersections of an EDGE with a hexahedron
405 vector< gp_XYZ > _origins; // origin points of all planes in one direction
406 vector< double > _zProjs; // projections of origins to _zNorm
408 // --------------------------------------------------------------------------
410 * \brief Iterator on the parallel grid lines of one direction
416 size_t _iVar1, _iVar2, _iConst;
417 string _name1, _name2, _nameConst;
419 LineIndexer( size_t sz1, size_t sz2, size_t sz3,
420 size_t iv1, size_t iv2, size_t iConst,
421 const string& nv1, const string& nv2, const string& nConst )
423 _size[0] = sz1; _size[1] = sz2; _size[2] = sz3;
424 _curInd[0] = _curInd[1] = _curInd[2] = 0;
425 _iVar1 = iv1; _iVar2 = iv2; _iConst = iConst;
426 _name1 = nv1; _name2 = nv2; _nameConst = nConst;
429 size_t I() const { return _curInd[0]; }
430 size_t J() const { return _curInd[1]; }
431 size_t K() const { return _curInd[2]; }
432 void SetIJK( size_t i, size_t j, size_t k )
434 _curInd[0] = i; _curInd[1] = j; _curInd[2] = k;
436 void SetLineIndex(size_t i)
438 _curInd[_iVar2] = i / _size[_iVar1];
439 _curInd[_iVar1] = i % _size[_iVar1];
443 if ( ++_curInd[_iVar1] == _size[_iVar1] )
444 _curInd[_iVar1] = 0, ++_curInd[_iVar2];
446 bool More() const { return _curInd[_iVar2] < _size[_iVar2]; }
447 size_t LineIndex () const { return _curInd[_iVar1] + _curInd[_iVar2]* _size[_iVar1]; }
448 size_t LineIndex10 () const { return (_curInd[_iVar1] + 1 ) + _curInd[_iVar2]* _size[_iVar1]; }
449 size_t LineIndex01 () const { return _curInd[_iVar1] + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
450 size_t LineIndex11 () const { return (_curInd[_iVar1] + 1 ) + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
451 void SetIndexOnLine (size_t i) { _curInd[ _iConst ] = i; }
452 bool IsValidIndexOnLine (size_t i) const { return i < _size[ _iConst ]; }
453 size_t NbLines() const { return _size[_iVar1] * _size[_iVar2]; }
455 struct FaceGridIntersector;
456 // --------------------------------------------------------------------------
458 * \brief Container of GridLine's
462 vector< double > _coords[3]; // coordinates of grid nodes
463 gp_XYZ _axes [3]; // axis directions
464 vector< GridLine > _lines [3]; // in 3 directions
465 double _tol, _minCellSize;
467 gp_Mat _invB; // inverted basis of _axes
469 // index shift within _nodes of nodes of a cell from the 1st node
472 vector< const SMDS_MeshNode* > _nodes; // mesh nodes at grid nodes
473 vector< const F_IntersectPoint* > _gridIntP; // grid node intersection with geometry
474 ObjectPool< E_IntersectPoint > _edgeIntPool; // intersections with EDGEs
475 ObjectPool< F_IntersectPoint > _extIntPool; // intersections with extended INTERNAL FACEs
476 //list< E_IntersectPoint > _edgeIntP; // intersections with EDGEs
481 bool _toConsiderInternalFaces;
482 bool _toUseThresholdForInternalFaces;
483 double _sizeThreshold;
485 SMESH_MesherHelper* _helper;
487 size_t CellIndex( size_t i, size_t j, size_t k ) const
489 return i + j*(_coords[0].size()-1) + k*(_coords[0].size()-1)*(_coords[1].size()-1);
491 size_t NodeIndex( size_t i, size_t j, size_t k ) const
493 return i + j*_coords[0].size() + k*_coords[0].size()*_coords[1].size();
495 size_t NodeIndex( const TIJK& ijk ) const
497 return NodeIndex( ijk[0], ijk[1], ijk[2] );
499 size_t NodeIndexDX() const { return 1; }
500 size_t NodeIndexDY() const { return _coords[0].size(); }
501 size_t NodeIndexDZ() const { return _coords[0].size() * _coords[1].size(); }
503 LineIndexer GetLineIndexer(size_t iDir) const;
504 size_t GetLineDir( const GridLine* line, size_t & index ) const;
506 E_IntersectPoint* Add( const E_IntersectPoint& ip )
508 E_IntersectPoint* eip = _edgeIntPool.getNew();
512 void Remove( E_IntersectPoint* eip ) { _edgeIntPool.destroy( eip ); }
514 TGeomID ShapeID( const TopoDS_Shape& s ) const;
515 const TopoDS_Shape& Shape( TGeomID id ) const;
516 TopAbs_ShapeEnum ShapeType( TGeomID id ) const { return Shape(id).ShapeType(); }
517 void InitGeometry( const TopoDS_Shape& theShape );
518 void InitClassifier( const TopoDS_Shape& mainShape,
519 TopAbs_ShapeEnum shapeType,
520 Controls::ElementsOnShape& classifier );
521 void GetEdgesToImplement( map< TGeomID, vector< TGeomID > > & edge2faceMap,
522 const TopoDS_Shape& shape,
523 const vector< TopoDS_Shape >& faces );
524 void SetSolidFather( const TopoDS_Shape& s, const TopoDS_Shape& theShapeToMesh );
525 bool IsShared( TGeomID faceID ) const;
526 bool IsAnyShared( const std::vector< TGeomID >& faceIDs ) const;
527 bool IsInternal( TGeomID faceID ) const {
528 return ( faceID == PseudoIntExtFaceID() ||
529 Shape( faceID ).Orientation() == TopAbs_INTERNAL ); }
530 bool IsSolid( TGeomID shapeID ) const {
531 if ( _geometry.IsOneSolid() ) return _geometry._soleSolid.ID() == shapeID;
532 else return _geometry._solidByID.count( shapeID ); }
533 bool IsStrangeEdge( TGeomID id ) const { return _geometry._strangeEdges.Contains( id ); }
534 TGeomID PseudoIntExtFaceID() const { return _geometry._extIntFaceID; }
535 Solid* GetSolid( TGeomID solidID = 0 );
536 Solid* GetOneOfSolids( TGeomID solidID );
537 const vector< TGeomID > & GetSolidIDs( TGeomID subShapeID ) const;
538 bool IsCorrectTransition( TGeomID faceID, const Solid* solid );
539 bool IsBoundaryFace( TGeomID face ) const { return _geometry._boundaryFaces.Contains( face ); }
540 void SetOnShape( const SMDS_MeshNode* n, const F_IntersectPoint& ip,
541 TopoDS_Vertex* vertex = nullptr, bool unset = false );
542 void UpdateFacesOfVertex( const B_IntersectPoint& ip, const TopoDS_Vertex& vertex );
543 bool IsToCheckNodePos() const { return !_toAddEdges && _toCreateFaces; }
544 bool IsToRemoveExcessEntities() const { return !_toAddEdges; }
546 void SetCoordinates(const vector<double>& xCoords,
547 const vector<double>& yCoords,
548 const vector<double>& zCoords,
549 const double* axesDirs,
550 const Bnd_Box& bndBox );
551 void ComputeUVW(const gp_XYZ& p, double uvw[3]);
552 void ComputeNodes(SMESH_MesherHelper& helper);
554 // --------------------------------------------------------------------------
556 * \brief Return cells sharing a link
558 struct CellsAroundLink
566 CellsAroundLink( Grid* grid, int iDir ):
568 _dInd{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} },
569 _nbCells{ grid->_coords[0].size() - 1,
570 grid->_coords[1].size() - 1,
571 grid->_coords[2].size() - 1 },
574 const int iDirOther[3][2] = {{ 1,2 },{ 0,2 },{ 0,1 }};
575 _dInd[1][ iDirOther[iDir][0] ] = -1;
576 _dInd[2][ iDirOther[iDir][1] ] = -1;
577 _dInd[3][ iDirOther[iDir][0] ] = -1; _dInd[3][ iDirOther[iDir][1] ] = -1;
579 void Init( int i, int j, int k, int link12 = 0 )
582 _i = i - _dInd[iL][0];
583 _j = j - _dInd[iL][1];
584 _k = k - _dInd[iL][2];
586 bool GetCell( int iL, int& i, int& j, int& k, int& cellIndex, int& linkIndex )
588 i = _i + _dInd[iL][0];
589 j = _j + _dInd[iL][1];
590 k = _k + _dInd[iL][2];
591 if ( i < 0 || i >= (int)_nbCells[0] ||
592 j < 0 || j >= (int)_nbCells[1] ||
593 k < 0 || k >= (int)_nbCells[2] )
595 cellIndex = _grid->CellIndex( i,j,k );
596 linkIndex = iL + _iDir * 4;
600 // --------------------------------------------------------------------------
602 * \brief Intersector of TopoDS_Face with all GridLine's
604 struct FaceGridIntersector
610 IntCurvesFace_Intersector* _surfaceInt;
611 vector< std::pair< GridLine*, F_IntersectPoint > > _intersections;
613 FaceGridIntersector(): _grid(0), _surfaceInt(0) {}
616 void StoreIntersections()
618 for ( size_t i = 0; i < _intersections.size(); ++i )
620 multiset< F_IntersectPoint >::iterator ip =
621 _intersections[i].first->_intPoints.insert( _intersections[i].second );
622 ip->_faceIDs.reserve( 1 );
623 ip->_faceIDs.push_back( _faceID );
626 const Bnd_Box& GetFaceBndBox()
628 GetCurveFaceIntersector();
631 IntCurvesFace_Intersector* GetCurveFaceIntersector()
635 _surfaceInt = new IntCurvesFace_Intersector( _face, Precision::PConfusion() );
636 _bndBox = _surfaceInt->Bounding();
637 if ( _bndBox.IsVoid() )
638 BRepBndLib::Add (_face, _bndBox);
642 bool IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const;
644 // --------------------------------------------------------------------------
646 * \brief Intersector of a surface with a GridLine
648 struct FaceLineIntersector
651 double _u, _v, _w; // params on the face and the line
652 Transition _transition; // transition at intersection (see IntCurveSurface.cdl)
653 Transition _transIn, _transOut; // IN and OUT transitions depending of face orientation
656 gp_Cylinder _cylinder;
660 IntCurvesFace_Intersector* _surfaceInt;
662 vector< F_IntersectPoint > _intPoints;
664 void IntersectWithPlane (const GridLine& gridLine);
665 void IntersectWithCylinder(const GridLine& gridLine);
666 void IntersectWithCone (const GridLine& gridLine);
667 void IntersectWithSphere (const GridLine& gridLine);
668 void IntersectWithTorus (const GridLine& gridLine);
669 void IntersectWithSurface (const GridLine& gridLine);
671 bool UVIsOnFace() const;
672 void addIntPoint(const bool toClassify=true);
673 bool isParamOnLineOK( const double linLength )
675 return -_tol < _w && _w < linLength + _tol;
677 FaceLineIntersector():_surfaceInt(0) {}
678 ~FaceLineIntersector() { if (_surfaceInt ) delete _surfaceInt; _surfaceInt = 0; }
680 // --------------------------------------------------------------------------
682 * \brief Class representing topology of the hexahedron and creating a mesh
683 * volume basing on analysis of hexahedron intersection with geometry
687 // --------------------------------------------------------------------------------
690 enum IsInternalFlag { IS_NOT_INTERNAL, IS_INTERNAL, IS_CUT_BY_INTERNAL_FACE };
691 // --------------------------------------------------------------------------------
692 struct _Node //!< node either at a hexahedron corner or at intersection
694 const SMDS_MeshNode* _node; // mesh node at hexahedron corner
695 const B_IntersectPoint* _intPoint;
696 const _Face* _usedInFace;
697 char _isInternalFlags;
699 _Node(const SMDS_MeshNode* n=0, const B_IntersectPoint* ip=0)
700 :_node(n), _intPoint(ip), _usedInFace(0), _isInternalFlags(0) {}
701 const SMDS_MeshNode* Node() const
702 { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
703 const E_IntersectPoint* EdgeIntPnt() const
704 { return static_cast< const E_IntersectPoint* >( _intPoint ); }
705 const F_IntersectPoint* FaceIntPnt() const
706 { return static_cast< const F_IntersectPoint* >( _intPoint ); }
707 const vector< TGeomID >& faces() const { return _intPoint->_faceIDs; }
708 TGeomID face(size_t i) const { return _intPoint->_faceIDs[ i ]; }
709 void SetInternal( IsInternalFlag intFlag ) { _isInternalFlags |= intFlag; }
710 bool IsCutByInternal() const { return _isInternalFlags & IS_CUT_BY_INTERNAL_FACE; }
711 bool IsUsedInFace( const _Face* polygon = 0 )
713 return polygon ? ( _usedInFace == polygon ) : bool( _usedInFace );
715 TGeomID IsLinked( const B_IntersectPoint* other,
716 TGeomID avoidFace=-1 ) const // returns id of a common face
718 return _intPoint ? _intPoint->HasCommonFace( other, avoidFace ) : 0;
720 bool IsOnFace( TGeomID faceID ) const // returns true if faceID is found
722 return _intPoint ? _intPoint->IsOnFace( faceID ) : false;
724 size_t GetCommonFaces( const B_IntersectPoint * other, TGeomID* common ) const
726 return _intPoint && other ? _intPoint->GetCommonFaces( other, common ) : 0;
730 if ( const SMDS_MeshNode* n = Node() )
731 return SMESH_NodeXYZ( n );
732 if ( const E_IntersectPoint* eip =
733 dynamic_cast< const E_IntersectPoint* >( _intPoint ))
735 return gp_Pnt( 1e100, 0, 0 );
737 TGeomID ShapeID() const
739 if ( const E_IntersectPoint* eip = dynamic_cast< const E_IntersectPoint* >( _intPoint ))
740 return eip->_shapeID;
743 void Add( const E_IntersectPoint* ip )
745 // Possible cases before Add(ip):
746 /// 1) _node != 0 --> _Node at hex corner ( _intPoint == 0 || _intPoint._node == 0 )
747 /// 2) _node == 0 && _intPoint._node != 0 --> link intersected by FACE
748 /// 3) _node == 0 && _intPoint._node == 0 --> _Node at EDGE intersection
750 // If ip is added in cases 1) and 2) _node position must be changed to ip._shapeID
751 // at creation of elements
752 // To recognize this case, set _intPoint._node = Node()
753 const SMDS_MeshNode* node = Node();
758 ip->Add( _intPoint->_faceIDs );
762 _node = _intPoint->_node = node;
765 // --------------------------------------------------------------------------------
766 struct _Link // link connecting two _Node's
769 _Face* _faces[2]; // polygons sharing a link
770 vector< const F_IntersectPoint* > _fIntPoints; // GridLine intersections with FACEs
771 vector< _Node* > _fIntNodes; // _Node's at _fIntPoints
772 vector< _Link > _splits;
773 _Link(): _faces{ 0, 0 } {}
775 // --------------------------------------------------------------------------------
780 _OrientedLink( _Link* link=0, bool reverse=false ): _link(link), _reverse(reverse) {}
781 void Reverse() { _reverse = !_reverse; }
782 size_t NbResultLinks() const { return _link->_splits.size(); }
783 _OrientedLink ResultLink(int i) const
785 return _OrientedLink(&_link->_splits[_reverse ? NbResultLinks()-i-1 : i],_reverse);
787 _Node* FirstNode() const { return _link->_nodes[ _reverse ]; }
788 _Node* LastNode() const { return _link->_nodes[ !_reverse ]; }
789 operator bool() const { return _link; }
790 vector< TGeomID > GetNotUsedFace(const set<TGeomID>& usedIDs ) const // returns supporting FACEs
792 vector< TGeomID > faces;
793 const B_IntersectPoint *ip0, *ip1;
794 if (( ip0 = _link->_nodes[0]->_intPoint ) &&
795 ( ip1 = _link->_nodes[1]->_intPoint ))
797 for ( size_t i = 0; i < ip0->_faceIDs.size(); ++i )
798 if ( ip1->IsOnFace ( ip0->_faceIDs[i] ) &&
799 !usedIDs.count( ip0->_faceIDs[i] ) )
800 faces.push_back( ip0->_faceIDs[i] );
804 bool HasEdgeNodes() const
806 return ( dynamic_cast< const E_IntersectPoint* >( _link->_nodes[0]->_intPoint ) ||
807 dynamic_cast< const E_IntersectPoint* >( _link->_nodes[1]->_intPoint ));
811 return !_link->_faces[0] ? 0 : 1 + bool( _link->_faces[1] );
813 void AddFace( _Face* f )
815 if ( _link->_faces[0] )
817 _link->_faces[1] = f;
821 _link->_faces[0] = f;
822 _link->_faces[1] = 0;
825 void RemoveFace( _Face* f )
827 if ( !_link->_faces[0] ) return;
829 if ( _link->_faces[1] == f )
831 _link->_faces[1] = 0;
833 else if ( _link->_faces[0] == f )
835 _link->_faces[0] = 0;
836 if ( _link->_faces[1] )
838 _link->_faces[0] = _link->_faces[1];
839 _link->_faces[1] = 0;
844 // --------------------------------------------------------------------------------
845 struct _SplitIterator //! set to _hexLinks splits on one side of INTERNAL FACEs
847 struct _Split // data of a link split
849 int _linkID; // hex link ID
851 int _iCheckIteration; // iteration where split is tried as Hexahedron split
852 _Link* _checkedSplit; // split set to hex links
853 bool _isUsed; // used in a volume
855 _Split( _Link & split, int iLink ):
856 _linkID( iLink ), _nodes{ split._nodes[0], split._nodes[1] },
857 _iCheckIteration( 0 ), _isUsed( false )
859 bool IsCheckedOrUsed( bool used ) const { return used ? _isUsed : _iCheckIteration > 0; }
862 std::vector< _Split > _splits;
866 std::vector< _Node* > _freeNodes; // nodes reached while composing a split set
868 _SplitIterator( _Link* hexLinks ):
869 _hexLinks( hexLinks ), _iterationNb(0), _nbChecked(0), _nbUsed(0)
871 _freeNodes.reserve( 12 );
872 _splits.reserve( 24 );
873 for ( int iL = 0; iL < 12; ++iL )
874 for ( size_t iS = 0; iS < _hexLinks[ iL ]._splits.size(); ++iS )
875 _splits.emplace_back( _hexLinks[ iL ]._splits[ iS ], iL );
878 bool More() const { return _nbUsed < _splits.size(); }
881 // --------------------------------------------------------------------------------
884 SMESH_Block::TShapeID _name;
885 vector< _OrientedLink > _links; // links on GridLine's
886 vector< _Link > _polyLinks; // links added to close a polygonal face
887 vector< _Node* > _eIntNodes; // nodes at intersection with EDGEs
889 _Face():_name( SMESH_Block::ID_NONE )
891 bool IsPolyLink( const _OrientedLink& ol )
893 return _polyLinks.empty() ? false :
894 ( &_polyLinks[0] <= ol._link && ol._link <= &_polyLinks.back() );
896 void AddPolyLink(_Node* n0, _Node* n1, _Face* faceToFindEqual=0)
898 if ( faceToFindEqual && faceToFindEqual != this ) {
899 for ( size_t iL = 0; iL < faceToFindEqual->_polyLinks.size(); ++iL )
900 if ( faceToFindEqual->_polyLinks[iL]._nodes[0] == n1 &&
901 faceToFindEqual->_polyLinks[iL]._nodes[1] == n0 )
904 ( _OrientedLink( & faceToFindEqual->_polyLinks[iL], /*reverse=*/true ));
911 _polyLinks.push_back( l );
912 _links.push_back( _OrientedLink( &_polyLinks.back() ));
915 // --------------------------------------------------------------------------------
916 struct _volumeDef // holder of nodes of a volume mesh element
922 const SMDS_MeshNode* _node; // mesh node at hexahedron corner
923 const B_IntersectPoint* _intPoint;
925 _nodeDef(): _node(0), _intPoint(0) {}
926 _nodeDef( _Node* n ): _node( n->_node), _intPoint( n->_intPoint ) {}
927 const SMDS_MeshNode* Node() const
928 { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
929 const E_IntersectPoint* EdgeIntPnt() const
930 { return static_cast< const E_IntersectPoint* >( _intPoint ); }
931 _ptr Ptr() const { return Node() ? (_ptr) Node() : (_ptr) EdgeIntPnt(); }
932 bool operator==(const _nodeDef& other ) const { return Ptr() == other.Ptr(); }
935 vector< _nodeDef > _nodes;
936 vector< int > _quantities;
937 _volumeDef* _next; // to store several _volumeDefs in a chain
940 const SMDS_MeshElement* _volume; // new volume
942 vector< SMESH_Block::TShapeID > _names; // name of side a polygon originates from
944 _volumeDef(): _next(0), _solidID(0), _size(0), _volume(0) {}
945 ~_volumeDef() { delete _next; }
946 _volumeDef( _volumeDef& other ):
947 _next(0), _solidID( other._solidID ), _size( other._size ), _volume( other._volume )
948 { _nodes.swap( other._nodes ); _quantities.swap( other._quantities ); other._volume = 0;
949 _names.swap( other._names ); }
951 size_t size() const { return 1 + ( _next ? _next->size() : 0 ); } // nb _volumeDef in a chain
952 _volumeDef* at(int index)
953 { return index == 0 ? this : ( _next ? _next->at(index-1) : _next ); }
955 void Set( _Node** nodes, int nb )
956 { _nodes.assign( nodes, nodes + nb ); }
958 void SetNext( _volumeDef* vd )
959 { if ( _next ) { _next->SetNext( vd ); } else { _next = vd; }}
961 bool IsEmpty() const { return (( _nodes.empty() ) &&
962 ( !_next || _next->IsEmpty() )); }
963 bool IsPolyhedron() const { return ( !_quantities.empty() ||
964 ( _next && !_next->_quantities.empty() )); }
967 struct _linkDef: public std::pair<_ptr,_ptr> // to join polygons in removeExcessSideDivision()
969 _nodeDef _node1;//, _node2;
970 mutable /*const */_linkDef *_prev, *_next;
973 _linkDef():_prev(0), _next(0) {}
975 void init( const _nodeDef& n1, const _nodeDef& n2, size_t iLoop )
977 _node1 = n1; //_node2 = n2;
981 if ( first > second ) std::swap( first, second );
983 void setNext( _linkDef* next )
991 // topology of a hexahedron
993 _Link _hexLinks [12];
996 // faces resulted from hexahedron intersection
997 vector< _Face > _polygons;
999 // intresections with EDGEs
1000 vector< const E_IntersectPoint* > _eIntPoints;
1002 // additional nodes created at intersection points
1003 vector< _Node > _intNodes;
1005 // nodes inside the hexahedron (at VERTEXes) refer to _intNodes
1006 vector< _Node* > _vIntNodes;
1008 // computed volume elements
1009 _volumeDef _volumeDefs;
1012 double _sideLength[3];
1013 int _nbCornerNodes, _nbFaceIntNodes, _nbBndNodes;
1014 int _origNodeInd; // index of _hexNodes[0] node within the _grid
1020 Hexahedron(Grid* grid);
1021 int MakeElements(SMESH_MesherHelper& helper,
1022 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
1023 void computeElements( const Solid* solid = 0, int solidIndex = -1 );
1026 Hexahedron(const Hexahedron& other, size_t i, size_t j, size_t k, int cellID );
1027 void init( size_t i, size_t j, size_t k, const Solid* solid=0 );
1028 void init( size_t i );
1029 void setIJK( size_t i );
1030 bool compute( const Solid* solid, const IsInternalFlag intFlag );
1031 size_t getSolids( TGeomID ids[] );
1032 bool isCutByInternalFace( IsInternalFlag & maxFlag );
1033 void addEdges(SMESH_MesherHelper& helper,
1034 vector< Hexahedron* >& intersectedHex,
1035 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
1036 gp_Pnt findIntPoint( double u1, double proj1, double u2, double proj2,
1037 double proj, BRepAdaptor_Curve& curve,
1038 const gp_XYZ& axis, const gp_XYZ& origin );
1039 int getEntity( const E_IntersectPoint* ip, int* facets, int& sub );
1040 bool addIntersection( const E_IntersectPoint* ip,
1041 vector< Hexahedron* >& hexes,
1042 int ijk[], int dIJK[] );
1043 bool isQuadOnFace( const size_t iQuad );
1044 bool findChain( _Node* n1, _Node* n2, _Face& quad, vector<_Node*>& chainNodes );
1045 bool closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const;
1046 bool findChainOnEdge( const vector< _OrientedLink >& splits,
1047 const _OrientedLink& prevSplit,
1048 const _OrientedLink& avoidSplit,
1049 const std::set< TGeomID > & concaveFaces,
1052 vector<_Node*>& chn);
1053 int addVolumes(SMESH_MesherHelper& helper );
1054 void addFaces( SMESH_MesherHelper& helper,
1055 const vector< const SMDS_MeshElement* > & boundaryVolumes );
1056 void addSegments( SMESH_MesherHelper& helper,
1057 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap );
1058 void getVolumes( vector< const SMDS_MeshElement* > & volumes );
1059 void getBoundaryElems( vector< const SMDS_MeshElement* > & boundaryVolumes );
1060 void removeExcessSideDivision(const vector< Hexahedron* >& allHexa);
1061 void removeExcessNodes(vector< Hexahedron* >& allHexa);
1062 void preventVolumesOverlapping();
1063 TGeomID getAnyFace() const;
1064 void cutByExtendedInternal( std::vector< Hexahedron* >& hexes,
1065 const TColStd_MapOfInteger& intEdgeIDs );
1066 gp_Pnt mostDistantInternalPnt( int hexIndex, const gp_Pnt& p1, const gp_Pnt& p2 );
1067 bool isOutPoint( _Link& link, int iP, SMESH_MesherHelper& helper, const Solid* solid ) const;
1068 void sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID face);
1069 bool isInHole() const;
1070 bool hasStrangeEdge() const;
1071 bool checkPolyhedronSize( bool isCutByInternalFace, double & volSize ) const;
1076 bool debugDumpLink( _Link* link );
1077 _Node* findEqualNode( vector< _Node* >& nodes,
1078 const E_IntersectPoint* ip,
1081 for ( size_t i = 0; i < nodes.size(); ++i )
1082 if ( nodes[i]->EdgeIntPnt() == ip ||
1083 nodes[i]->Point().SquareDistance( ip->_point ) <= tol2 )
1087 bool isCorner( const _Node* node ) const { return ( node >= &_hexNodes[0] &&
1088 node - &_hexNodes[0] < 8 ); }
1089 bool hasEdgesAround( const ConcaveFace* cf ) const;
1090 bool isImplementEdges() const { return _grid->_edgeIntPool.nbElements(); }
1091 bool isOutParam(const double uvw[3]) const;
1093 typedef boost::container::flat_map< TGeomID, size_t > TID2Nb;
1094 static void insertAndIncrement( TGeomID id, TID2Nb& id2nbMap )
1096 TID2Nb::value_type s0( id, 0 );
1097 TID2Nb::iterator id2nb = id2nbMap.insert( s0 ).first;
1100 }; // class Hexahedron
1103 // --------------------------------------------------------------------------
1105 * \brief Hexahedron computing volumes in one thread
1107 struct ParallelHexahedron
1109 vector< Hexahedron* >& _hexVec;
1110 ParallelHexahedron( vector< Hexahedron* >& hv ): _hexVec(hv) {}
1111 void operator() ( const tbb::blocked_range<size_t>& r ) const
1113 for ( size_t i = r.begin(); i != r.end(); ++i )
1114 if ( Hexahedron* hex = _hexVec[ i ] )
1115 hex->computeElements();
1118 // --------------------------------------------------------------------------
1120 * \brief Structure intersecting certain nb of faces with GridLine's in one thread
1122 struct ParallelIntersector
1124 vector< FaceGridIntersector >& _faceVec;
1125 ParallelIntersector( vector< FaceGridIntersector >& faceVec): _faceVec(faceVec){}
1126 void operator() ( const tbb::blocked_range<size_t>& r ) const
1128 for ( size_t i = r.begin(); i != r.end(); ++i )
1129 _faceVec[i].Intersect();
1134 //=============================================================================
1135 // Implementation of internal utils
1136 //=============================================================================
1138 * \brief adjust \a i to have \a val between values[i] and values[i+1]
1140 inline void locateValue( int & i, double val, const vector<double>& values,
1141 int& di, double tol )
1143 //val += values[0]; // input \a val is measured from 0.
1144 if ( i > (int) values.size()-2 )
1145 i = values.size()-2;
1147 while ( i+2 < (int) values.size() && val > values[ i+1 ])
1149 while ( i > 0 && val < values[ i ])
1152 if ( i > 0 && val - values[ i ] < tol )
1154 else if ( i+2 < (int) values.size() && values[ i+1 ] - val < tol )
1159 //=============================================================================
1161 * Return a vector of SOLIDS sharing given shapes
1163 GeomIDVecHelder Geometry::GetSolidIDsByShapeID( const vector< TGeomID >& theShapeIDs ) const
1165 if ( theShapeIDs.size() == 1 )
1166 return GeomIDVecHelder( _solidIDsByShapeID[ theShapeIDs[ 0 ]], /*owner=*/false );
1168 // look for an empty slot in _solidIDsByShapeID
1169 vector< TGeomID > * resultIDs = 0;
1170 for ( const vector< TGeomID >& vec : _solidIDsByShapeID )
1173 resultIDs = const_cast< vector< TGeomID > * >( & vec );
1176 // fill in resultIDs
1177 for ( const TGeomID& id : theShapeIDs )
1178 for ( const TGeomID& solid : _solidIDsByShapeID[ id ])
1180 if ( std::find( resultIDs->begin(), resultIDs->end(), solid ) == resultIDs->end() )
1181 resultIDs->push_back( solid );
1183 return GeomIDVecHelder( *resultIDs, /*owner=*/true );
1185 //=============================================================================
1187 * Remove coincident intersection points
1189 void GridLine::RemoveExcessIntPoints( const double tol )
1191 if ( _intPoints.size() < 2 ) return;
1193 set< Transition > tranSet;
1194 multiset< F_IntersectPoint >::iterator ip1, ip2 = _intPoints.begin();
1195 while ( ip2 != _intPoints.end() )
1199 while ( ip2 != _intPoints.end() && ip2->_paramOnLine - ip1->_paramOnLine <= tol )
1201 tranSet.insert( ip1->_transition );
1202 tranSet.insert( ip2->_transition );
1203 ip2->Add( ip1->_faceIDs );
1204 _intPoints.erase( ip1 );
1207 if ( tranSet.size() > 1 ) // points with different transition coincide
1209 bool isIN = tranSet.count( Trans_IN );
1210 bool isOUT = tranSet.count( Trans_OUT );
1211 if ( isIN && isOUT )
1212 (*ip1)._transition = Trans_TANGENT;
1214 (*ip1)._transition = isIN ? Trans_IN : Trans_OUT;
1218 //================================================================================
1220 * Return ID of SOLID for nodes before the given intersection point
1222 TGeomID GridLine::GetSolidIDBefore( multiset< F_IntersectPoint >::iterator ip,
1223 const TGeomID prevID,
1224 const Geometry& geom )
1226 if ( ip == _intPoints.begin() )
1229 if ( geom.IsOneSolid() )
1232 switch ( ip->_transition ) {
1233 case Trans_IN: isOut = true; break;
1234 case Trans_OUT: isOut = false; break;
1235 case Trans_TANGENT: isOut = ( prevID != 0 ); break;
1238 // singularity point (apex of a cone)
1239 multiset< F_IntersectPoint >::iterator ipBef = ip, ipAft = ++ip;
1240 if ( ipAft == _intPoints.end() )
1245 if ( ipBef->_transition != ipAft->_transition )
1246 isOut = ( ipBef->_transition == Trans_OUT );
1248 isOut = ( ipBef->_transition != Trans_OUT );
1252 case Trans_INTERNAL: isOut = false;
1255 return isOut ? 0 : geom._soleSolid.ID();
1258 GeomIDVecHelder solids = geom.GetSolidIDsByShapeID( ip->_faceIDs );
1261 if ( ip->_transition == Trans_INTERNAL )
1264 GeomIDVecHelder solidsBef = geom.GetSolidIDsByShapeID( ip->_faceIDs );
1266 if ( ip->_transition == Trans_IN ||
1267 ip->_transition == Trans_OUT )
1269 if ( solidsBef.size() == 1 )
1271 if ( solidsBef[0] == prevID )
1272 return ip->_transition == Trans_OUT ? 0 : solidsBef[0];
1274 return solidsBef[0];
1277 if ( solids.size() == 2 )
1279 if ( solids == solidsBef )
1280 return solids.contain( prevID ) ? solids.otherThan( prevID ) : theUndefID; // bos #29212
1282 return solids.oneCommon( solidsBef );
1285 if ( solidsBef.size() == 1 )
1286 return solidsBef[0];
1288 return solids.oneCommon( solidsBef );
1290 //================================================================================
1294 bool B_IntersectPoint::Add( const vector< TGeomID >& fIDs,
1295 const SMDS_MeshNode* n) const
1297 size_t prevNbF = _faceIDs.size();
1299 if ( _faceIDs.empty() )
1302 for ( size_t i = 0; i < fIDs.size(); ++i )
1304 vector< TGeomID >::iterator it =
1305 std::find( _faceIDs.begin(), _faceIDs.end(), fIDs[i] );
1306 if ( it == _faceIDs.end() )
1307 _faceIDs.push_back( fIDs[i] );
1312 return prevNbF < _faceIDs.size();
1314 //================================================================================
1316 * Return ID of a common face if any, else zero
1318 TGeomID B_IntersectPoint::HasCommonFace( const B_IntersectPoint * other, TGeomID avoidFace ) const
1321 for ( size_t i = 0; i < other->_faceIDs.size(); ++i )
1322 if ( avoidFace != other->_faceIDs[i] &&
1323 IsOnFace ( other->_faceIDs[i] ))
1324 return other->_faceIDs[i];
1327 //================================================================================
1329 * Return faces common with other point
1331 size_t B_IntersectPoint::GetCommonFaces( const B_IntersectPoint * other, TGeomID* common ) const
1336 if ( _faceIDs.size() > other->_faceIDs.size() )
1337 return other->GetCommonFaces( this, common );
1338 for ( const TGeomID& face : _faceIDs )
1339 if ( other->IsOnFace( face ))
1340 common[ nbComm++ ] = face;
1343 //================================================================================
1345 * Return \c true if \a faceID in in this->_faceIDs
1347 bool B_IntersectPoint::IsOnFace( TGeomID faceID ) const // returns true if faceID is found
1349 vector< TGeomID >::const_iterator it =
1350 std::find( _faceIDs.begin(), _faceIDs.end(), faceID );
1351 return ( it != _faceIDs.end() );
1353 //================================================================================
1355 * OneOfSolids initialization
1357 void OneOfSolids::Init( const TopoDS_Shape& solid,
1358 TopAbs_ShapeEnum subType,
1359 const SMESHDS_Mesh* mesh )
1361 SetID( mesh->ShapeToIndex( solid ));
1363 if ( subType == TopAbs_FACE )
1364 SetHasInternalFaces( false );
1366 for ( TopExp_Explorer sub( solid, subType ); sub.More(); sub.Next() )
1368 _subIDs.Add( mesh->ShapeToIndex( sub.Current() ));
1369 if ( subType == TopAbs_FACE )
1371 _faces.Add( sub.Current() );
1372 if ( sub.Current().Orientation() == TopAbs_INTERNAL )
1373 SetHasInternalFaces( true );
1375 TGeomID faceID = mesh->ShapeToIndex( sub.Current() );
1376 if ( sub.Current().Orientation() == TopAbs_INTERNAL ||
1377 sub.Current().Orientation() == mesh->IndexToShape( faceID ).Orientation() )
1378 _outFaceIDs.Add( faceID );
1382 //================================================================================
1384 * Return an iterator on GridLine's in a given direction
1386 LineIndexer Grid::GetLineIndexer(size_t iDir) const
1388 const size_t indices[] = { 1,2,0, 0,2,1, 0,1,2 };
1389 const string s [] = { "X", "Y", "Z" };
1390 LineIndexer li( _coords[0].size(), _coords[1].size(), _coords[2].size(),
1391 indices[iDir*3], indices[iDir*3+1], indices[iDir*3+2],
1392 s[indices[iDir*3]], s[indices[iDir*3+1]], s[indices[iDir*3+2]]);
1395 //================================================================================
1397 * Return direction [0,1,2] of a GridLine
1399 size_t Grid::GetLineDir( const GridLine* line, size_t & index ) const
1401 for ( size_t iDir = 0; iDir < 3; ++iDir )
1402 if ( &_lines[ iDir ][0] <= line && line <= &_lines[ iDir ].back() )
1404 index = line - &_lines[ iDir ][0];
1409 //=============================================================================
1411 * Creates GridLine's of the grid
1413 void Grid::SetCoordinates(const vector<double>& xCoords,
1414 const vector<double>& yCoords,
1415 const vector<double>& zCoords,
1416 const double* axesDirs,
1417 const Bnd_Box& shapeBox)
1419 _coords[0] = xCoords;
1420 _coords[1] = yCoords;
1421 _coords[2] = zCoords;
1423 _axes[0].SetCoord( axesDirs[0],
1426 _axes[1].SetCoord( axesDirs[3],
1429 _axes[2].SetCoord( axesDirs[6],
1432 _axes[0].Normalize();
1433 _axes[1].Normalize();
1434 _axes[2].Normalize();
1436 _invB.SetCols( _axes[0], _axes[1], _axes[2] );
1439 // compute tolerance
1440 _minCellSize = Precision::Infinite();
1441 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1443 for ( size_t i = 1; i < _coords[ iDir ].size(); ++i )
1445 double cellLen = _coords[ iDir ][ i ] - _coords[ iDir ][ i-1 ];
1446 if ( cellLen < _minCellSize )
1447 _minCellSize = cellLen;
1450 if ( _minCellSize < Precision::Confusion() )
1451 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1452 SMESH_Comment("Too small cell size: ") << _minCellSize );
1453 _tol = _minCellSize / 1000.;
1455 // attune grid extremities to shape bounding box
1457 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
1458 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
1459 double* cP[6] = { &_coords[0].front(), &_coords[1].front(), &_coords[2].front(),
1460 &_coords[0].back(), &_coords[1].back(), &_coords[2].back() };
1461 for ( int i = 0; i < 6; ++i )
1462 if ( fabs( sP[i] - *cP[i] ) < _tol )
1463 *cP[i] = sP[i];// + _tol/1000. * ( i < 3 ? +1 : -1 );
1465 for ( int iDir = 0; iDir < 3; ++iDir )
1467 if ( _coords[iDir][0] - sP[iDir] > _tol )
1469 _minCellSize = Min( _minCellSize, _coords[iDir][0] - sP[iDir] );
1470 _coords[iDir].insert( _coords[iDir].begin(), sP[iDir] + _tol/1000.);
1472 if ( sP[iDir+3] - _coords[iDir].back() > _tol )
1474 _minCellSize = Min( _minCellSize, sP[iDir+3] - _coords[iDir].back() );
1475 _coords[iDir].push_back( sP[iDir+3] - _tol/1000.);
1478 _tol = _minCellSize / 1000.;
1480 _origin = ( _coords[0][0] * _axes[0] +
1481 _coords[1][0] * _axes[1] +
1482 _coords[2][0] * _axes[2] );
1485 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1487 LineIndexer li = GetLineIndexer( iDir );
1488 _lines[iDir].resize( li.NbLines() );
1489 double len = _coords[ iDir ].back() - _coords[iDir].front();
1490 for ( ; li.More(); ++li )
1492 GridLine& gl = _lines[iDir][ li.LineIndex() ];
1493 gl._line.SetLocation( _coords[0][li.I()] * _axes[0] +
1494 _coords[1][li.J()] * _axes[1] +
1495 _coords[2][li.K()] * _axes[2] );
1496 gl._line.SetDirection( _axes[ iDir ]);
1501 //================================================================================
1503 * Return local ID of shape
1505 TGeomID Grid::ShapeID( const TopoDS_Shape& s ) const
1507 return _helper->GetMeshDS()->ShapeToIndex( s );
1509 //================================================================================
1511 * Return a shape by its local ID
1513 const TopoDS_Shape& Grid::Shape( TGeomID id ) const
1515 return _helper->GetMeshDS()->IndexToShape( id );
1517 //================================================================================
1519 * Initialize _geometry
1521 void Grid::InitGeometry( const TopoDS_Shape& theShapeToMesh )
1523 SMESH_Mesh* mesh = _helper->GetMesh();
1525 _geometry._mainShape = theShapeToMesh;
1526 _geometry._extIntFaceID = mesh->GetMeshDS()->MaxShapeIndex() * 100;
1527 _geometry._soleSolid.SetID( 0 );
1528 _geometry._soleSolid.SetHasInternalFaces( false );
1530 InitClassifier( theShapeToMesh, TopAbs_VERTEX, _geometry._vertexClassifier );
1531 InitClassifier( theShapeToMesh, TopAbs_EDGE , _geometry._edgeClassifier );
1533 TopExp_Explorer solidExp( theShapeToMesh, TopAbs_SOLID );
1535 bool isSeveralSolids = false;
1536 if ( _toConsiderInternalFaces ) // check nb SOLIDs
1539 isSeveralSolids = solidExp.More();
1540 _toConsiderInternalFaces = isSeveralSolids;
1543 if ( !isSeveralSolids ) // look for an internal FACE
1545 TopExp_Explorer fExp( theShapeToMesh, TopAbs_FACE );
1546 for ( ; fExp.More() && !_toConsiderInternalFaces; fExp.Next() )
1547 _toConsiderInternalFaces = ( fExp.Current().Orientation() == TopAbs_INTERNAL );
1549 _geometry._soleSolid.SetHasInternalFaces( _toConsiderInternalFaces );
1550 _geometry._soleSolid.SetID( ShapeID( solidExp.Current() ));
1552 else // fill Geometry::_solidByID
1554 for ( ; solidExp.More(); solidExp.Next() )
1556 OneOfSolids & solid = _geometry._solidByID[ ShapeID( solidExp.Current() )];
1557 solid.Init( solidExp.Current(), TopAbs_FACE, mesh->GetMeshDS() );
1558 solid.Init( solidExp.Current(), TopAbs_EDGE, mesh->GetMeshDS() );
1559 solid.Init( solidExp.Current(), TopAbs_VERTEX, mesh->GetMeshDS() );
1565 _geometry._soleSolid.SetID( ShapeID( solidExp.Current() ));
1568 if ( !_toCreateFaces )
1570 int nbSolidsGlobal = _helper->Count( mesh->GetShapeToMesh(), TopAbs_SOLID, false );
1571 int nbSolidsLocal = _helper->Count( theShapeToMesh, TopAbs_SOLID, false );
1572 _toCreateFaces = ( nbSolidsLocal < nbSolidsGlobal );
1575 TopTools_IndexedMapOfShape faces;
1576 TopExp::MapShapes( theShapeToMesh, TopAbs_FACE, faces );
1578 // find boundary FACEs on boundary of mesh->ShapeToMesh()
1579 if ( _toCreateFaces )
1580 for ( int i = 1; i <= faces.Size(); ++i )
1581 if ( faces(i).Orientation() != TopAbs_INTERNAL &&
1582 _helper->NbAncestors( faces(i), *mesh, TopAbs_SOLID ) == 1 )
1584 _geometry._boundaryFaces.Add( ShapeID( faces(i) ));
1587 if ( isSeveralSolids )
1588 for ( int i = 1; i <= faces.Size(); ++i )
1590 SetSolidFather( faces(i), theShapeToMesh );
1591 for ( TopExp_Explorer eExp( faces(i), TopAbs_EDGE ); eExp.More(); eExp.Next() )
1593 const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
1594 SetSolidFather( edge, theShapeToMesh );
1595 SetSolidFather( _helper->IthVertex( 0, edge ), theShapeToMesh );
1596 SetSolidFather( _helper->IthVertex( 1, edge ), theShapeToMesh );
1600 // fill in _geometry._shape2NbNodes == find already meshed sub-shapes
1601 _geometry._shape2NbNodes.Clear();
1602 if ( mesh->NbNodes() > 0 )
1604 for ( TopAbs_ShapeEnum type : { TopAbs_FACE, TopAbs_EDGE, TopAbs_VERTEX })
1605 for ( TopExp_Explorer exp( theShapeToMesh, type ); exp.More(); exp.Next() )
1607 if ( _geometry._shape2NbNodes.IsBound( exp.Current() ))
1609 if ( SMESHDS_SubMesh* sm = mesh->GetMeshDS()->MeshElements( exp.Current() ))
1610 if ( sm->NbNodes() > 0 )
1611 _geometry._shape2NbNodes.Bind( exp.Current(), sm->NbNodes() );
1615 // fill in Solid::_concaveVertex
1616 vector< TGeomID > soleSolidID( 1, _geometry._soleSolid.ID() );
1617 for ( int i = 1; i <= faces.Size(); ++i )
1619 const TopoDS_Face& F = TopoDS::Face( faces( i ));
1621 TSideVector wires = StdMeshers_FaceSide::GetFaceWires( F, *mesh, 0, error,
1622 nullptr, nullptr, false );
1623 for ( StdMeshers_FaceSidePtr& wire : wires )
1625 const int nbEdges = wire->NbEdges();
1626 if ( nbEdges < 2 && SMESH_Algo::isDegenerated( wire->Edge(0)))
1628 for ( int iE1 = 0; iE1 < nbEdges; ++iE1 )
1630 if ( SMESH_Algo::isDegenerated( wire->Edge( iE1 ))) continue;
1631 int iE2 = ( iE1 + 1 ) % nbEdges;
1632 while ( SMESH_Algo::isDegenerated( wire->Edge( iE2 )))
1633 iE2 = ( iE2 + 1 ) % nbEdges;
1634 TopoDS_Vertex V = wire->FirstVertex( iE2 );
1635 double angle = _helper->GetAngle( wire->Edge( iE1 ),
1636 wire->Edge( iE2 ), F, V );
1637 if ( angle < -5. * M_PI / 180. )
1639 TGeomID faceID = ShapeID( F );
1640 const vector< TGeomID > & solids =
1641 _geometry.IsOneSolid() ? soleSolidID : GetSolidIDs( faceID );
1642 for ( const TGeomID & solidID : solids )
1644 Solid* solid = GetSolid( solidID );
1645 TGeomID V1 = ShapeID( wire->FirstVertex( iE1 ));
1646 TGeomID V2 = ShapeID( wire->LastVertex ( iE2 ));
1647 solid->SetConcave( ShapeID( V ), faceID,
1648 wire->EdgeID( iE1 ), wire->EdgeID( iE2 ), V1, V2 );
1657 //================================================================================
1659 * Store ID of SOLID as father of its child shape ID
1661 void Grid::SetSolidFather( const TopoDS_Shape& s, const TopoDS_Shape& theShapeToMesh )
1663 if ( _geometry._solidIDsByShapeID.empty() )
1664 _geometry._solidIDsByShapeID.resize( _helper->GetMeshDS()->MaxShapeIndex() + 1 );
1666 vector< TGeomID > & solidIDs = _geometry._solidIDsByShapeID[ ShapeID( s )];
1667 if ( !solidIDs.empty() )
1669 solidIDs.reserve(2);
1670 PShapeIteratorPtr solidIt = _helper->GetAncestors( s,
1671 *_helper->GetMesh(),
1674 while ( const TopoDS_Shape* solid = solidIt->next() )
1675 solidIDs.push_back( ShapeID( *solid ));
1677 //================================================================================
1679 * Return IDs of solids given sub-shape belongs to
1681 const vector< TGeomID > & Grid::GetSolidIDs( TGeomID subShapeID ) const
1683 return _geometry._solidIDsByShapeID[ subShapeID ];
1685 //================================================================================
1687 * Check if a sub-shape belongs to several SOLIDs
1689 bool Grid::IsShared( TGeomID shapeID ) const
1691 return !_geometry.IsOneSolid() && ( _geometry._solidIDsByShapeID[ shapeID ].size() > 1 );
1693 //================================================================================
1695 * Check if any of FACEs belongs to several SOLIDs
1697 bool Grid::IsAnyShared( const std::vector< TGeomID >& faceIDs ) const
1699 for ( size_t i = 0; i < faceIDs.size(); ++i )
1700 if ( IsShared( faceIDs[ i ]))
1704 //================================================================================
1706 * Return Solid by ID
1708 Solid* Grid::GetSolid( TGeomID solidID )
1710 if ( !solidID || _geometry.IsOneSolid() || _geometry._solidByID.empty() )
1711 return & _geometry._soleSolid;
1713 return & _geometry._solidByID[ solidID ];
1715 //================================================================================
1717 * Return OneOfSolids by ID
1719 Solid* Grid::GetOneOfSolids( TGeomID solidID )
1721 map< TGeomID, OneOfSolids >::iterator is2s = _geometry._solidByID.find( solidID );
1722 if ( is2s != _geometry._solidByID.end() )
1723 return & is2s->second;
1725 return & _geometry._soleSolid;
1727 //================================================================================
1729 * Check if transition on given FACE is correct for a given SOLID
1731 bool Grid::IsCorrectTransition( TGeomID faceID, const Solid* solid )
1733 if ( _geometry.IsOneSolid() )
1736 const vector< TGeomID >& solidIDs = _geometry._solidIDsByShapeID[ faceID ];
1737 return solidIDs[0] == solid->ID();
1740 //================================================================================
1742 * Assign to geometry a node at FACE intersection
1743 * Return a found supporting VERTEX
1745 void Grid::SetOnShape( const SMDS_MeshNode* n, const F_IntersectPoint& ip,
1746 TopoDS_Vertex* vertex, bool unset )
1749 SMESHDS_Mesh* mesh = _helper->GetMeshDS();
1750 if ( ip._faceIDs.size() == 1 )
1752 mesh->SetNodeOnFace( n, ip._faceIDs[0], ip._u, ip._v );
1754 else if ( _geometry._vertexClassifier.IsSatisfy( n, &s ))
1756 if ( unset ) mesh->UnSetNodeOnShape( n );
1757 mesh->SetNodeOnVertex( n, TopoDS::Vertex( s ));
1759 *vertex = TopoDS::Vertex( s );
1761 else if ( _geometry._edgeClassifier.IsSatisfy( n, &s ))
1763 if ( unset ) mesh->UnSetNodeOnShape( n );
1764 mesh->SetNodeOnEdge( n, TopoDS::Edge( s ));
1766 else if ( ip._faceIDs.size() > 0 )
1768 mesh->SetNodeOnFace( n, ip._faceIDs[0], ip._u, ip._v );
1770 else if ( !unset && _geometry.IsOneSolid() )
1772 mesh->SetNodeInVolume( n, _geometry._soleSolid.ID() );
1775 //================================================================================
1777 * Fill in B_IntersectPoint::_faceIDs with all FACEs sharing a VERTEX
1779 void Grid::UpdateFacesOfVertex( const B_IntersectPoint& ip, const TopoDS_Vertex& vertex )
1781 if ( vertex.IsNull() )
1783 std::vector< int > faceID(1);
1784 PShapeIteratorPtr fIt = _helper->GetAncestors( vertex, *_helper->GetMesh(),
1785 TopAbs_FACE, & _geometry._mainShape );
1786 while ( const TopoDS_Shape* face = fIt->next() )
1788 faceID[ 0 ] = ShapeID( *face );
1792 //================================================================================
1794 * Initialize a classifier
1796 void Grid::InitClassifier( const TopoDS_Shape& mainShape,
1797 TopAbs_ShapeEnum shapeType,
1798 Controls::ElementsOnShape& classifier )
1800 TopTools_IndexedMapOfShape shapes;
1801 TopExp::MapShapes( mainShape, shapeType, shapes );
1803 TopoDS_Compound compound; BRep_Builder builder;
1804 builder.MakeCompound( compound );
1805 for ( int i = 1; i <= shapes.Size(); ++i )
1806 builder.Add( compound, shapes(i) );
1808 classifier.SetMesh( _helper->GetMeshDS() );
1809 //classifier.SetTolerance( _tol ); // _tol is not initialised
1810 classifier.SetShape( compound, SMDSAbs_Node );
1813 //================================================================================
1815 * Return EDGEs with FACEs to implement into the mesh
1817 void Grid::GetEdgesToImplement( map< TGeomID, vector< TGeomID > > & edge2faceIDsMap,
1818 const TopoDS_Shape& shape,
1819 const vector< TopoDS_Shape >& faces )
1821 // check if there are strange EDGEs
1822 TopTools_IndexedMapOfShape faceMap;
1823 TopExp::MapShapes( _helper->GetMesh()->GetShapeToMesh(), TopAbs_FACE, faceMap );
1824 int nbFacesGlobal = faceMap.Size();
1825 faceMap.Clear( false );
1826 TopExp::MapShapes( shape, TopAbs_FACE, faceMap );
1827 int nbFacesLocal = faceMap.Size();
1828 bool hasStrangeEdges = ( nbFacesGlobal > nbFacesLocal );
1829 if ( !_toAddEdges && !hasStrangeEdges )
1830 return; // no FACEs in contact with those meshed by other algo
1832 for ( size_t i = 0; i < faces.size(); ++i )
1834 _helper->SetSubShape( faces[i] );
1835 for ( TopExp_Explorer eExp( faces[i], TopAbs_EDGE ); eExp.More(); eExp.Next() )
1837 const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
1838 if ( hasStrangeEdges )
1840 bool hasStrangeFace = false;
1841 PShapeIteratorPtr faceIt = _helper->GetAncestors( edge, *_helper->GetMesh(), TopAbs_FACE);
1842 while ( const TopoDS_Shape* face = faceIt->next() )
1843 if (( hasStrangeFace = !faceMap.Contains( *face )))
1845 if ( !hasStrangeFace && !_toAddEdges )
1847 _geometry._strangeEdges.Add( ShapeID( edge ));
1848 _geometry._strangeEdges.Add( ShapeID( _helper->IthVertex( 0, edge )));
1849 _geometry._strangeEdges.Add( ShapeID( _helper->IthVertex( 1, edge )));
1851 if ( !SMESH_Algo::isDegenerated( edge ) &&
1852 !_helper->IsRealSeam( edge ))
1854 edge2faceIDsMap[ ShapeID( edge )].push_back( ShapeID( faces[i] ));
1861 //================================================================================
1863 * Computes coordinates of a point in the grid CS
1865 void Grid::ComputeUVW(const gp_XYZ& P, double UVW[3])
1867 gp_XYZ p = P * _invB;
1868 p.Coord( UVW[0], UVW[1], UVW[2] );
1870 //================================================================================
1874 void Grid::ComputeNodes(SMESH_MesherHelper& helper)
1876 // state of each node of the grid relative to the geometry
1877 const size_t nbGridNodes = _coords[0].size() * _coords[1].size() * _coords[2].size();
1878 vector< TGeomID > shapeIDVec( nbGridNodes, theUndefID );
1879 _nodes.resize( nbGridNodes, 0 );
1880 _gridIntP.resize( nbGridNodes, NULL );
1882 SMESHDS_Mesh* mesh = helper.GetMeshDS();
1884 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1886 LineIndexer li = GetLineIndexer( iDir );
1888 // find out a shift of node index while walking along a GridLine in this direction
1889 li.SetIndexOnLine( 0 );
1890 size_t nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1891 li.SetIndexOnLine( 1 );
1892 const size_t nShift = NodeIndex( li.I(), li.J(), li.K() ) - nIndex0;
1894 const vector<double> & coords = _coords[ iDir ];
1895 for ( ; li.More(); ++li ) // loop on lines in iDir
1897 li.SetIndexOnLine( 0 );
1898 nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1900 GridLine& line = _lines[ iDir ][ li.LineIndex() ];
1901 const gp_XYZ lineLoc = line._line.Location().XYZ();
1902 const gp_XYZ lineDir = line._line.Direction().XYZ();
1904 line.RemoveExcessIntPoints( _tol );
1905 multiset< F_IntersectPoint >& intPnts = line._intPoints;
1906 multiset< F_IntersectPoint >::iterator ip = intPnts.begin();
1908 // Create mesh nodes at intersections with geometry
1909 // and set OUT state of nodes between intersections
1911 TGeomID solidID = 0;
1912 const double* nodeCoord = & coords[0];
1913 const double* coord0 = nodeCoord;
1914 const double* coordEnd = coord0 + coords.size();
1915 double nodeParam = 0;
1916 for ( ; ip != intPnts.end(); ++ip )
1918 solidID = line.GetSolidIDBefore( ip, solidID, _geometry );
1920 // set OUT state or just skip IN nodes before ip
1921 if ( nodeParam < ip->_paramOnLine - _tol )
1923 while ( nodeParam < ip->_paramOnLine - _tol )
1925 TGeomID & nodeShapeID = shapeIDVec[ nIndex0 + nShift * ( nodeCoord-coord0 ) ];
1926 nodeShapeID = Min( solidID, nodeShapeID );
1927 if ( ++nodeCoord < coordEnd )
1928 nodeParam = *nodeCoord - *coord0;
1932 if ( nodeCoord == coordEnd ) break;
1934 // create a mesh node on a GridLine at ip if it does not coincide with a grid node
1935 if ( nodeParam > ip->_paramOnLine + _tol )
1937 gp_XYZ xyz = lineLoc + ip->_paramOnLine * lineDir;
1938 ip->_node = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1939 ip->_indexOnLine = nodeCoord-coord0-1;
1941 SetOnShape( ip->_node, *ip, & v );
1942 UpdateFacesOfVertex( *ip, v );
1944 // create a mesh node at ip coincident with a grid node
1947 int nodeIndex = nIndex0 + nShift * ( nodeCoord-coord0 );
1948 if ( !_nodes[ nodeIndex ] )
1950 gp_XYZ xyz = lineLoc + nodeParam * lineDir;
1951 _nodes [ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1952 //_gridIntP[ nodeIndex ] = & * ip;
1953 //SetOnShape( _nodes[ nodeIndex ], *ip );
1955 if ( _gridIntP[ nodeIndex ] )
1956 _gridIntP[ nodeIndex ]->Add( ip->_faceIDs );
1958 _gridIntP[ nodeIndex ] = & * ip;
1959 // ip->_node = _nodes[ nodeIndex ]; -- to differ from ip on links
1960 ip->_indexOnLine = nodeCoord-coord0;
1961 if ( ++nodeCoord < coordEnd )
1962 nodeParam = *nodeCoord - *coord0;
1965 // set OUT state to nodes after the last ip
1966 for ( ; nodeCoord < coordEnd; ++nodeCoord )
1967 shapeIDVec[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = 0;
1971 // Create mesh nodes at !OUT nodes of the grid
1973 for ( size_t z = 0; z < _coords[2].size(); ++z )
1974 for ( size_t y = 0; y < _coords[1].size(); ++y )
1975 for ( size_t x = 0; x < _coords[0].size(); ++x )
1977 size_t nodeIndex = NodeIndex( x, y, z );
1978 if ( !_nodes[ nodeIndex ] &&
1979 0 < shapeIDVec[ nodeIndex ] && shapeIDVec[ nodeIndex ] < theUndefID )
1981 gp_XYZ xyz = ( _coords[0][x] * _axes[0] +
1982 _coords[1][y] * _axes[1] +
1983 _coords[2][z] * _axes[2] );
1984 _nodes[ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1985 mesh->SetNodeInVolume( _nodes[ nodeIndex ], shapeIDVec[ nodeIndex ]);
1987 else if ( _nodes[ nodeIndex ] && _gridIntP[ nodeIndex ] /*&&
1988 !_nodes[ nodeIndex]->GetShapeID()*/ )
1991 SetOnShape( _nodes[ nodeIndex ], *_gridIntP[ nodeIndex ], & v );
1992 UpdateFacesOfVertex( *_gridIntP[ nodeIndex ], v );
1997 // check validity of transitions
1998 const char* trName[] = { "TANGENT", "IN", "OUT", "APEX" };
1999 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
2001 LineIndexer li = GetLineIndexer( iDir );
2002 for ( ; li.More(); ++li )
2004 multiset< F_IntersectPoint >& intPnts = _lines[ iDir ][ li.LineIndex() ]._intPoints;
2005 if ( intPnts.empty() ) continue;
2006 if ( intPnts.size() == 1 )
2008 if ( intPnts.begin()->_transition != Trans_TANGENT &&
2009 intPnts.begin()->_transition != Trans_APEX )
2010 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
2011 SMESH_Comment("Wrong SOLE transition of GridLine (")
2012 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
2013 << ") along " << li._nameConst
2014 << ": " << trName[ intPnts.begin()->_transition] );
2018 if ( intPnts.begin()->_transition == Trans_OUT )
2019 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
2020 SMESH_Comment("Wrong START transition of GridLine (")
2021 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
2022 << ") along " << li._nameConst
2023 << ": " << trName[ intPnts.begin()->_transition ]);
2024 if ( intPnts.rbegin()->_transition == Trans_IN )
2025 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
2026 SMESH_Comment("Wrong END transition of GridLine (")
2027 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
2028 << ") along " << li._nameConst
2029 << ": " << trName[ intPnts.rbegin()->_transition ]);
2038 //=============================================================================
2040 * Intersects TopoDS_Face with all GridLine's
2042 void FaceGridIntersector::Intersect()
2044 FaceLineIntersector intersector;
2045 intersector._surfaceInt = GetCurveFaceIntersector();
2046 intersector._tol = _grid->_tol;
2047 intersector._transOut = _face.Orientation() == TopAbs_REVERSED ? Trans_IN : Trans_OUT;
2048 intersector._transIn = _face.Orientation() == TopAbs_REVERSED ? Trans_OUT : Trans_IN;
2050 typedef void (FaceLineIntersector::* PIntFun )(const GridLine& gridLine);
2051 PIntFun interFunction;
2053 bool isDirect = true;
2054 BRepAdaptor_Surface surf( _face );
2055 switch ( surf.GetType() ) {
2057 intersector._plane = surf.Plane();
2058 interFunction = &FaceLineIntersector::IntersectWithPlane;
2059 isDirect = intersector._plane.Direct();
2061 case GeomAbs_Cylinder:
2062 intersector._cylinder = surf.Cylinder();
2063 interFunction = &FaceLineIntersector::IntersectWithCylinder;
2064 isDirect = intersector._cylinder.Direct();
2067 intersector._cone = surf.Cone();
2068 interFunction = &FaceLineIntersector::IntersectWithCone;
2069 //isDirect = intersector._cone.Direct();
2071 case GeomAbs_Sphere:
2072 intersector._sphere = surf.Sphere();
2073 interFunction = &FaceLineIntersector::IntersectWithSphere;
2074 isDirect = intersector._sphere.Direct();
2077 intersector._torus = surf.Torus();
2078 interFunction = &FaceLineIntersector::IntersectWithTorus;
2079 //isDirect = intersector._torus.Direct();
2082 interFunction = &FaceLineIntersector::IntersectWithSurface;
2085 std::swap( intersector._transOut, intersector._transIn );
2087 _intersections.clear();
2088 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
2090 if ( surf.GetType() == GeomAbs_Plane )
2092 // check if all lines in this direction are parallel to a plane
2093 if ( intersector._plane.Axis().IsNormal( _grid->_lines[iDir][0]._line.Position(),
2094 Precision::Angular()))
2096 // find out a transition, that is the same for all lines of a direction
2097 gp_Dir plnNorm = intersector._plane.Axis().Direction();
2098 gp_Dir lineDir = _grid->_lines[iDir][0]._line.Direction();
2099 intersector._transition =
2100 ( plnNorm * lineDir < 0 ) ? intersector._transIn : intersector._transOut;
2102 if ( surf.GetType() == GeomAbs_Cylinder )
2104 // check if all lines in this direction are parallel to a cylinder
2105 if ( intersector._cylinder.Axis().IsParallel( _grid->_lines[iDir][0]._line.Position(),
2106 Precision::Angular()))
2110 // intersect the grid lines with the face
2111 for ( size_t iL = 0; iL < _grid->_lines[iDir].size(); ++iL )
2113 GridLine& gridLine = _grid->_lines[iDir][iL];
2114 if ( _bndBox.IsOut( gridLine._line )) continue;
2116 intersector._intPoints.clear();
2117 (intersector.*interFunction)( gridLine ); // <- intersection with gridLine
2118 for ( size_t i = 0; i < intersector._intPoints.size(); ++i )
2119 _intersections.push_back( make_pair( &gridLine, intersector._intPoints[i] ));
2123 if ( _face.Orientation() == TopAbs_INTERNAL )
2125 for ( size_t i = 0; i < _intersections.size(); ++i )
2126 if ( _intersections[i].second._transition == Trans_IN ||
2127 _intersections[i].second._transition == Trans_OUT )
2129 _intersections[i].second._transition = Trans_INTERNAL;
2134 //================================================================================
2136 * Return true if (_u,_v) is on the face
2138 bool FaceLineIntersector::UVIsOnFace() const
2140 TopAbs_State state = _surfaceInt->ClassifyUVPoint(gp_Pnt2d( _u,_v ));
2141 return ( state == TopAbs_IN || state == TopAbs_ON );
2143 //================================================================================
2145 * Store an intersection if it is IN or ON the face
2147 void FaceLineIntersector::addIntPoint(const bool toClassify)
2149 if ( !toClassify || UVIsOnFace() )
2152 p._paramOnLine = _w;
2155 p._transition = _transition;
2156 _intPoints.push_back( p );
2159 //================================================================================
2161 * Intersect a line with a plane
2163 void FaceLineIntersector::IntersectWithPlane(const GridLine& gridLine)
2165 IntAna_IntConicQuad linPlane( gridLine._line, _plane, Precision::Angular());
2166 _w = linPlane.ParamOnConic(1);
2167 if ( isParamOnLineOK( gridLine._length ))
2169 ElSLib::Parameters(_plane, linPlane.Point(1) ,_u,_v);
2173 //================================================================================
2175 * Intersect a line with a cylinder
2177 void FaceLineIntersector::IntersectWithCylinder(const GridLine& gridLine)
2179 IntAna_IntConicQuad linCylinder( gridLine._line, _cylinder );
2180 if ( linCylinder.IsDone() && linCylinder.NbPoints() > 0 )
2182 _w = linCylinder.ParamOnConic(1);
2183 if ( linCylinder.NbPoints() == 1 )
2184 _transition = Trans_TANGENT;
2186 _transition = _w < linCylinder.ParamOnConic(2) ? _transIn : _transOut;
2187 if ( isParamOnLineOK( gridLine._length ))
2189 ElSLib::Parameters(_cylinder, linCylinder.Point(1) ,_u,_v);
2192 if ( linCylinder.NbPoints() > 1 )
2194 _w = linCylinder.ParamOnConic(2);
2195 if ( isParamOnLineOK( gridLine._length ))
2197 ElSLib::Parameters(_cylinder, linCylinder.Point(2) ,_u,_v);
2198 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
2204 //================================================================================
2206 * Intersect a line with a cone
2208 void FaceLineIntersector::IntersectWithCone (const GridLine& gridLine)
2210 IntAna_IntConicQuad linCone(gridLine._line,_cone);
2211 if ( !linCone.IsDone() ) return;
2213 gp_Vec du, dv, norm;
2214 for ( int i = 1; i <= linCone.NbPoints(); ++i )
2216 _w = linCone.ParamOnConic( i );
2217 if ( !isParamOnLineOK( gridLine._length )) continue;
2218 ElSLib::Parameters(_cone, linCone.Point(i) ,_u,_v);
2221 ElSLib::D1( _u, _v, _cone, P, du, dv );
2223 double normSize2 = norm.SquareMagnitude();
2224 if ( normSize2 > Precision::Angular() * Precision::Angular() )
2226 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
2227 cos /= sqrt( normSize2 );
2228 if ( cos < -Precision::Angular() )
2229 _transition = _transIn;
2230 else if ( cos > Precision::Angular() )
2231 _transition = _transOut;
2233 _transition = Trans_TANGENT;
2237 _transition = Trans_APEX;
2239 addIntPoint( /*toClassify=*/false);
2243 //================================================================================
2245 * Intersect a line with a sphere
2247 void FaceLineIntersector::IntersectWithSphere (const GridLine& gridLine)
2249 IntAna_IntConicQuad linSphere(gridLine._line,_sphere);
2250 if ( linSphere.IsDone() && linSphere.NbPoints() > 0 )
2252 _w = linSphere.ParamOnConic(1);
2253 if ( linSphere.NbPoints() == 1 )
2254 _transition = Trans_TANGENT;
2256 _transition = _w < linSphere.ParamOnConic(2) ? _transIn : _transOut;
2257 if ( isParamOnLineOK( gridLine._length ))
2259 ElSLib::Parameters(_sphere, linSphere.Point(1) ,_u,_v);
2262 if ( linSphere.NbPoints() > 1 )
2264 _w = linSphere.ParamOnConic(2);
2265 if ( isParamOnLineOK( gridLine._length ))
2267 ElSLib::Parameters(_sphere, linSphere.Point(2) ,_u,_v);
2268 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
2274 //================================================================================
2276 * Intersect a line with a torus
2278 void FaceLineIntersector::IntersectWithTorus (const GridLine& gridLine)
2280 IntAna_IntLinTorus linTorus(gridLine._line,_torus);
2281 if ( !linTorus.IsDone()) return;
2283 gp_Vec du, dv, norm;
2284 for ( int i = 1; i <= linTorus.NbPoints(); ++i )
2286 _w = linTorus.ParamOnLine( i );
2287 if ( !isParamOnLineOK( gridLine._length )) continue;
2288 linTorus.ParamOnTorus( i, _u,_v );
2291 ElSLib::D1( _u, _v, _torus, P, du, dv );
2293 double normSize = norm.Magnitude();
2294 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
2296 if ( cos < -Precision::Angular() )
2297 _transition = _transIn;
2298 else if ( cos > Precision::Angular() )
2299 _transition = _transOut;
2301 _transition = Trans_TANGENT;
2302 addIntPoint( /*toClassify=*/false);
2306 //================================================================================
2308 * Intersect a line with a non-analytical surface
2310 void FaceLineIntersector::IntersectWithSurface (const GridLine& gridLine)
2312 _surfaceInt->Perform( gridLine._line, 0.0, gridLine._length );
2313 if ( !_surfaceInt->IsDone() ) return;
2314 for ( int i = 1; i <= _surfaceInt->NbPnt(); ++i )
2316 _transition = Transition( _surfaceInt->Transition( i ) );
2317 _w = _surfaceInt->WParameter( i );
2318 addIntPoint(/*toClassify=*/false);
2321 //================================================================================
2323 * check if its face can be safely intersected in a thread
2325 bool FaceGridIntersector::IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const
2330 TopLoc_Location loc;
2331 Handle(Geom_Surface) surf = BRep_Tool::Surface( _face, loc );
2332 Handle(Geom_RectangularTrimmedSurface) ts =
2333 Handle(Geom_RectangularTrimmedSurface)::DownCast( surf );
2334 while( !ts.IsNull() ) {
2335 surf = ts->BasisSurface();
2336 ts = Handle(Geom_RectangularTrimmedSurface)::DownCast(surf);
2338 if ( surf->IsKind( STANDARD_TYPE(Geom_BSplineSurface )) ||
2339 surf->IsKind( STANDARD_TYPE(Geom_BezierSurface )))
2340 if ( !noSafeTShapes.insert( _face.TShape().get() ).second )
2344 TopExp_Explorer exp( _face, TopAbs_EDGE );
2345 for ( ; exp.More(); exp.Next() )
2347 bool edgeIsSafe = true;
2348 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
2351 Handle(Geom_Curve) c = BRep_Tool::Curve( e, loc, f, l);
2354 Handle(Geom_TrimmedCurve) tc = Handle(Geom_TrimmedCurve)::DownCast(c);
2355 while( !tc.IsNull() ) {
2356 c = tc->BasisCurve();
2357 tc = Handle(Geom_TrimmedCurve)::DownCast(c);
2359 if ( c->IsKind( STANDARD_TYPE(Geom_BSplineCurve )) ||
2360 c->IsKind( STANDARD_TYPE(Geom_BezierCurve )))
2367 Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( e, surf, loc, f, l);
2370 Handle(Geom2d_TrimmedCurve) tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
2371 while( !tc.IsNull() ) {
2372 c2 = tc->BasisCurve();
2373 tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
2375 if ( c2->IsKind( STANDARD_TYPE(Geom2d_BSplineCurve )) ||
2376 c2->IsKind( STANDARD_TYPE(Geom2d_BezierCurve )))
2380 if ( !edgeIsSafe && !noSafeTShapes.insert( e.TShape().get() ).second )
2385 //================================================================================
2387 * \brief Creates topology of the hexahedron
2389 Hexahedron::Hexahedron(Grid* grid)
2390 : _grid( grid ), _nbFaceIntNodes(0), _hasTooSmall( false )
2392 _polygons.reserve(100); // to avoid reallocation;
2394 //set nodes shift within grid->_nodes from the node 000
2395 size_t dx = _grid->NodeIndexDX();
2396 size_t dy = _grid->NodeIndexDY();
2397 size_t dz = _grid->NodeIndexDZ();
2399 size_t i100 = i000 + dx;
2400 size_t i010 = i000 + dy;
2401 size_t i110 = i010 + dx;
2402 size_t i001 = i000 + dz;
2403 size_t i101 = i100 + dz;
2404 size_t i011 = i010 + dz;
2405 size_t i111 = i110 + dz;
2406 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V000 )] = i000;
2407 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V100 )] = i100;
2408 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V010 )] = i010;
2409 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V110 )] = i110;
2410 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V001 )] = i001;
2411 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V101 )] = i101;
2412 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V011 )] = i011;
2413 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V111 )] = i111;
2415 vector< int > idVec;
2416 // set nodes to links
2417 for ( int linkID = SMESH_Block::ID_Ex00; linkID <= SMESH_Block::ID_E11z; ++linkID )
2419 SMESH_Block::GetEdgeVertexIDs( linkID, idVec );
2420 _Link& link = _hexLinks[ SMESH_Block::ShapeIndex( linkID )];
2421 link._nodes[0] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[0] )];
2422 link._nodes[1] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[1] )];
2425 // set links to faces
2426 int interlace[4] = { 0, 3, 1, 2 }; // to walk by links around a face: { u0, 1v, u1, 0v }
2427 for ( int faceID = SMESH_Block::ID_Fxy0; faceID <= SMESH_Block::ID_F1yz; ++faceID )
2429 _Face& quad = _hexQuads[ SMESH_Block::ShapeIndex( faceID )];
2430 quad._name = (SMESH_Block::TShapeID) faceID;
2432 SMESH_Block::GetFaceEdgesIDs( faceID, idVec );
2433 bool revFace = ( faceID == SMESH_Block::ID_Fxy0 ||
2434 faceID == SMESH_Block::ID_Fx1z ||
2435 faceID == SMESH_Block::ID_F0yz );
2436 quad._links.resize(4);
2437 vector<_OrientedLink>::iterator frwLinkIt = quad._links.begin();
2438 vector<_OrientedLink>::reverse_iterator revLinkIt = quad._links.rbegin();
2439 for ( int i = 0; i < 4; ++i )
2441 bool revLink = revFace;
2442 if ( i > 1 ) // reverse links u1 and v0
2444 _OrientedLink& link = revFace ? *revLinkIt++ : *frwLinkIt++;
2445 link = _OrientedLink( & _hexLinks[ SMESH_Block::ShapeIndex( idVec[interlace[i]] )],
2450 //================================================================================
2452 * \brief Copy constructor
2454 Hexahedron::Hexahedron( const Hexahedron& other, size_t i, size_t j, size_t k, int cellID )
2455 :_grid( other._grid ), _nbFaceIntNodes(0), _i( i ), _j( j ), _k( k ), _hasTooSmall( false )
2457 _polygons.reserve(100); // to avoid reallocation;
2460 for ( int i = 0; i < 12; ++i )
2462 const _Link& srcLink = other._hexLinks[ i ];
2463 _Link& tgtLink = this->_hexLinks[ i ];
2464 tgtLink._nodes[0] = _hexNodes + ( srcLink._nodes[0] - other._hexNodes );
2465 tgtLink._nodes[1] = _hexNodes + ( srcLink._nodes[1] - other._hexNodes );
2468 for ( int i = 0; i < 6; ++i )
2470 const _Face& srcQuad = other._hexQuads[ i ];
2471 _Face& tgtQuad = this->_hexQuads[ i ];
2472 tgtQuad._name = srcQuad._name;
2473 tgtQuad._links.resize(4);
2474 for ( int j = 0; j < 4; ++j )
2476 const _OrientedLink& srcLink = srcQuad._links[ j ];
2477 _OrientedLink& tgtLink = tgtQuad._links[ j ];
2478 tgtLink._reverse = srcLink._reverse;
2479 tgtLink._link = _hexLinks + ( srcLink._link - other._hexLinks );
2483 if (SALOME::VerbosityActivated())
2487 //================================================================================
2489 * \brief Return IDs of SOLIDs interfering with this Hexahedron
2491 size_t Hexahedron::getSolids( TGeomID ids[] )
2493 if ( _grid->_geometry.IsOneSolid() )
2495 ids[0] = _grid->GetSolid()->ID();
2498 // count intersection points belonging to each SOLID
2500 id2NbPoints.reserve( 3 );
2502 _origNodeInd = _grid->NodeIndex( _i,_j,_k );
2503 for ( int iN = 0; iN < 8; ++iN )
2505 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
2506 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
2508 if ( _hexNodes[iN]._intPoint ) // intersection with a FACE
2510 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2512 const vector< TGeomID > & solidIDs =
2513 _grid->GetSolidIDs( _hexNodes[iN]._intPoint->_faceIDs[iF] );
2514 for ( size_t i = 0; i < solidIDs.size(); ++i )
2515 insertAndIncrement( solidIDs[i], id2NbPoints );
2518 else if ( _hexNodes[iN]._node ) // node inside a SOLID
2520 insertAndIncrement( _hexNodes[iN]._node->GetShapeID(), id2NbPoints );
2524 for ( int iL = 0; iL < 12; ++iL )
2526 const _Link& link = _hexLinks[ iL ];
2527 for ( size_t iP = 0; iP < link._fIntPoints.size(); ++iP )
2529 for ( size_t iF = 0; iF < link._fIntPoints[iP]->_faceIDs.size(); ++iF )
2531 const vector< TGeomID > & solidIDs =
2532 _grid->GetSolidIDs( link._fIntPoints[iP]->_faceIDs[iF] );
2533 for ( size_t i = 0; i < solidIDs.size(); ++i )
2534 insertAndIncrement( solidIDs[i], id2NbPoints );
2539 for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
2541 const vector< TGeomID > & solidIDs = _grid->GetSolidIDs( _eIntPoints[iP]->_shapeID );
2542 for ( size_t i = 0; i < solidIDs.size(); ++i )
2543 insertAndIncrement( solidIDs[i], id2NbPoints );
2546 size_t nbSolids = 0;
2547 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2548 if ( id2nb->second >= 3 )
2549 ids[ nbSolids++ ] = id2nb->first;
2554 //================================================================================
2556 * \brief Count cuts by INTERNAL FACEs and set _Node::_isInternalFlags
2558 bool Hexahedron::isCutByInternalFace( IsInternalFlag & maxFlag )
2561 id2NbPoints.reserve( 3 );
2563 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2564 for ( size_t iF = 0; iF < _intNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2566 if ( _grid->IsInternal( _intNodes[iN]._intPoint->_faceIDs[iF]))
2567 insertAndIncrement( _intNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2569 for ( size_t iN = 0; iN < 8; ++iN )
2570 if ( _hexNodes[iN]._intPoint )
2571 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2573 if ( _grid->IsInternal( _hexNodes[iN]._intPoint->_faceIDs[iF]))
2574 insertAndIncrement( _hexNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2577 maxFlag = IS_NOT_INTERNAL;
2578 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2580 TGeomID intFace = id2nb->first;
2581 IsInternalFlag intFlag = ( id2nb->second >= 3 ? IS_CUT_BY_INTERNAL_FACE : IS_INTERNAL );
2582 if ( intFlag > maxFlag )
2585 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2586 if ( _intNodes[iN].IsOnFace( intFace ))
2587 _intNodes[iN].SetInternal( intFlag );
2589 for ( size_t iN = 0; iN < 8; ++iN )
2590 if ( _hexNodes[iN].IsOnFace( intFace ))
2591 _hexNodes[iN].SetInternal( intFlag );
2597 //================================================================================
2599 * \brief Return any FACE interfering with this Hexahedron
2601 TGeomID Hexahedron::getAnyFace() const
2604 id2NbPoints.reserve( 3 );
2606 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2607 for ( size_t iF = 0; iF < _intNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2608 insertAndIncrement( _intNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2610 for ( size_t iN = 0; iN < 8; ++iN )
2611 if ( _hexNodes[iN]._intPoint )
2612 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2613 insertAndIncrement( _hexNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2615 for ( unsigned int minNb = 3; minNb > 0; --minNb )
2616 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2617 if ( id2nb->second >= minNb )
2618 return id2nb->first;
2623 //================================================================================
2625 * \brief Initializes IJK by Hexahedron index
2627 void Hexahedron::setIJK( size_t iCell )
2629 size_t iNbCell = _grid->_coords[0].size() - 1;
2630 size_t jNbCell = _grid->_coords[1].size() - 1;
2631 _i = iCell % iNbCell;
2632 _j = ( iCell % ( iNbCell * jNbCell )) / iNbCell;
2633 _k = iCell / iNbCell / jNbCell;
2636 //================================================================================
2638 * \brief Initializes its data by given grid cell (countered from zero)
2640 void Hexahedron::init( size_t iCell )
2646 //================================================================================
2648 * \brief Initializes its data by given grid cell nodes and intersections
2650 void Hexahedron::init( size_t i, size_t j, size_t k, const Solid* solid )
2652 _i = i; _j = j; _k = k;
2654 bool isCompute = solid;
2656 solid = _grid->GetSolid();
2658 // set nodes of grid to nodes of the hexahedron and
2659 // count nodes at hexahedron corners located IN and ON geometry
2660 _nbCornerNodes = _nbBndNodes = 0;
2661 _origNodeInd = _grid->NodeIndex( i,j,k );
2662 for ( int iN = 0; iN < 8; ++iN )
2664 _hexNodes[iN]._isInternalFlags = 0;
2666 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
2667 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
2669 if ( _hexNodes[iN]._node && !solid->Contains( _hexNodes[iN]._node->GetShapeID() ))
2670 _hexNodes[iN]._node = 0;
2671 if ( _hexNodes[iN]._intPoint && !solid->ContainsAny( _hexNodes[iN]._intPoint->_faceIDs ))
2672 _hexNodes[iN]._intPoint = 0;
2674 _nbCornerNodes += bool( _hexNodes[iN]._node );
2675 _nbBndNodes += bool( _hexNodes[iN]._intPoint );
2677 _sideLength[0] = _grid->_coords[0][i+1] - _grid->_coords[0][i];
2678 _sideLength[1] = _grid->_coords[1][j+1] - _grid->_coords[1][j];
2679 _sideLength[2] = _grid->_coords[2][k+1] - _grid->_coords[2][k];
2687 if ( _nbFaceIntNodes + _eIntPoints.size() > 0 &&
2688 _nbFaceIntNodes + _eIntPoints.size() + _nbCornerNodes > 3)
2690 _intNodes.reserve( 3 * ( _nbBndNodes + _nbFaceIntNodes + _eIntPoints.size() ));
2692 // this method can be called in parallel, so use own helper
2693 SMESH_MesherHelper helper( *_grid->_helper->GetMesh() );
2695 // Create sub-links (_Link::_splits) by splitting links with _Link::_fIntPoints
2696 // ---------------------------------------------------------------
2698 for ( int iLink = 0; iLink < 12; ++iLink )
2700 _Link& link = _hexLinks[ iLink ];
2701 link._fIntNodes.clear();
2702 link._fIntNodes.reserve( link._fIntPoints.size() );
2703 for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
2704 if ( solid->ContainsAny( link._fIntPoints[i]->_faceIDs ))
2706 _intNodes.push_back( _Node( 0, link._fIntPoints[i] ));
2707 link._fIntNodes.push_back( & _intNodes.back() );
2710 link._splits.clear();
2711 split._nodes[ 0 ] = link._nodes[0];
2712 bool isOut = ( ! link._nodes[0]->Node() );
2713 bool checkTransition;
2714 for ( size_t i = 0; i < link._fIntNodes.size(); ++i )
2716 const bool isGridNode = ( ! link._fIntNodes[i]->Node() );
2717 if ( !isGridNode ) // intersection non-coincident with a grid node
2719 if ( split._nodes[ 0 ]->Node() && !isOut )
2721 split._nodes[ 1 ] = link._fIntNodes[i];
2722 link._splits.push_back( split );
2724 split._nodes[ 0 ] = link._fIntNodes[i];
2725 checkTransition = true;
2727 else // FACE intersection coincident with a grid node (at link ends)
2729 checkTransition = ( i == 0 && link._nodes[0]->Node() );
2731 if ( checkTransition )
2733 const vector< TGeomID >& faceIDs = link._fIntNodes[i]->_intPoint->_faceIDs;
2734 if ( _grid->IsInternal( faceIDs.back() ))
2736 else if ( faceIDs.size() > 1 || _eIntPoints.size() > 0 )
2737 isOut = isOutPoint( link, i, helper, solid );
2740 bool okTransi = _grid->IsCorrectTransition( faceIDs[0], solid );
2741 switch ( link._fIntNodes[i]->FaceIntPnt()->_transition ) {
2742 case Trans_OUT: isOut = okTransi; break;
2743 case Trans_IN : isOut = !okTransi; break;
2745 isOut = isOutPoint( link, i, helper, solid );
2750 if ( link._nodes[ 1 ]->Node() && split._nodes[ 0 ]->Node() && !isOut )
2752 split._nodes[ 1 ] = link._nodes[1];
2753 link._splits.push_back( split );
2757 // Create _Node's at intersections with EDGEs.
2758 // --------------------------------------------
2759 // 1) add this->_eIntPoints to _Face::_eIntNodes
2760 // 2) fill _intNodes and _vIntNodes
2762 const double tol2 = _grid->_tol * _grid->_tol * 4;
2763 int facets[3], nbFacets, subEntity;
2765 for ( int iF = 0; iF < 6; ++iF )
2766 _hexQuads[ iF ]._eIntNodes.clear();
2768 for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
2770 if ( !solid->ContainsAny( _eIntPoints[iP]->_faceIDs ))
2772 nbFacets = getEntity( _eIntPoints[iP], facets, subEntity );
2773 _Node* equalNode = 0;
2774 switch( nbFacets ) {
2775 case 1: // in a _Face
2777 _Face& quad = _hexQuads[ facets[0] - SMESH_Block::ID_FirstF ];
2778 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2780 equalNode->Add( _eIntPoints[ iP ] );
2783 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2784 quad._eIntNodes.push_back( & _intNodes.back() );
2788 case 2: // on a _Link
2790 _Link& link = _hexLinks[ subEntity - SMESH_Block::ID_FirstE ];
2791 if ( link._splits.size() > 0 )
2793 equalNode = findEqualNode( link._fIntNodes, _eIntPoints[ iP ], tol2 );
2795 equalNode->Add( _eIntPoints[ iP ] );
2796 else if ( link._splits.size() == 1 &&
2797 link._splits[0]._nodes[0] &&
2798 link._splits[0]._nodes[1] )
2799 link._splits.clear(); // hex edge is divided by _eIntPoints[iP]
2804 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2805 bool newNodeUsed = false;
2806 for ( int iF = 0; iF < 2; ++iF )
2808 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
2809 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2811 equalNode->Add( _eIntPoints[ iP ] );
2814 quad._eIntNodes.push_back( & _intNodes.back() );
2819 _intNodes.pop_back();
2823 case 3: // at a corner
2825 _Node& node = _hexNodes[ subEntity - SMESH_Block::ID_FirstV ];
2828 if ( node._intPoint )
2829 node._intPoint->Add( _eIntPoints[ iP ]->_faceIDs, _eIntPoints[ iP ]->_node );
2833 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2834 for ( int iF = 0; iF < 3; ++iF )
2836 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
2837 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2839 equalNode->Add( _eIntPoints[ iP ] );
2842 quad._eIntNodes.push_back( & _intNodes.back() );
2848 } // switch( nbFacets )
2850 if ( nbFacets == 0 ||
2851 _grid->ShapeType( _eIntPoints[ iP ]->_shapeID ) == TopAbs_VERTEX )
2853 equalNode = findEqualNode( _vIntNodes, _eIntPoints[ iP ], tol2 );
2855 equalNode->Add( _eIntPoints[ iP ] );
2857 else if ( nbFacets == 0 ) {
2858 if ( _intNodes.empty() || _intNodes.back().EdgeIntPnt() != _eIntPoints[ iP ])
2859 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2860 _vIntNodes.push_back( & _intNodes.back() );
2863 } // loop on _eIntPoints
2866 else if (( 3 < _nbCornerNodes && _nbCornerNodes < 8 ) || // _nbFaceIntNodes == 0
2867 ( !_grid->_geometry.IsOneSolid() ))
2870 // create sub-links (_splits) of whole links
2871 for ( int iLink = 0; iLink < 12; ++iLink )
2873 _Link& link = _hexLinks[ iLink ];
2874 link._splits.clear();
2875 if ( link._nodes[ 0 ]->Node() && link._nodes[ 1 ]->Node() )
2877 split._nodes[ 0 ] = link._nodes[0];
2878 split._nodes[ 1 ] = link._nodes[1];
2879 link._splits.push_back( split );
2885 } // init( _i, _j, _k )
2887 //================================================================================
2889 * \brief Compute mesh volumes resulted from intersection of the Hexahedron
2891 void Hexahedron::computeElements( const Solid* solid, int solidIndex )
2895 solid = _grid->GetSolid();
2896 if ( !_grid->_geometry.IsOneSolid() )
2898 TGeomID solidIDs[20] = { 0 };
2899 size_t nbSolids = getSolids( solidIDs );
2902 for ( size_t i = 0; i < nbSolids; ++i )
2904 solid = _grid->GetSolid( solidIDs[i] );
2905 computeElements( solid, i );
2906 if ( !_volumeDefs._nodes.empty() && i < nbSolids - 1 )
2907 _volumeDefs.SetNext( new _volumeDef( _volumeDefs ));
2911 solid = _grid->GetSolid( solidIDs[0] );
2915 init( _i, _j, _k, solid ); // get nodes and intersections from grid nodes and split links
2917 int nbIntersections = _nbFaceIntNodes + _eIntPoints.size();
2918 if ( _nbCornerNodes + nbIntersections < 4 )
2921 if ( _nbBndNodes == _nbCornerNodes && nbIntersections == 0 && isInHole() )
2922 return; // cell is in a hole
2924 IsInternalFlag intFlag = IS_NOT_INTERNAL;
2925 if ( solid->HasInternalFaces() && this->isCutByInternalFace( intFlag ))
2927 for ( _SplitIterator it( _hexLinks ); it.More(); it.Next() )
2929 if ( compute( solid, intFlag ))
2930 _volumeDefs.SetNext( new _volumeDef( _volumeDefs ));
2935 if ( solidIndex >= 0 )
2936 intFlag = IS_CUT_BY_INTERNAL_FACE;
2938 compute( solid, intFlag );
2942 //================================================================================
2944 * \brief Compute mesh volumes resulted from intersection of the Hexahedron
2946 bool Hexahedron::compute( const Solid* solid, const IsInternalFlag intFlag )
2949 _polygons.reserve( 20 );
2951 for ( int iN = 0; iN < 8; ++iN )
2952 _hexNodes[iN]._usedInFace = 0;
2954 if ( intFlag & IS_CUT_BY_INTERNAL_FACE && !_grid->_toAddEdges ) // Issue #19913
2955 preventVolumesOverlapping();
2957 std::set< TGeomID > concaveFaces; // to avoid connecting nodes laying on them
2959 if ( solid->HasConcaveVertex() )
2961 for ( const E_IntersectPoint* ip : _eIntPoints )
2963 if ( const ConcaveFace* cf = solid->GetConcave( ip->_shapeID ))
2964 if ( this->hasEdgesAround( cf ))
2965 concaveFaces.insert( cf->_concaveFace );
2967 if ( concaveFaces.empty() || concaveFaces.size() * 3 < _eIntPoints.size() )
2968 for ( const _Node& hexNode: _hexNodes )
2970 if ( hexNode._node && hexNode._intPoint && hexNode._intPoint->_faceIDs.size() >= 3 )
2971 if ( const ConcaveFace* cf = solid->GetConcave( hexNode._node->GetShapeID() ))
2972 if ( this->hasEdgesAround( cf ))
2973 concaveFaces.insert( cf->_concaveFace );
2977 // Create polygons from quadrangles
2978 // --------------------------------
2980 vector< _OrientedLink > splits;
2981 vector<_Node*> chainNodes;
2982 _Face* coplanarPolyg;
2984 const bool hasEdgeIntersections = !_eIntPoints.empty();
2985 const bool toCheckSideDivision = isImplementEdges() || intFlag & IS_CUT_BY_INTERNAL_FACE;
2987 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
2989 _Face& quad = _hexQuads[ iF ] ;
2991 _polygons.resize( _polygons.size() + 1 );
2992 _Face* polygon = &_polygons.back();
2993 polygon->_polyLinks.reserve( 20 );
2994 polygon->_name = quad._name;
2997 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
2998 for ( size_t iS = 0; iS < quad._links[ iE ].NbResultLinks(); ++iS )
2999 splits.push_back( quad._links[ iE ].ResultLink( iS ));
3001 if ( splits.size() == 4 &&
3002 isQuadOnFace( iF )) // check if a quad on FACE is not split
3004 polygon->_links.swap( splits );
3005 continue; // goto the next quad
3008 // add splits of links to a polygon and add _polyLinks to make
3009 // polygon's boundary closed
3011 int nbSplits = splits.size();
3012 if (( nbSplits == 1 ) &&
3013 ( quad._eIntNodes.empty() ||
3014 splits[0].FirstNode()->IsLinked( splits[0].LastNode()->_intPoint )))
3015 //( quad._eIntNodes.empty() || _nbCornerNodes + nbIntersections > 6 ))
3018 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
3019 if ( quad._eIntNodes[ iP ]->IsUsedInFace( polygon ))
3020 quad._eIntNodes[ iP ]->_usedInFace = 0;
3022 size_t nbUsedEdgeNodes = 0;
3023 _Face* prevPolyg = 0; // polygon previously created from this quad
3025 while ( nbSplits > 0 )
3028 while ( !splits[ iS ] )
3031 if ( !polygon->_links.empty() )
3033 _polygons.resize( _polygons.size() + 1 );
3034 polygon = &_polygons.back();
3035 polygon->_polyLinks.reserve( 20 );
3036 polygon->_name = quad._name;
3038 polygon->_links.push_back( splits[ iS ] );
3039 splits[ iS++ ]._link = 0;
3042 _Node* nFirst = polygon->_links.back().FirstNode();
3043 _Node *n1,*n2 = polygon->_links.back().LastNode();
3044 for ( ; nFirst != n2 && iS < splits.size(); ++iS )
3046 _OrientedLink& split = splits[ iS ];
3047 if ( !split ) continue;
3049 n1 = split.FirstNode();
3052 (( n1->_intPoint->_faceIDs.size() > 1 && toCheckSideDivision ) ||
3053 ( n1->_isInternalFlags )))
3055 // n1 is at intersection with EDGE
3056 if ( findChainOnEdge( splits, polygon->_links.back(), split, concaveFaces,
3057 iS, quad, chainNodes ))
3059 for ( size_t i = 1; i < chainNodes.size(); ++i )
3060 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
3061 if ( chainNodes.back() != n1 ) // not a partial cut by INTERNAL FACE
3063 prevPolyg = polygon;
3064 n2 = chainNodes.back();
3069 else if ( n1 != n2 )
3071 // try to connect to intersections with EDGEs
3072 if ( quad._eIntNodes.size() > nbUsedEdgeNodes &&
3073 findChain( n2, n1, quad, chainNodes ))
3075 for ( size_t i = 1; i < chainNodes.size(); ++i )
3077 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i] );
3078 nbUsedEdgeNodes += ( chainNodes[i]->IsUsedInFace( polygon ));
3080 if ( chainNodes.back() != n1 )
3082 n2 = chainNodes.back();
3087 // try to connect to a split ending on the same FACE
3090 _OrientedLink foundSplit;
3091 for ( size_t i = iS; i < splits.size() && !foundSplit; ++i )
3092 if (( foundSplit = splits[ i ]) &&
3093 ( n2->IsLinked( foundSplit.FirstNode()->_intPoint )))
3099 foundSplit._link = 0;
3103 if ( n2 != foundSplit.FirstNode() )
3105 polygon->AddPolyLink( n2, foundSplit.FirstNode() );
3106 n2 = foundSplit.FirstNode();
3112 if ( n2->IsLinked( nFirst->_intPoint ))
3114 polygon->AddPolyLink( n2, n1, prevPolyg );
3117 } // if ( n1 != n2 )
3119 polygon->_links.push_back( split );
3122 n2 = polygon->_links.back().LastNode();
3126 if ( nFirst != n2 ) // close a polygon
3128 if ( !findChain( n2, nFirst, quad, chainNodes ))
3130 if ( !closePolygon( polygon, chainNodes ))
3131 if ( !isImplementEdges() )
3132 chainNodes.push_back( nFirst );
3134 for ( size_t i = 1; i < chainNodes.size(); ++i )
3136 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
3137 nbUsedEdgeNodes += bool( chainNodes[i]->IsUsedInFace( polygon ));
3141 if ( polygon->_links.size() < 3 && nbSplits > 0 )
3143 polygon->_polyLinks.clear();
3144 polygon->_links.clear();
3146 } // while ( nbSplits > 0 )
3148 if ( polygon->_links.size() < 3 )
3150 _polygons.pop_back();
3152 } // loop on 6 hexahedron sides
3154 // Create polygons closing holes in a polyhedron
3155 // ----------------------------------------------
3157 // clear _usedInFace
3158 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
3159 _intNodes[ iN ]._usedInFace = 0;
3161 // add polygons to their links and mark used nodes
3162 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3164 _Face& polygon = _polygons[ iP ];
3165 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3167 polygon._links[ iL ].AddFace( &polygon );
3168 polygon._links[ iL ].FirstNode()->_usedInFace = &polygon;
3172 vector< _OrientedLink* > freeLinks;
3173 freeLinks.reserve(20);
3174 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3176 _Face& polygon = _polygons[ iP ];
3177 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3178 if ( polygon._links[ iL ].NbFaces() < 2 )
3179 freeLinks.push_back( & polygon._links[ iL ]);
3181 int nbFreeLinks = freeLinks.size();
3182 if ( nbFreeLinks == 1 ) return false;
3184 // put not used intersection nodes to _vIntNodes
3185 int nbVertexNodes = 0; // nb not used vertex nodes
3187 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
3188 nbVertexNodes += ( !_vIntNodes[ iN ]->IsUsedInFace() );
3190 const double tol = 1e-3 * Min( Min( _sideLength[0], _sideLength[1] ), _sideLength[0] );
3191 for ( size_t iN = _nbFaceIntNodes; iN < _intNodes.size(); ++iN )
3193 if ( _intNodes[ iN ].IsUsedInFace() ) continue;
3194 if ( dynamic_cast< const F_IntersectPoint* >( _intNodes[ iN ]._intPoint )) continue;
3196 findEqualNode( _vIntNodes, _intNodes[ iN ].EdgeIntPnt(), tol*tol );
3199 _vIntNodes.push_back( &_intNodes[ iN ]);
3205 std::set<TGeomID> usedFaceIDs;
3206 std::vector< TGeomID > faces;
3207 TGeomID curFace = 0;
3208 const size_t nbQuadPolygons = _polygons.size();
3209 E_IntersectPoint ipTmp;
3210 std::map< TGeomID, std::vector< const B_IntersectPoint* > > tmpAddedFace; // face added to _intPoint
3212 // create polygons by making closed chains of free links
3213 size_t iPolygon = _polygons.size();
3214 while ( nbFreeLinks > 0 )
3216 if ( iPolygon == _polygons.size() )
3218 _polygons.resize( _polygons.size() + 1 );
3219 _polygons[ iPolygon ]._polyLinks.reserve( 20 );
3220 _polygons[ iPolygon ]._links.reserve( 20 );
3222 _Face& polygon = _polygons[ iPolygon ];
3224 _OrientedLink* curLink = 0;
3226 if (( !hasEdgeIntersections ) ||
3227 ( nbFreeLinks < 4 && nbVertexNodes == 0 ))
3229 // get a remaining link to start from
3230 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3231 if (( curLink = freeLinks[ iL ] ))
3232 freeLinks[ iL ] = 0;
3233 polygon._links.push_back( *curLink );
3237 // find all links connected to curLink
3238 curNode = curLink->FirstNode();
3240 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3241 if ( freeLinks[ iL ] && freeLinks[ iL ]->LastNode() == curNode )
3243 curLink = freeLinks[ iL ];
3244 freeLinks[ iL ] = 0;
3246 polygon._links.push_back( *curLink );
3248 } while ( curLink );
3250 else // there are intersections with EDGEs
3252 // get a remaining link to start from, one lying on minimal nb of FACEs
3254 typedef pair< TGeomID, int > TFaceOfLink;
3255 TFaceOfLink faceOfLink( -1, -1 );
3256 TFaceOfLink facesOfLink[3] = { faceOfLink, faceOfLink, faceOfLink };
3257 for ( size_t iL = 0; iL < freeLinks.size(); ++iL )
3258 if ( freeLinks[ iL ] )
3260 faces = freeLinks[ iL ]->GetNotUsedFace( usedFaceIDs );
3261 if ( faces.size() == 1 )
3263 faceOfLink = TFaceOfLink( faces[0], iL );
3264 if ( !freeLinks[ iL ]->HasEdgeNodes() )
3266 facesOfLink[0] = faceOfLink;
3268 else if ( facesOfLink[0].first < 0 )
3270 faceOfLink = TFaceOfLink(( faces.empty() ? -1 : faces[0]), iL );
3271 facesOfLink[ 1 + faces.empty() ] = faceOfLink;
3274 for ( int i = 0; faceOfLink.first < 0 && i < 3; ++i )
3275 faceOfLink = facesOfLink[i];
3277 if ( faceOfLink.first < 0 ) // all faces used
3279 for ( size_t iL = 0; iL < freeLinks.size() && faceOfLink.first < 1; ++iL )
3280 if (( curLink = freeLinks[ iL ]))
3283 curLink->FirstNode()->IsLinked( curLink->LastNode()->_intPoint );
3284 faceOfLink.second = iL;
3286 usedFaceIDs.clear();
3288 curFace = faceOfLink.first;
3289 curLink = freeLinks[ faceOfLink.second ];
3290 freeLinks[ faceOfLink.second ] = 0;
3292 usedFaceIDs.insert( curFace );
3293 polygon._links.push_back( *curLink );
3296 // find all links lying on a curFace
3299 // go forward from curLink
3300 curNode = curLink->LastNode();
3302 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3303 if ( freeLinks[ iL ] &&
3304 freeLinks[ iL ]->FirstNode() == curNode &&
3305 freeLinks[ iL ]->LastNode()->IsOnFace( curFace ))
3307 curLink = freeLinks[ iL ];
3308 freeLinks[ iL ] = 0;
3309 polygon._links.push_back( *curLink );
3312 } while ( curLink );
3314 std::reverse( polygon._links.begin(), polygon._links.end() );
3316 curLink = & polygon._links.back();
3319 // go backward from curLink
3320 curNode = curLink->FirstNode();
3322 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3323 if ( freeLinks[ iL ] &&
3324 freeLinks[ iL ]->LastNode() == curNode &&
3325 freeLinks[ iL ]->FirstNode()->IsOnFace( curFace ))
3327 curLink = freeLinks[ iL ];
3328 freeLinks[ iL ] = 0;
3329 polygon._links.push_back( *curLink );
3332 } while ( curLink );
3334 curNode = polygon._links.back().FirstNode();
3336 if ( polygon._links[0].LastNode() != curNode )
3338 if ( nbVertexNodes > 0 )
3340 // add links with _vIntNodes if not already used
3342 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
3343 if ( !_vIntNodes[ iN ]->IsUsedInFace() &&
3344 _vIntNodes[ iN ]->IsOnFace( curFace ))
3346 _vIntNodes[ iN ]->_usedInFace = &polygon;
3347 chainNodes.push_back( _vIntNodes[ iN ] );
3349 if ( chainNodes.size() > 1 &&
3350 curFace != _grid->PseudoIntExtFaceID() ) /////// TODO
3352 sortVertexNodes( chainNodes, curNode, curFace );
3354 for ( size_t i = 0; i < chainNodes.size(); ++i )
3356 polygon.AddPolyLink( chainNodes[ i ], curNode );
3357 curNode = chainNodes[ i ];
3358 freeLinks.push_back( &polygon._links.back() );
3361 nbVertexNodes -= chainNodes.size();
3363 // if ( polygon._links.size() > 1 )
3365 polygon.AddPolyLink( polygon._links[0].LastNode(), curNode );
3366 freeLinks.push_back( &polygon._links.back() );
3370 } // if there are intersections with EDGEs
3372 if ( polygon._links.size() < 2 ||
3373 polygon._links[0].LastNode() != polygon._links.back().FirstNode() )
3376 break; // closed polygon not found -> invalid polyhedron
3379 if ( polygon._links.size() == 2 )
3381 if ( freeLinks.back() == &polygon._links.back() )
3383 freeLinks.pop_back();
3386 if ( polygon._links.front().NbFaces() > 0 )
3387 polygon._links.back().AddFace( polygon._links.front()._link->_faces[0] );
3388 if ( polygon._links.back().NbFaces() > 0 )
3389 polygon._links.front().AddFace( polygon._links.back()._link->_faces[0] );
3391 if ( iPolygon == _polygons.size()-1 )
3392 _polygons.pop_back();
3394 else // polygon._links.size() >= 2
3396 // add polygon to its links
3397 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3399 polygon._links[ iL ].AddFace( &polygon );
3400 polygon._links[ iL ].Reverse();
3402 if ( /*hasEdgeIntersections &&*/ iPolygon == _polygons.size() - 1 )
3404 // check that a polygon does not lie on a hexa side
3406 for ( size_t iL = 0; iL < polygon._links.size() && !coplanarPolyg; ++iL )
3408 if ( polygon._links[ iL ].NbFaces() < 2 )
3409 continue; // it's a just added free link
3410 // look for a polygon made on a hexa side and sharing
3411 // two or more haxa links
3413 coplanarPolyg = polygon._links[ iL ]._link->_faces[0];
3414 for ( iL2 = iL + 1; iL2 < polygon._links.size(); ++iL2 )
3415 if ( polygon._links[ iL2 ]._link->_faces[0] == coplanarPolyg &&
3416 !coplanarPolyg->IsPolyLink( polygon._links[ iL ]) &&
3417 !coplanarPolyg->IsPolyLink( polygon._links[ iL2 ]) &&
3418 coplanarPolyg < & _polygons[ nbQuadPolygons ])
3420 if ( iL2 == polygon._links.size() )
3423 if ( coplanarPolyg ) // coplanar polygon found
3425 freeLinks.resize( freeLinks.size() - polygon._polyLinks.size() );
3426 nbFreeLinks -= polygon._polyLinks.size();
3428 // an E_IntersectPoint used to mark nodes of coplanarPolyg
3429 // as lying on curFace while they are not at intersection with geometry
3430 ipTmp._faceIDs.resize(1);
3431 ipTmp._faceIDs[0] = curFace;
3433 // fill freeLinks with links not shared by coplanarPolyg and polygon
3434 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3435 if ( polygon._links[ iL ]._link->_faces[1] &&
3436 polygon._links[ iL ]._link->_faces[0] != coplanarPolyg )
3438 _Face* p = polygon._links[ iL ]._link->_faces[0];
3439 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
3440 if ( p->_links[ iL2 ]._link == polygon._links[ iL ]._link )
3442 freeLinks.push_back( & p->_links[ iL2 ] );
3444 freeLinks.back()->RemoveFace( &polygon );
3448 for ( size_t iL = 0; iL < coplanarPolyg->_links.size(); ++iL )
3449 if ( coplanarPolyg->_links[ iL ]._link->_faces[1] &&
3450 coplanarPolyg->_links[ iL ]._link->_faces[1] != &polygon )
3452 _Face* p = coplanarPolyg->_links[ iL ]._link->_faces[0];
3453 if ( p == coplanarPolyg )
3454 p = coplanarPolyg->_links[ iL ]._link->_faces[1];
3455 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
3456 if ( p->_links[ iL2 ]._link == coplanarPolyg->_links[ iL ]._link )
3458 // set links of coplanarPolyg in place of used freeLinks
3459 // to re-create coplanarPolyg next
3461 for ( ; iL3 < freeLinks.size() && freeLinks[ iL3 ]; ++iL3 );
3462 if ( iL3 < freeLinks.size() )
3463 freeLinks[ iL3 ] = ( & p->_links[ iL2 ] );
3465 freeLinks.push_back( & p->_links[ iL2 ] );
3467 freeLinks[ iL3 ]->RemoveFace( coplanarPolyg );
3468 // mark nodes of coplanarPolyg as lying on curFace
3469 for ( int iN = 0; iN < 2; ++iN )
3471 _Node* n = freeLinks[ iL3 ]->_link->_nodes[ iN ];
3473 if ( n->_intPoint ) added = n->_intPoint->Add( ipTmp._faceIDs );
3474 else n->_intPoint = &ipTmp;
3476 tmpAddedFace[ ipTmp._faceIDs[0] ].push_back( n->_intPoint );
3481 // set coplanarPolyg to be re-created next
3482 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3483 if ( coplanarPolyg == & _polygons[ iP ] )
3486 _polygons[ iPolygon ]._links.clear();
3487 _polygons[ iPolygon ]._polyLinks.clear();
3490 _polygons.pop_back();
3491 usedFaceIDs.erase( curFace );
3493 } // if ( coplanarPolyg )
3494 } // if ( hasEdgeIntersections ) - search for coplanarPolyg
3496 iPolygon = _polygons.size();
3498 } // end of case ( polygon._links.size() > 2 )
3499 } // while ( nbFreeLinks > 0 )
3501 for ( auto & face_ip : tmpAddedFace )
3503 curFace = face_ip.first;
3504 for ( const B_IntersectPoint* ip : face_ip.second )
3506 auto it = std::find( ip->_faceIDs.begin(), ip->_faceIDs.end(), curFace );
3507 if ( it != ip->_faceIDs.end() )
3508 ip->_faceIDs.erase( it );
3512 if ( _polygons.size() < 3 )
3515 // check volume size
3517 _hasTooSmall = ! checkPolyhedronSize( intFlag & IS_CUT_BY_INTERNAL_FACE, volSize );
3519 for ( size_t i = 0; i < 8; ++i )
3520 if ( _hexNodes[ i ]._intPoint == &ipTmp )
3521 _hexNodes[ i ]._intPoint = 0;
3524 return false; // too small volume
3527 // Try to find out names of no-name polygons (issue # 19887)
3528 if ( _grid->IsToRemoveExcessEntities() && _polygons.back()._name == SMESH_Block::ID_NONE )
3531 0.5 * ( _grid->_coords[0][_i] + _grid->_coords[0][_i+1] ) * _grid->_axes[0] +
3532 0.5 * ( _grid->_coords[1][_j] + _grid->_coords[1][_j+1] ) * _grid->_axes[1] +
3533 0.5 * ( _grid->_coords[2][_k] + _grid->_coords[2][_k+1] ) * _grid->_axes[2];
3534 for ( size_t i = _polygons.size() - 1; _polygons[i]._name == SMESH_Block::ID_NONE; --i )
3536 _Face& face = _polygons[ i ];
3539 for ( size_t iL = 0; iL < face._links.size(); ++iL )
3541 _Node* n = face._links[ iL ].FirstNode();
3542 gp_XYZ p = SMESH_NodeXYZ( n->Node() );
3543 _grid->ComputeUVW( p, uvw.ChangeCoord().ChangeData() );
3546 gp_Pnt pMin = bb.CornerMin();
3547 if ( bb.IsXThin( _grid->_tol ))
3548 face._name = pMin.X() < uvwCenter.X() ? SMESH_Block::ID_F0yz : SMESH_Block::ID_F1yz;
3549 else if ( bb.IsYThin( _grid->_tol ))
3550 face._name = pMin.Y() < uvwCenter.Y() ? SMESH_Block::ID_Fx0z : SMESH_Block::ID_Fx1z;
3551 else if ( bb.IsZThin( _grid->_tol ))
3552 face._name = pMin.Z() < uvwCenter.Z() ? SMESH_Block::ID_Fxy0 : SMESH_Block::ID_Fxy1;
3556 _volumeDefs._nodes.clear();
3557 _volumeDefs._quantities.clear();
3558 _volumeDefs._names.clear();
3560 // create a classic cell if possible
3563 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
3564 nbPolygons += (_polygons[ iF ]._links.size() > 2 );
3566 //const int nbNodes = _nbCornerNodes + nbIntersections;
3568 for ( size_t i = 0; i < 8; ++i )
3569 nbNodes += _hexNodes[ i ].IsUsedInFace();
3570 for ( size_t i = 0; i < _intNodes.size(); ++i )
3571 nbNodes += _intNodes[ i ].IsUsedInFace();
3573 bool isClassicElem = false;
3574 if ( nbNodes == 8 && nbPolygons == 6 ) isClassicElem = addHexa();
3575 else if ( nbNodes == 4 && nbPolygons == 4 ) isClassicElem = addTetra();
3576 else if ( nbNodes == 6 && nbPolygons == 5 ) isClassicElem = addPenta();
3577 else if ( nbNodes == 5 && nbPolygons == 5 ) isClassicElem = addPyra ();
3578 if ( !isClassicElem )
3580 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
3582 const size_t nbLinks = _polygons[ iF ]._links.size();
3583 if ( nbLinks < 3 ) continue;
3584 _volumeDefs._quantities.push_back( nbLinks );
3585 _volumeDefs._names.push_back( _polygons[ iF ]._name );
3586 for ( size_t iL = 0; iL < nbLinks; ++iL )
3587 _volumeDefs._nodes.push_back( _polygons[ iF ]._links[ iL ].FirstNode() );
3590 _volumeDefs._solidID = solid->ID();
3591 _volumeDefs._size = volSize;
3593 return !_volumeDefs._nodes.empty();
3595 //================================================================================
3597 * \brief Create elements in the mesh
3599 int Hexahedron::MakeElements(SMESH_MesherHelper& helper,
3600 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
3602 SMESHDS_Mesh* mesh = helper.GetMeshDS();
3604 CellsAroundLink c( _grid, 0 );
3605 const size_t nbGridCells = c._nbCells[0] * c._nbCells[1] * c._nbCells[2];
3606 vector< Hexahedron* > allHexa( nbGridCells, 0 );
3609 // set intersection nodes from GridLine's to links of allHexa
3610 int i,j,k, cellIndex, iLink;
3611 for ( int iDir = 0; iDir < 3; ++iDir )
3613 // loop on GridLine's parallel to iDir
3614 LineIndexer lineInd = _grid->GetLineIndexer( iDir );
3615 CellsAroundLink fourCells( _grid, iDir );
3616 for ( ; lineInd.More(); ++lineInd )
3618 GridLine& line = _grid->_lines[ iDir ][ lineInd.LineIndex() ];
3619 multiset< F_IntersectPoint >::const_iterator ip = line._intPoints.begin();
3620 for ( ; ip != line._intPoints.end(); ++ip )
3622 // if ( !ip->_node ) continue; // intersection at a grid node
3623 lineInd.SetIndexOnLine( ip->_indexOnLine );
3624 fourCells.Init( lineInd.I(), lineInd.J(), lineInd.K() );
3625 for ( int iL = 0; iL < 4; ++iL ) // loop on 4 cells sharing a link
3627 if ( !fourCells.GetCell( iL, i,j,k, cellIndex, iLink ))
3629 Hexahedron *& hex = allHexa[ cellIndex ];
3632 hex = new Hexahedron( *this, i, j, k, cellIndex );
3635 hex->_hexLinks[iLink]._fIntPoints.push_back( &(*ip) );
3636 hex->_nbFaceIntNodes += bool( ip->_node );
3642 // implement geom edges into the mesh
3643 addEdges( helper, allHexa, edge2faceIDsMap );
3645 // add not split hexahedra to the mesh
3647 TGeomID solidIDs[20];
3648 vector< Hexahedron* > intHexa; intHexa.reserve( nbIntHex );
3649 vector< const SMDS_MeshElement* > boundaryVolumes; boundaryVolumes.reserve( nbIntHex * 1.1 );
3650 for ( size_t i = 0; i < allHexa.size(); ++i )
3652 // initialize this by not cut allHexa[ i ]
3653 Hexahedron * & hex = allHexa[ i ];
3654 if ( hex ) // split hexahedron
3656 intHexa.push_back( hex );
3657 if ( hex->_nbFaceIntNodes > 0 ||
3658 hex->_eIntPoints.size() > 0 ||
3659 hex->getSolids( solidIDs ) > 1 )
3660 continue; // treat intersected hex later in parallel
3661 this->init( hex->_i, hex->_j, hex->_k );
3665 this->init( i ); // == init(i,j,k)
3667 if (( _nbCornerNodes == 8 ) &&
3668 ( _nbBndNodes < _nbCornerNodes || !isInHole() ))
3670 // order of _hexNodes is defined by enum SMESH_Block::TShapeID
3671 SMDS_MeshElement* el =
3672 mesh->AddVolume( _hexNodes[0].Node(), _hexNodes[2].Node(),
3673 _hexNodes[3].Node(), _hexNodes[1].Node(),
3674 _hexNodes[4].Node(), _hexNodes[6].Node(),
3675 _hexNodes[7].Node(), _hexNodes[5].Node() );
3676 TGeomID solidID = 0;
3677 if ( _nbBndNodes < _nbCornerNodes )
3679 for ( int iN = 0; iN < 8 && !solidID; ++iN )
3680 if ( !_hexNodes[iN]._intPoint ) // no intersection
3681 solidID = _hexNodes[iN].Node()->GetShapeID();
3685 getSolids( solidIDs );
3686 solidID = solidIDs[0];
3688 mesh->SetMeshElementOnShape( el, solidID );
3692 if ( _grid->_toCreateFaces && _nbBndNodes >= 3 )
3694 boundaryVolumes.push_back( el );
3695 el->setIsMarked( true );
3698 else if ( _nbCornerNodes > 3 && !hex )
3700 // all intersections of hex with geometry are at grid nodes
3701 hex = new Hexahedron( *this, _i, _j, _k, i );
3702 intHexa.push_back( hex );
3706 // compute definitions of volumes resulted from hexadron intersection
3708 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, intHexa.size() ),
3709 ParallelHexahedron( intHexa ),
3710 tbb::simple_partitioner()); // computeElements() is called here
3712 for ( size_t i = 0; i < intHexa.size(); ++i )
3713 if ( Hexahedron * hex = intHexa[ i ] )
3714 hex->computeElements();
3717 // simplify polyhedrons
3718 if ( _grid->IsToRemoveExcessEntities() )
3720 for ( size_t i = 0; i < intHexa.size(); ++i )
3721 if ( Hexahedron * hex = intHexa[ i ] )
3722 hex->removeExcessSideDivision( allHexa );
3724 for ( size_t i = 0; i < intHexa.size(); ++i )
3725 if ( Hexahedron * hex = intHexa[ i ] )
3726 hex->removeExcessNodes( allHexa );
3730 for ( size_t i = 0; i < intHexa.size(); ++i )
3731 if ( Hexahedron * hex = intHexa[ i ] )
3732 nbAdded += hex->addVolumes( helper );
3734 // fill boundaryVolumes with volumes neighboring too small skipped volumes
3735 if ( _grid->_toCreateFaces )
3737 for ( size_t i = 0; i < intHexa.size(); ++i )
3738 if ( Hexahedron * hex = intHexa[ i ] )
3739 hex->getBoundaryElems( boundaryVolumes );
3742 // merge nodes on outer sub-shapes with pre-existing ones
3743 TopTools_DataMapIteratorOfDataMapOfShapeInteger s2nIt( _grid->_geometry._shape2NbNodes );
3744 for ( ; s2nIt.More(); s2nIt.Next() )
3745 if ( s2nIt.Value() > 0 )
3746 if ( SMESHDS_SubMesh* sm = mesh->MeshElements( s2nIt.Key() ))
3748 TIDSortedNodeSet smNodes( SMDS_MeshElement::iterator( sm->GetNodes() ),
3749 SMDS_MeshElement::iterator() );
3750 SMESH_MeshEditor::TListOfListOfNodes equalNodes;
3751 SMESH_MeshEditor editor( helper.GetMesh() );
3752 editor.FindCoincidentNodes( smNodes, 10 * _grid->_tol, equalNodes,
3753 /*SeparateCornersAndMedium =*/ false);
3754 if ((int) equalNodes.size() <= s2nIt.Value() )
3755 editor.MergeNodes( equalNodes );
3758 // create boundary mesh faces
3759 addFaces( helper, boundaryVolumes );
3761 // create mesh edges
3762 addSegments( helper, edge2faceIDsMap );
3764 for ( size_t i = 0; i < allHexa.size(); ++i )
3766 delete allHexa[ i ];
3771 //================================================================================
3773 * \brief Implements geom edges into the mesh
3775 void Hexahedron::addEdges(SMESH_MesherHelper& helper,
3776 vector< Hexahedron* >& hexes,
3777 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
3779 if ( edge2faceIDsMap.empty() ) return;
3781 // Prepare planes for intersecting with EDGEs
3784 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ ) // iDirZ gives normal direction to planes
3786 GridPlanes& planes = pln[ iDirZ ];
3787 int iDirX = ( iDirZ + 1 ) % 3;
3788 int iDirY = ( iDirZ + 2 ) % 3;
3789 planes._zNorm = ( _grid->_axes[ iDirX ] ^ _grid->_axes[ iDirY ] ).Normalized();
3790 planes._zProjs.resize ( _grid->_coords[ iDirZ ].size() );
3791 planes._zProjs [0] = 0;
3792 const double zFactor = _grid->_axes[ iDirZ ] * planes._zNorm;
3793 const vector< double > & u = _grid->_coords[ iDirZ ];
3794 for ( size_t i = 1; i < planes._zProjs.size(); ++i )
3796 planes._zProjs [i] = zFactor * ( u[i] - u[0] );
3800 const double deflection = _grid->_minCellSize / 20.;
3801 const double tol = _grid->_tol;
3802 E_IntersectPoint ip;
3804 TColStd_MapOfInteger intEdgeIDs; // IDs of not shared INTERNAL EDGES
3806 // Intersect EDGEs with the planes
3807 map< TGeomID, vector< TGeomID > >::const_iterator e2fIt = edge2faceIDsMap.begin();
3808 for ( ; e2fIt != edge2faceIDsMap.end(); ++e2fIt )
3810 const TGeomID edgeID = e2fIt->first;
3811 const TopoDS_Edge & E = TopoDS::Edge( _grid->Shape( edgeID ));
3812 BRepAdaptor_Curve curve( E );
3813 TopoDS_Vertex v1 = helper.IthVertex( 0, E, false );
3814 TopoDS_Vertex v2 = helper.IthVertex( 1, E, false );
3816 ip._faceIDs = e2fIt->second;
3817 ip._shapeID = edgeID;
3819 bool isInternal = ( ip._faceIDs.size() == 1 && _grid->IsInternal( edgeID ));
3822 intEdgeIDs.Add( edgeID );
3823 intEdgeIDs.Add( _grid->ShapeID( v1 ));
3824 intEdgeIDs.Add( _grid->ShapeID( v2 ));
3827 // discretize the EDGE
3828 GCPnts_UniformDeflection discret( curve, deflection, true );
3829 if ( !discret.IsDone() || discret.NbPoints() < 2 )
3832 // perform intersection
3833 E_IntersectPoint* eip, *vip = 0;
3834 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ )
3836 GridPlanes& planes = pln[ iDirZ ];
3837 int iDirX = ( iDirZ + 1 ) % 3;
3838 int iDirY = ( iDirZ + 2 ) % 3;
3839 double xLen = _grid->_coords[ iDirX ].back() - _grid->_coords[ iDirX ][0];
3840 double yLen = _grid->_coords[ iDirY ].back() - _grid->_coords[ iDirY ][0];
3841 double zLen = _grid->_coords[ iDirZ ].back() - _grid->_coords[ iDirZ ][0];
3842 int dIJK[3], d000[3] = { 0,0,0 };
3843 double o[3] = { _grid->_coords[0][0],
3844 _grid->_coords[1][0],
3845 _grid->_coords[2][0] };
3847 // locate the 1st point of a segment within the grid
3848 gp_XYZ p1 = discret.Value( 1 ).XYZ();
3849 double u1 = discret.Parameter( 1 );
3850 double zProj1 = planes._zNorm * ( p1 - _grid->_origin );
3852 _grid->ComputeUVW( p1, ip._uvw );
3853 int iX1 = int(( ip._uvw[iDirX] - o[iDirX]) / xLen * (_grid->_coords[ iDirX ].size() - 1));
3854 int iY1 = int(( ip._uvw[iDirY] - o[iDirY]) / yLen * (_grid->_coords[ iDirY ].size() - 1));
3855 int iZ1 = int(( ip._uvw[iDirZ] - o[iDirZ]) / zLen * (_grid->_coords[ iDirZ ].size() - 1));
3856 locateValue( iX1, ip._uvw[iDirX], _grid->_coords[ iDirX ], dIJK[ iDirX ], tol );
3857 locateValue( iY1, ip._uvw[iDirY], _grid->_coords[ iDirY ], dIJK[ iDirY ], tol );
3858 locateValue( iZ1, ip._uvw[iDirZ], _grid->_coords[ iDirZ ], dIJK[ iDirZ ], tol );
3860 int ijk[3]; // grid index where a segment intersects a plane
3865 // add the 1st vertex point to a hexahedron
3869 ip._shapeID = _grid->ShapeID( v1 );
3870 vip = _grid->Add( ip );
3871 _grid->UpdateFacesOfVertex( *vip, v1 );
3873 vip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3874 if ( !addIntersection( vip, hexes, ijk, d000 ))
3875 _grid->Remove( vip );
3876 ip._shapeID = edgeID;
3878 for ( int iP = 2; iP <= discret.NbPoints(); ++iP )
3880 // locate the 2nd point of a segment within the grid
3881 gp_XYZ p2 = discret.Value( iP ).XYZ();
3882 double u2 = discret.Parameter( iP );
3883 double zProj2 = planes._zNorm * ( p2 - _grid->_origin );
3885 if ( Abs( zProj2 - zProj1 ) > std::numeric_limits<double>::min() )
3887 locateValue( iZ2, zProj2, planes._zProjs, dIJK[ iDirZ ], tol );
3889 // treat intersections with planes between 2 end points of a segment
3890 int dZ = ( iZ1 <= iZ2 ) ? +1 : -1;
3891 int iZ = iZ1 + ( iZ1 < iZ2 );
3892 for ( int i = 0, nb = Abs( iZ1 - iZ2 ); i < nb; ++i, iZ += dZ )
3894 ip._point = findIntPoint( u1, zProj1, u2, zProj2,
3895 planes._zProjs[ iZ ],
3896 curve, planes._zNorm, _grid->_origin );
3897 _grid->ComputeUVW( ip._point.XYZ(), ip._uvw );
3898 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
3899 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
3902 // add ip to hex "above" the plane
3903 eip = _grid->Add( ip );
3905 eip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3907 bool added = addIntersection( eip, hexes, ijk, dIJK);
3909 // add ip to hex "below" the plane
3910 ijk[ iDirZ ] = iZ-1;
3911 if ( !addIntersection( eip, hexes, ijk, dIJK ) &&
3913 _grid->Remove( eip );
3921 // add the 2nd vertex point to a hexahedron
3925 ip._shapeID = _grid->ShapeID( v2 );
3926 _grid->ComputeUVW( p1, ip._uvw );
3927 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
3928 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
3930 bool sameV = ( v1.IsSame( v2 ));
3933 vip = _grid->Add( ip );
3934 _grid->UpdateFacesOfVertex( *vip, v2 );
3936 vip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3938 if ( !addIntersection( vip, hexes, ijk, d000 ) && !sameV )
3939 _grid->Remove( vip );
3940 ip._shapeID = edgeID;
3942 } // loop on 3 grid directions
3946 if ( intEdgeIDs.Size() > 0 )
3947 cutByExtendedInternal( hexes, intEdgeIDs );
3952 //================================================================================
3954 * \brief Fully cut hexes that are partially cut by INTERNAL FACE.
3955 * Cut them by extended INTERNAL FACE.
3957 void Hexahedron::cutByExtendedInternal( std::vector< Hexahedron* >& hexes,
3958 const TColStd_MapOfInteger& intEdgeIDs )
3960 IntAna_IntConicQuad intersection;
3961 SMESHDS_Mesh* meshDS = _grid->_helper->GetMeshDS();
3962 const double tol2 = _grid->_tol * _grid->_tol;
3964 for ( size_t iH = 0; iH < hexes.size(); ++iH )
3966 Hexahedron* hex = hexes[ iH ];
3967 if ( !hex || hex->_eIntPoints.size() < 2 )
3969 if ( !intEdgeIDs.Contains( hex->_eIntPoints.back()->_shapeID ))
3972 // get 3 points on INTERNAL FACE to construct a cutting plane
3973 gp_Pnt p1 = hex->_eIntPoints[0]->_point;
3974 gp_Pnt p2 = hex->_eIntPoints[1]->_point;
3975 gp_Pnt p3 = hex->mostDistantInternalPnt( iH, p1, p2 );
3977 gp_Vec norm = gp_Vec( p1, p2 ) ^ gp_Vec( p1, p3 );
3980 pln = gp_Pln( p1, norm );
3987 TGeomID intFaceID = hex->_eIntPoints.back()->_faceIDs.front(); // FACE being "extended"
3988 TGeomID solidID = _grid->GetSolid( intFaceID )->ID();
3990 // cut links by the plane
3991 //bool isCut = false;
3992 for ( int iLink = 0; iLink < 12; ++iLink )
3994 _Link& link = hex->_hexLinks[ iLink ];
3995 if ( !link._fIntPoints.empty() )
3997 // if ( link._fIntPoints[0]->_faceIDs.back() == _grid->PseudoIntExtFaceID() )
3999 continue; // already cut link
4001 if ( !link._nodes[0]->Node() ||
4002 !link._nodes[1]->Node() )
4003 continue; // outside link
4005 if ( link._nodes[0]->IsOnFace( intFaceID ))
4007 if ( link._nodes[0]->_intPoint->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
4008 if ( p1.SquareDistance( link._nodes[0]->Point() ) < tol2 ||
4009 p2.SquareDistance( link._nodes[0]->Point() ) < tol2 )
4010 link._nodes[0]->_intPoint->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4011 continue; // link is cut by FACE being "extended"
4013 if ( link._nodes[1]->IsOnFace( intFaceID ))
4015 if ( link._nodes[1]->_intPoint->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
4016 if ( p1.SquareDistance( link._nodes[1]->Point() ) < tol2 ||
4017 p2.SquareDistance( link._nodes[1]->Point() ) < tol2 )
4018 link._nodes[1]->_intPoint->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4019 continue; // link is cut by FACE being "extended"
4021 gp_Pnt p4 = link._nodes[0]->Point();
4022 gp_Pnt p5 = link._nodes[1]->Point();
4023 gp_Lin line( p4, gp_Vec( p4, p5 ));
4025 intersection.Perform( line, pln );
4026 if ( !intersection.IsDone() ||
4027 intersection.IsInQuadric() ||
4028 intersection.IsParallel() ||
4029 intersection.NbPoints() < 1 )
4032 double u = intersection.ParamOnConic(1);
4033 if ( u + _grid->_tol < 0 )
4035 int iDir = iLink / 4;
4036 int index = (&hex->_i)[iDir];
4037 double linkLen = _grid->_coords[iDir][index+1] - _grid->_coords[iDir][index];
4038 if ( u - _grid->_tol > linkLen )
4041 if ( u < _grid->_tol ||
4042 u > linkLen - _grid->_tol ) // intersection at grid node
4044 int i = ! ( u < _grid->_tol ); // [0,1]
4045 int iN = link._nodes[ i ] - hex->_hexNodes; // [0-7]
4047 const F_IntersectPoint * & ip = _grid->_gridIntP[ hex->_origNodeInd +
4048 _grid->_nodeShift[iN] ];
4051 ip = _grid->_extIntPool.getNew();
4052 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4053 //ip->_transition = Trans_INTERNAL;
4055 else if ( ip->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
4057 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4059 hex->_nbFaceIntNodes++;
4064 const gp_Pnt& p = intersection.Point( 1 );
4065 F_IntersectPoint* ip = _grid->_extIntPool.getNew();
4066 ip->_node = meshDS->AddNode( p.X(), p.Y(), p.Z() );
4067 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4068 ip->_transition = Trans_INTERNAL;
4069 meshDS->SetNodeInVolume( ip->_node, solidID );
4071 CellsAroundLink fourCells( _grid, iDir );
4072 fourCells.Init( hex->_i, hex->_j, hex->_k, iLink );
4073 int i,j,k, cellIndex;
4074 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing the link
4076 if ( !fourCells.GetCell( iC, i,j,k, cellIndex, iLink ))
4078 Hexahedron * h = hexes[ cellIndex ];
4080 h = hexes[ cellIndex ] = new Hexahedron( *this, i, j, k, cellIndex );
4081 h->_hexLinks[iLink]._fIntPoints.push_back( ip );
4082 h->_nbFaceIntNodes++;
4089 // for ( size_t i = 0; i < hex->_eIntPoints.size(); ++i )
4091 // if ( _grid->IsInternal( hex->_eIntPoints[i]->_shapeID ) &&
4092 // ! hex->_eIntPoints[i]->IsOnFace( _grid->PseudoIntExtFaceID() ))
4093 // hex->_eIntPoints[i]->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
4097 } // loop on all hexes
4101 //================================================================================
4103 * \brief Return intersection point on INTERNAL FACE most distant from given ones
4105 gp_Pnt Hexahedron::mostDistantInternalPnt( int hexIndex, const gp_Pnt& p1, const gp_Pnt& p2 )
4107 gp_Pnt resultPnt = p1;
4109 double maxDist2 = 0;
4110 for ( int iLink = 0; iLink < 12; ++iLink ) // check links
4112 _Link& link = _hexLinks[ iLink ];
4113 for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
4114 if ( _grid->PseudoIntExtFaceID() != link._fIntPoints[i]->_faceIDs[0] &&
4115 _grid->IsInternal( link._fIntPoints[i]->_faceIDs[0] ) &&
4116 link._fIntPoints[i]->_node )
4118 gp_Pnt p = SMESH_NodeXYZ( link._fIntPoints[i]->_node );
4119 double d = p1.SquareDistance( p );
4127 d = p2.SquareDistance( p );
4137 _origNodeInd = _grid->NodeIndex( _i,_j,_k );
4139 for ( size_t iN = 0; iN < 8; ++iN ) // check corners
4141 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
4142 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
4143 if ( _hexNodes[iN]._intPoint )
4144 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
4146 if ( _grid->IsInternal( _hexNodes[iN]._intPoint->_faceIDs[iF]))
4148 gp_Pnt p = SMESH_NodeXYZ( _hexNodes[iN]._node );
4149 double d = p1.SquareDistance( p );
4157 d = p2.SquareDistance( p );
4167 if ( maxDist2 < _grid->_tol * _grid->_tol )
4173 //================================================================================
4175 * \brief Finds intersection of a curve with a plane
4176 * \param [in] u1 - parameter of one curve point
4177 * \param [in] proj1 - projection of the curve point to the plane normal
4178 * \param [in] u2 - parameter of another curve point
4179 * \param [in] proj2 - projection of the other curve point to the plane normal
4180 * \param [in] proj - projection of a point where the curve intersects the plane
4181 * \param [in] curve - the curve
4182 * \param [in] axis - the plane normal
4183 * \param [in] origin - the plane origin
4184 * \return gp_Pnt - the found intersection point
4186 gp_Pnt Hexahedron::findIntPoint( double u1, double proj1,
4187 double u2, double proj2,
4189 BRepAdaptor_Curve& curve,
4191 const gp_XYZ& origin)
4193 double r = (( proj - proj1 ) / ( proj2 - proj1 ));
4194 double u = u1 * ( 1 - r ) + u2 * r;
4195 gp_Pnt p = curve.Value( u );
4196 double newProj = axis * ( p.XYZ() - origin );
4197 if ( Abs( proj - newProj ) > _grid->_tol / 10. )
4200 return findIntPoint( u2, proj2, u, newProj, proj, curve, axis, origin );
4202 return findIntPoint( u1, proj2, u, newProj, proj, curve, axis, origin );
4207 //================================================================================
4209 * \brief Returns indices of a hexahedron sub-entities holding a point
4210 * \param [in] ip - intersection point
4211 * \param [out] facets - 0-3 facets holding a point
4212 * \param [out] sub - index of a vertex or an edge holding a point
4213 * \return int - number of facets holding a point
4215 int Hexahedron::getEntity( const E_IntersectPoint* ip, int* facets, int& sub )
4217 enum { X = 1, Y = 2, Z = 4 }; // == 001, 010, 100
4219 int vertex = 0, edgeMask = 0;
4221 if ( Abs( _grid->_coords[0][ _i ] - ip->_uvw[0] ) < _grid->_tol ) {
4222 facets[ nbFacets++ ] = SMESH_Block::ID_F0yz;
4225 else if ( Abs( _grid->_coords[0][ _i+1 ] - ip->_uvw[0] ) < _grid->_tol ) {
4226 facets[ nbFacets++ ] = SMESH_Block::ID_F1yz;
4230 if ( Abs( _grid->_coords[1][ _j ] - ip->_uvw[1] ) < _grid->_tol ) {
4231 facets[ nbFacets++ ] = SMESH_Block::ID_Fx0z;
4234 else if ( Abs( _grid->_coords[1][ _j+1 ] - ip->_uvw[1] ) < _grid->_tol ) {
4235 facets[ nbFacets++ ] = SMESH_Block::ID_Fx1z;
4239 if ( Abs( _grid->_coords[2][ _k ] - ip->_uvw[2] ) < _grid->_tol ) {
4240 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy0;
4243 else if ( Abs( _grid->_coords[2][ _k+1 ] - ip->_uvw[2] ) < _grid->_tol ) {
4244 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy1;
4251 case 0: sub = 0; break;
4252 case 1: sub = facets[0]; break;
4254 const int edge [3][8] = {
4255 { SMESH_Block::ID_E00z, SMESH_Block::ID_E10z,
4256 SMESH_Block::ID_E01z, SMESH_Block::ID_E11z },
4257 { SMESH_Block::ID_E0y0, SMESH_Block::ID_E1y0, 0, 0,
4258 SMESH_Block::ID_E0y1, SMESH_Block::ID_E1y1 },
4259 { SMESH_Block::ID_Ex00, 0, SMESH_Block::ID_Ex10, 0,
4260 SMESH_Block::ID_Ex01, 0, SMESH_Block::ID_Ex11 }
4262 switch ( edgeMask ) {
4263 case X | Y: sub = edge[ 0 ][ vertex ]; break;
4264 case X | Z: sub = edge[ 1 ][ vertex ]; break;
4265 default: sub = edge[ 2 ][ vertex ];
4271 sub = vertex + SMESH_Block::ID_FirstV;
4276 //================================================================================
4278 * \brief Adds intersection with an EDGE
4280 bool Hexahedron::addIntersection( const E_IntersectPoint* ip,
4281 vector< Hexahedron* >& hexes,
4282 int ijk[], int dIJK[] )
4286 size_t hexIndex[4] = {
4287 _grid->CellIndex( ijk[0], ijk[1], ijk[2] ),
4288 dIJK[0] ? _grid->CellIndex( ijk[0]+dIJK[0], ijk[1], ijk[2] ) : -1,
4289 dIJK[1] ? _grid->CellIndex( ijk[0], ijk[1]+dIJK[1], ijk[2] ) : -1,
4290 dIJK[2] ? _grid->CellIndex( ijk[0], ijk[1], ijk[2]+dIJK[2] ) : -1
4292 for ( int i = 0; i < 4; ++i )
4294 if ( hexIndex[i] < hexes.size() && hexes[ hexIndex[i] ] )
4296 Hexahedron* h = hexes[ hexIndex[i] ];
4297 h->_eIntPoints.reserve(2);
4298 h->_eIntPoints.push_back( ip );
4301 // check if ip is really inside the hex
4302 if (SALOME::VerbosityActivated() && h->isOutParam( ip->_uvw ))
4303 throw SALOME_Exception("ip outside a hex");
4308 //================================================================================
4310 * \brief Check if a hexahedron facet lies on a FACE
4311 * Also return true if the facet does not interfere with any FACE
4313 bool Hexahedron::isQuadOnFace( const size_t iQuad )
4315 _Face& quad = _hexQuads[ iQuad ] ;
4317 int nbGridNodesInt = 0; // nb FACE intersections at grid nodes
4318 int nbNoGeomNodes = 0;
4319 for ( int iE = 0; iE < 4; ++iE )
4321 nbNoGeomNodes = ( !quad._links[ iE ].FirstNode()->_intPoint &&
4322 quad._links[ iE ].NbResultLinks() == 1 );
4324 ( quad._links[ iE ].FirstNode()->_intPoint &&
4325 quad._links[ iE ].NbResultLinks() == 1 &&
4326 quad._links[ iE ].ResultLink( 0 ).FirstNode() == quad._links[ iE ].FirstNode() &&
4327 quad._links[ iE ].ResultLink( 0 ).LastNode() == quad._links[ iE ].LastNode() );
4329 if ( nbNoGeomNodes == 4 )
4332 if ( nbGridNodesInt == 4 ) // all quad nodes are at FACE intersection
4334 size_t iEmin = 0, minNbFaces = 1000;
4335 for ( int iE = 0; iE < 4; ++iE ) // look for a node with min nb FACEs
4337 size_t nbFaces = quad._links[ iE ].FirstNode()->faces().size();
4338 if ( minNbFaces > nbFaces )
4341 minNbFaces = nbFaces;
4344 // check if there is a FACE passing through all 4 nodes
4345 for ( const TGeomID& faceID : quad._links[ iEmin ].FirstNode()->faces() )
4347 bool allNodesAtFace = true;
4348 for ( size_t iE = 0; iE < 4 && allNodesAtFace; ++iE )
4349 allNodesAtFace = ( iE == iEmin ||
4350 quad._links[ iE ].FirstNode()->IsOnFace( faceID ));
4351 if ( allNodesAtFace ) // quad if on faceID
4357 //================================================================================
4359 * \brief Finds nodes at a path from one node to another via intersections with EDGEs
4361 bool Hexahedron::findChain( _Node* n1,
4364 vector<_Node*>& chn )
4367 chn.push_back( n1 );
4368 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4369 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
4370 n1->IsLinked( quad._eIntNodes[ iP ]->_intPoint ) &&
4371 n2->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
4373 chn.push_back( quad._eIntNodes[ iP ]);
4374 chn.push_back( n2 );
4375 quad._eIntNodes[ iP ]->_usedInFace = &quad;
4382 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4383 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
4384 chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
4386 chn.push_back( quad._eIntNodes[ iP ]);
4387 found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
4390 } while ( found && ! chn.back()->IsLinked( n2->_intPoint ) );
4392 if ( chn.back() != n2 && chn.back()->IsLinked( n2->_intPoint ))
4393 chn.push_back( n2 );
4395 return chn.size() > 1;
4397 //================================================================================
4399 * \brief Try to heal a polygon whose ends are not connected
4401 bool Hexahedron::closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const
4403 int i = -1, nbLinks = polygon->_links.size();
4406 vector< _OrientedLink > newLinks;
4407 // find a node lying on the same FACE as the last one
4408 _Node* node = polygon->_links.back().LastNode();
4409 TGeomID avoidFace = node->IsLinked( polygon->_links.back().FirstNode()->_intPoint );
4410 for ( i = nbLinks - 2; i >= 0; --i )
4411 if ( node->IsLinked( polygon->_links[i].FirstNode()->_intPoint, avoidFace ))
4415 for ( ; i < nbLinks; ++i )
4416 newLinks.push_back( polygon->_links[i] );
4420 // find a node lying on the same FACE as the first one
4421 node = polygon->_links[0].FirstNode();
4422 avoidFace = node->IsLinked( polygon->_links[0].LastNode()->_intPoint );
4423 for ( i = 1; i < nbLinks; ++i )
4424 if ( node->IsLinked( polygon->_links[i].LastNode()->_intPoint, avoidFace ))
4427 for ( nbLinks = i + 1, i = 0; i < nbLinks; ++i )
4428 newLinks.push_back( polygon->_links[i] );
4430 if ( newLinks.size() > 1 )
4432 polygon->_links.swap( newLinks );
4434 chainNodes.push_back( polygon->_links.back().LastNode() );
4435 chainNodes.push_back( polygon->_links[0].FirstNode() );
4440 //================================================================================
4442 * \brief Finds nodes on the same EDGE as the first node of avoidSplit.
4444 * This function is for
4445 * 1) a case where an EDGE lies on a quad which lies on a FACE
4446 * so that a part of quad in ON and another part is IN
4447 * 2) INTERNAL FACE passes through the 1st node of avoidSplit
4449 bool Hexahedron::findChainOnEdge( const vector< _OrientedLink >& splits,
4450 const _OrientedLink& prevSplit,
4451 const _OrientedLink& avoidSplit,
4452 const std::set< TGeomID > & concaveFaces,
4455 vector<_Node*>& chn )
4457 _Node* pn1 = prevSplit.FirstNode();
4458 _Node* pn2 = prevSplit.LastNode(); // pn2 is on EDGE, if not on INTERNAL FACE
4459 _Node* an3 = avoidSplit.LastNode();
4460 TGeomID avoidFace = pn1->IsLinked( pn2->_intPoint ); // FACE under the quad
4461 if ( avoidFace < 1 && pn1->_intPoint )
4466 if ( !quad._eIntNodes.empty() ) // connect pn2 with EDGE intersections
4468 chn.push_back( pn2 );
4473 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4474 if (( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad )) &&
4475 ( chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint, avoidFace )) &&
4476 ( !avoidFace || quad._eIntNodes[ iP ]->IsOnFace( avoidFace )))
4478 chn.push_back( quad._eIntNodes[ iP ]);
4479 found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
4486 _Node* n = 0, *stopNode = avoidSplit.LastNode();
4488 if ( pn2 == prevSplit.LastNode() && // pn2 is at avoidSplit.FirstNode()
4489 !isCorner( stopNode )) // stopNode is in the middle of a _hexLinks
4491 // move stopNode to a _hexNodes
4492 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
4493 for ( size_t iL = 0; iL < quad._links[ iE ].NbResultLinks(); ++iL )
4495 const _Link* sideSplit = & quad._links[ iE ]._link->_splits[ iL ];
4496 if ( sideSplit == avoidSplit._link )
4498 if ( quad._links[ iE ].LastNode()->Node() )
4499 stopNode = quad._links[ iE ].LastNode();
4506 // connect pn2 (probably new, at _eIntNodes) with a split
4510 TGeomID commonFaces[20];
4511 _Node* nPrev = nullptr;
4512 for ( i = splits.size()-1; i >= 0; --i )
4518 for ( int is1st = 0; is1st < 2; ++is1st )
4520 _Node* nConn = is1st ? splits[i].FirstNode() : splits[i].LastNode();
4521 if ( nConn == nPrev )
4528 if (( stop = ( nConn == stopNode )))
4530 // find a FACE connecting nConn with pn2 but not with an3
4531 if (( nConn != pn1 ) &&
4532 ( nConn->_intPoint && !nConn->_intPoint->_faceIDs.empty() ) &&
4533 ( nbCommon = nConn->GetCommonFaces( pn2->_intPoint, commonFaces )))
4535 bool a3Coonect = true;
4536 for ( size_t iF = 0; iF < nbCommon && a3Coonect; ++iF )
4537 a3Coonect = an3->IsOnFace( commonFaces[ iF ]) || concaveFaces.count( commonFaces[ iF ]);
4546 if ( nbCommon > 1 ) // nConn is linked with pn2 by an EDGE
4562 if ( n && n != stopNode )
4565 chn.push_back( pn2 );
4570 else if ( !chn.empty() && chn.back()->_isInternalFlags )
4572 // INTERNAL FACE partially cuts the quad
4573 for ( int ip = chn.size() - 2; ip >= 0; --ip )
4574 chn.push_back( chn[ ip ]);
4579 //================================================================================
4581 * \brief Checks transition at the ginen intersection node of a link
4583 bool Hexahedron::isOutPoint( _Link& link, int iP,
4584 SMESH_MesherHelper& helper, const Solid* solid ) const
4588 if ( link._fIntNodes[iP]->faces().size() == 1 &&
4589 _grid->IsInternal( link._fIntNodes[iP]->face(0) ))
4592 const bool moreIntPoints = ( iP+1 < (int) link._fIntNodes.size() );
4595 _Node* n1 = link._fIntNodes[ iP ];
4597 n1 = link._nodes[0];
4598 _Node* n2 = moreIntPoints ? link._fIntNodes[ iP+1 ] : 0;
4599 if ( !n2 || !n2->Node() )
4600 n2 = link._nodes[1];
4604 // get all FACEs under n1 and n2
4605 set< TGeomID > faceIDs;
4606 if ( moreIntPoints ) faceIDs.insert( link._fIntNodes[iP+1]->faces().begin(),
4607 link._fIntNodes[iP+1]->faces().end() );
4608 if ( n2->_intPoint ) faceIDs.insert( n2->_intPoint->_faceIDs.begin(),
4609 n2->_intPoint->_faceIDs.end() );
4610 if ( faceIDs.empty() )
4611 return false; // n2 is inside
4612 if ( n1->_intPoint ) faceIDs.insert( n1->_intPoint->_faceIDs.begin(),
4613 n1->_intPoint->_faceIDs.end() );
4614 faceIDs.insert( link._fIntNodes[iP]->faces().begin(),
4615 link._fIntNodes[iP]->faces().end() );
4617 // get a point between 2 nodes
4618 gp_Pnt p1 = n1->Point();
4619 gp_Pnt p2 = n2->Point();
4620 gp_Pnt pOnLink = 0.8 * p1.XYZ() + 0.2 * p2.XYZ();
4622 TopLoc_Location loc;
4624 set< TGeomID >::iterator faceID = faceIDs.begin();
4625 for ( ; faceID != faceIDs.end(); ++faceID )
4627 // project pOnLink on a FACE
4628 if ( *faceID < 1 || !solid->Contains( *faceID )) continue;
4629 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( *faceID ));
4630 GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( face, loc, 0.1*_grid->_tol );
4631 gp_Pnt testPnt = pOnLink.Transformed( loc.Transformation().Inverted() );
4632 proj.Perform( testPnt );
4633 if ( proj.IsDone() && proj.NbPoints() > 0 )
4636 proj.LowerDistanceParameters( u,v );
4638 if ( proj.LowerDistance() <= 0.1 * _grid->_tol )
4644 // find isOut by normals
4646 if ( GeomLib::NormEstim( BRep_Tool::Surface( face, loc ),
4651 if ( solid->Orientation( face ) == TopAbs_REVERSED )
4653 gp_Vec v( proj.NearestPoint(), testPnt );
4654 isOut = ( v * normal > 0 );
4659 // classify a projection
4660 if ( !n1->IsOnFace( *faceID ) || !n2->IsOnFace( *faceID ))
4662 BRepTopAdaptor_FClass2d cls( face, Precision::Confusion() );
4663 TopAbs_State state = cls.Perform( gp_Pnt2d( u,v ));
4664 if ( state == TopAbs_OUT )
4676 //================================================================================
4678 * \brief Sort nodes on a FACE
4680 void Hexahedron::sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID faceID)
4682 if ( nodes.size() > 20 ) return;
4684 // get shapes under nodes
4685 TGeomID nShapeIds[20], *nShapeIdsEnd = &nShapeIds[0] + nodes.size();
4686 for ( size_t i = 0; i < nodes.size(); ++i )
4687 if ( !( nShapeIds[i] = nodes[i]->ShapeID() ))
4690 // get shapes of the FACE
4691 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( faceID ));
4692 list< TopoDS_Edge > edges;
4693 list< int > nbEdges;
4694 int nbW = SMESH_Block::GetOrderedEdges (face, edges, nbEdges);
4696 // select a WIRE - remove EDGEs of irrelevant WIREs from edges
4697 list< TopoDS_Edge >::iterator e = edges.begin(), eEnd = e;
4698 list< int >::iterator nE = nbEdges.begin();
4699 for ( ; nbW > 0; ++nE, --nbW )
4701 std::advance( eEnd, *nE );
4702 for ( ; e != eEnd; ++e )
4703 for ( int i = 0; i < 2; ++i )
4706 _grid->ShapeID( *e ) :
4707 _grid->ShapeID( SMESH_MesherHelper::IthVertex( 0, *e ));
4709 ( std::find( &nShapeIds[0], nShapeIdsEnd, id ) != nShapeIdsEnd ))
4711 edges.erase( eEnd, edges.end() ); // remove rest wires
4712 e = eEnd = edges.end();
4719 edges.erase( edges.begin(), eEnd ); // remove a current irrelevant wire
4722 // rotate edges to have the first one at least partially out of the hexa
4723 list< TopoDS_Edge >::iterator e = edges.begin(), eMidOut = edges.end();
4724 for ( ; e != edges.end(); ++e )
4726 if ( !_grid->ShapeID( *e ))
4731 for ( int i = 0; i < 2 && !isOut; ++i )
4735 TopoDS_Vertex v = SMESH_MesherHelper::IthVertex( 0, *e );
4736 p = BRep_Tool::Pnt( v );
4738 else if ( eMidOut == edges.end() )
4740 TopLoc_Location loc;
4741 Handle(Geom_Curve) c = BRep_Tool::Curve( *e, loc, f, l);
4742 if ( c.IsNull() ) break;
4743 p = c->Value( 0.5 * ( f + l )).Transformed( loc );
4750 _grid->ComputeUVW( p.XYZ(), uvw );
4751 if ( isOutParam( uvw ))
4762 if ( e != edges.end() )
4763 edges.splice( edges.end(), edges, edges.begin(), e );
4764 else if ( eMidOut != edges.end() )
4765 edges.splice( edges.end(), edges, edges.begin(), eMidOut );
4767 // sort nodes according to the order of edges
4768 _Node* orderNodes [20];
4769 //TGeomID orderShapeIDs[20];
4771 TGeomID id, *pID = 0;
4772 for ( e = edges.begin(); e != edges.end(); ++e )
4774 if (( id = _grid->ShapeID( SMESH_MesherHelper::IthVertex( 0, *e ))) &&
4775 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
4777 //orderShapeIDs[ nbN ] = id;
4778 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
4781 if (( id = _grid->ShapeID( *e )) &&
4782 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
4784 //orderShapeIDs[ nbN ] = id;
4785 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
4789 if ( nbN != nodes.size() )
4792 bool reverse = ( orderNodes[0 ]->Point().SquareDistance( curNode->Point() ) >
4793 orderNodes[nbN-1]->Point().SquareDistance( curNode->Point() ));
4795 for ( size_t i = 0; i < nodes.size(); ++i )
4796 nodes[ i ] = orderNodes[ reverse ? nbN-1-i : i ];
4799 //================================================================================
4801 * \brief Adds computed elements to the mesh
4803 int Hexahedron::addVolumes( SMESH_MesherHelper& helper )
4805 F_IntersectPoint noIntPnt;
4806 const bool toCheckNodePos = _grid->IsToCheckNodePos();
4809 // add elements resulted from hexahedron intersection
4810 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4812 vector< const SMDS_MeshNode* > nodes( volDef->_nodes.size() );
4813 for ( size_t iN = 0; iN < nodes.size(); ++iN )
4815 if ( !( nodes[iN] = volDef->_nodes[iN].Node() ))
4817 if ( const E_IntersectPoint* eip = volDef->_nodes[iN].EdgeIntPnt() )
4819 nodes[iN] = volDef->_nodes[iN]._intPoint->_node =
4820 helper.AddNode( eip->_point.X(),
4823 if ( _grid->ShapeType( eip->_shapeID ) == TopAbs_VERTEX )
4824 helper.GetMeshDS()->SetNodeOnVertex( nodes[iN], eip->_shapeID );
4826 helper.GetMeshDS()->SetNodeOnEdge( nodes[iN], eip->_shapeID );
4829 throw SALOME_Exception("Bug: no node at intersection point");
4831 else if ( volDef->_nodes[iN]._intPoint &&
4832 volDef->_nodes[iN]._intPoint->_node == volDef->_nodes[iN]._node )
4834 // Update position of node at EDGE intersection;
4835 // see comment to _Node::Add( E_IntersectPoint )
4836 SMESHDS_Mesh* mesh = helper.GetMeshDS();
4837 TGeomID shapeID = volDef->_nodes[iN].EdgeIntPnt()->_shapeID;
4838 mesh->UnSetNodeOnShape( nodes[iN] );
4839 if ( _grid->ShapeType( shapeID ) == TopAbs_VERTEX )
4840 mesh->SetNodeOnVertex( nodes[iN], shapeID );
4842 mesh->SetNodeOnEdge( nodes[iN], shapeID );
4844 else if ( toCheckNodePos &&
4845 !nodes[iN]->isMarked() &&
4846 _grid->ShapeType( nodes[iN]->GetShapeID() ) == TopAbs_FACE )
4848 _grid->SetOnShape( nodes[iN], noIntPnt, /*v=*/nullptr,/*unset=*/true );
4849 nodes[iN]->setIsMarked( true );
4851 } // loop to get nodes
4853 const SMDS_MeshElement* v = 0;
4854 if ( !volDef->_quantities.empty() )
4856 v = helper.AddPolyhedralVolume( nodes, volDef->_quantities );
4857 volDef->_size = SMDS_VolumeTool( v ).GetSize();
4858 if ( volDef->_size < 0 ) // invalid polyhedron
4860 if ( ! SMESH_MeshEditor( helper.GetMesh() ).Reorient( v ) || // try to fix
4861 SMDS_VolumeTool( v ).GetSize() < 0 )
4863 helper.GetMeshDS()->RemoveFreeElement( v, /*sm=*/nullptr, /*fromGroups=*/false );
4865 //_hasTooSmall = true;
4867 if (SALOME::VerbosityActivated())
4869 std::cout << "Remove INVALID polyhedron, _cellID = " << _cellID
4870 << " ijk = ( " << _i << " " << _j << " " << _k << " ) "
4871 << " solid " << volDef->_solidID << std::endl;
4878 switch ( nodes.size() )
4880 case 8: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],
4881 nodes[4],nodes[5],nodes[6],nodes[7] );
4883 case 4: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3] );
4885 case 6: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4],nodes[5] );
4887 case 5: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4] );
4891 volDef->_volume = v;
4892 nbAdded += bool( v );
4894 } // loop on _volumeDefs chain
4896 // avoid creating overlapping volumes (bos #24052)
4899 double sumSize = 0, maxSize = 0;
4900 _volumeDef* maxSizeDef = nullptr;
4901 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4903 if ( !volDef->_volume )
4905 sumSize += volDef->_size;
4906 if ( volDef->_size > maxSize )
4908 maxSize = volDef->_size;
4909 maxSizeDef = volDef;
4912 if ( sumSize > _sideLength[0] * _sideLength[1] * _sideLength[2] * 1.05 )
4914 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4915 if ( volDef != maxSizeDef && volDef->_volume )
4917 helper.GetMeshDS()->RemoveFreeElement( volDef->_volume, /*sm=*/nullptr,
4918 /*fromGroups=*/false );
4919 volDef->_volume = nullptr;
4920 //volDef->_nodes.clear();
4926 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4928 if ( volDef->_volume )
4930 helper.GetMeshDS()->SetMeshElementOnShape( volDef->_volume, volDef->_solidID );
4936 //================================================================================
4938 * \brief Return true if the element is in a hole
4940 bool Hexahedron::isInHole() const
4942 if ( !_vIntNodes.empty() )
4945 const size_t ijk[3] = { _i, _j, _k };
4946 F_IntersectPoint curIntPnt;
4948 // consider a cell to be in a hole if all links in any direction
4949 // comes OUT of geometry
4950 for ( int iDir = 0; iDir < 3; ++iDir )
4952 const vector<double>& coords = _grid->_coords[ iDir ];
4953 LineIndexer li = _grid->GetLineIndexer( iDir );
4954 li.SetIJK( _i,_j,_k );
4955 size_t lineIndex[4] = { li.LineIndex (),
4959 bool allLinksOut = true, hasLinks = false;
4960 for ( int iL = 0; iL < 4 && allLinksOut; ++iL ) // loop on 4 links parallel to iDir
4962 const _Link& link = _hexLinks[ iL + 4*iDir ];
4963 // check transition of the first node of a link
4964 const F_IntersectPoint* firstIntPnt = 0;
4965 if ( link._nodes[0]->Node() ) // 1st node is a hexa corner
4967 curIntPnt._paramOnLine = coords[ ijk[ iDir ]] - coords[0] + _grid->_tol;
4968 const GridLine& line = _grid->_lines[ iDir ][ lineIndex[ iL ]];
4969 if ( !line._intPoints.empty() )
4971 multiset< F_IntersectPoint >::const_iterator ip =
4972 line._intPoints.upper_bound( curIntPnt );
4974 firstIntPnt = &(*ip);
4977 else if ( !link._fIntPoints.empty() )
4979 firstIntPnt = link._fIntPoints[0];
4985 allLinksOut = ( firstIntPnt->_transition == Trans_OUT &&
4986 !_grid->IsShared( firstIntPnt->_faceIDs[0] ));
4989 if ( hasLinks && allLinksOut )
4995 //================================================================================
4997 * \brief Check if a polyherdon has an edge lying on EDGE shared by strange FACE
4998 * that will be meshed by other algo
5000 bool Hexahedron::hasStrangeEdge() const
5002 if ( _eIntPoints.size() < 2 )
5005 TopTools_MapOfShape edges;
5006 for ( size_t i = 0; i < _eIntPoints.size(); ++i )
5008 if ( !_grid->IsStrangeEdge( _eIntPoints[i]->_shapeID ))
5010 const TopoDS_Shape& s = _grid->Shape( _eIntPoints[i]->_shapeID );
5011 if ( s.ShapeType() == TopAbs_EDGE )
5013 if ( ! edges.Add( s ))
5014 return true; // an EDGE encounters twice
5018 PShapeIteratorPtr edgeIt = _grid->_helper->GetAncestors( s,
5019 *_grid->_helper->GetMesh(),
5021 while ( const TopoDS_Shape* edge = edgeIt->next() )
5022 if ( ! edges.Add( *edge ))
5023 return true; // an EDGE encounters twice
5029 //================================================================================
5031 * \brief Return true if a polyhedron passes _sizeThreshold criterion
5033 bool Hexahedron::checkPolyhedronSize( bool cutByInternalFace, double & volume) const
5037 if ( cutByInternalFace && !_grid->_toUseThresholdForInternalFaces )
5039 // check if any polygon fully lies on shared/internal FACEs
5040 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
5042 const _Face& polygon = _polygons[iP];
5043 if ( polygon._links.empty() )
5045 bool allNodesInternal = true;
5046 for ( size_t iL = 0; iL < polygon._links.size() && allNodesInternal; ++iL )
5048 _Node* n = polygon._links[ iL ].FirstNode();
5049 allNodesInternal = (( n->IsCutByInternal() ) ||
5050 ( n->_intPoint && _grid->IsAnyShared( n->_intPoint->_faceIDs )));
5052 if ( allNodesInternal )
5056 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
5058 const _Face& polygon = _polygons[iP];
5059 if ( polygon._links.empty() )
5061 gp_XYZ area (0,0,0);
5062 gp_XYZ p1 = polygon._links[ 0 ].FirstNode()->Point().XYZ();
5063 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
5065 gp_XYZ p2 = polygon._links[ iL ].LastNode()->Point().XYZ();
5069 volume += p1 * area;
5073 if ( this->hasStrangeEdge() && volume > 1e-13 )
5076 double initVolume = _sideLength[0] * _sideLength[1] * _sideLength[2];
5078 return volume > initVolume / _grid->_sizeThreshold;
5080 //================================================================================
5082 * \brief Tries to create a hexahedron
5084 bool Hexahedron::addHexa()
5086 int nbQuad = 0, iQuad = -1;
5087 for ( size_t i = 0; i < _polygons.size(); ++i )
5089 if ( _polygons[i]._links.empty() )
5091 if ( _polygons[i]._links.size() != 4 )
5102 for ( int iL = 0; iL < 4; ++iL )
5105 nodes[iL] = _polygons[iQuad]._links[iL].FirstNode();
5108 // find a top node above the base node
5109 _Link* link = _polygons[iQuad]._links[iL]._link;
5110 if ( !link->_faces[0] || !link->_faces[1] )
5111 return debugDumpLink( link );
5112 // a quadrangle sharing <link> with _polygons[iQuad]
5113 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[iQuad] )];
5114 for ( int i = 0; i < 4; ++i )
5115 if ( quad->_links[i]._link == link )
5117 // 1st node of a link opposite to <link> in <quad>
5118 nodes[iL+4] = quad->_links[(i+2)%4].FirstNode();
5124 _volumeDefs.Set( &nodes[0], 8 );
5128 //================================================================================
5130 * \brief Tries to create a tetrahedron
5132 bool Hexahedron::addTetra()
5135 for ( size_t i = 0; i < _polygons.size() && iTria < 0; ++i )
5136 if ( _polygons[i]._links.size() == 3 )
5142 nodes[0] = _polygons[iTria]._links[0].FirstNode();
5143 nodes[1] = _polygons[iTria]._links[1].FirstNode();
5144 nodes[2] = _polygons[iTria]._links[2].FirstNode();
5146 _Link* link = _polygons[iTria]._links[0]._link;
5147 if ( !link->_faces[0] || !link->_faces[1] )
5148 return debugDumpLink( link );
5150 // a triangle sharing <link> with _polygons[0]
5151 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[iTria] )];
5152 for ( int i = 0; i < 3; ++i )
5153 if ( tria->_links[i]._link == link )
5155 nodes[3] = tria->_links[(i+1)%3].LastNode();
5156 _volumeDefs.Set( &nodes[0], 4 );
5162 //================================================================================
5164 * \brief Tries to create a pentahedron
5166 bool Hexahedron::addPenta()
5168 // find a base triangular face
5170 for ( int iF = 0; iF < 5 && iTri < 0; ++iF )
5171 if ( _polygons[ iF ]._links.size() == 3 )
5173 if ( iTri < 0 ) return false;
5178 for ( int iL = 0; iL < 3; ++iL )
5181 nodes[iL] = _polygons[ iTri ]._links[iL].FirstNode();
5184 // find a top node above the base node
5185 _Link* link = _polygons[ iTri ]._links[iL]._link;
5186 if ( !link->_faces[0] || !link->_faces[1] )
5187 return debugDumpLink( link );
5188 // a quadrangle sharing <link> with a base triangle
5189 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[ iTri ] )];
5190 if ( quad->_links.size() != 4 ) return false;
5191 for ( int i = 0; i < 4; ++i )
5192 if ( quad->_links[i]._link == link )
5194 // 1st node of a link opposite to <link> in <quad>
5195 nodes[iL+3] = quad->_links[(i+2)%4].FirstNode();
5201 _volumeDefs.Set( &nodes[0], 6 );
5203 return ( nbN == 6 );
5205 //================================================================================
5207 * \brief Tries to create a pyramid
5209 bool Hexahedron::addPyra()
5211 // find a base quadrangle
5213 for ( int iF = 0; iF < 5 && iQuad < 0; ++iF )
5214 if ( _polygons[ iF ]._links.size() == 4 )
5216 if ( iQuad < 0 ) return false;
5220 nodes[0] = _polygons[iQuad]._links[0].FirstNode();
5221 nodes[1] = _polygons[iQuad]._links[1].FirstNode();
5222 nodes[2] = _polygons[iQuad]._links[2].FirstNode();
5223 nodes[3] = _polygons[iQuad]._links[3].FirstNode();
5225 _Link* link = _polygons[iQuad]._links[0]._link;
5226 if ( !link->_faces[0] || !link->_faces[1] )
5227 return debugDumpLink( link );
5229 // a triangle sharing <link> with a base quadrangle
5230 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[ iQuad ] )];
5231 if ( tria->_links.size() != 3 ) return false;
5232 for ( int i = 0; i < 3; ++i )
5233 if ( tria->_links[i]._link == link )
5235 nodes[4] = tria->_links[(i+1)%3].LastNode();
5236 _volumeDefs.Set( &nodes[0], 5 );
5242 //================================================================================
5244 * \brief Return true if there are _eIntPoints at EDGEs forming a concave corner
5246 bool Hexahedron::hasEdgesAround( const ConcaveFace* cf ) const
5249 ConcaveFace foundGeomHolder;
5250 for ( const E_IntersectPoint* ip : _eIntPoints )
5252 if ( cf->HasEdge( ip->_shapeID ))
5254 if ( ++nbEdges == 2 )
5256 foundGeomHolder.SetEdge( ip->_shapeID );
5258 else if ( ip->_faceIDs.size() >= 3 )
5260 const TGeomID & vID = ip->_shapeID;
5261 if ( cf->HasVertex( vID ) && !foundGeomHolder.HasVertex( vID ))
5263 if ( ++nbEdges == 2 )
5265 foundGeomHolder.SetVertex( vID );
5270 for ( const _Node& hexNode: _hexNodes )
5272 if ( !hexNode._node || !hexNode._intPoint )
5274 const B_IntersectPoint* ip = hexNode._intPoint;
5275 if ( ip->_faceIDs.size() == 2 ) // EDGE
5277 TGeomID edgeID = hexNode._node->GetShapeID();
5278 if ( cf->HasEdge( edgeID ) && !foundGeomHolder.HasEdge( edgeID ))
5280 foundGeomHolder.SetEdge( edgeID );
5281 if ( ++nbEdges == 2 )
5285 else if ( ip->_faceIDs.size() >= 3 ) // VERTEX
5287 TGeomID vID = hexNode._node->GetShapeID();
5288 if ( cf->HasVertex( vID ) && !foundGeomHolder.HasVertex( vID ))
5290 if ( ++nbEdges == 2 )
5292 foundGeomHolder.SetVertex( vID );
5299 //================================================================================
5301 * \brief Dump a link and return \c false
5303 bool Hexahedron::debugDumpLink( Hexahedron::_Link* link )
5305 if (SALOME::VerbosityActivated())
5307 gp_Pnt p1 = link->_nodes[0]->Point(), p2 = link->_nodes[1]->Point();
5308 cout << "BUG: not shared link. IKJ = ( "<< _i << " " << _j << " " << _k << " )" << endl
5309 << "n1 (" << p1.X() << ", "<< p1.Y() << ", "<< p1.Z() << " )" << endl
5310 << "n2 (" << p2.X() << ", "<< p2.Y() << ", "<< p2.Z() << " )" << endl;
5315 //================================================================================
5317 * \brief Classify a point by grid parameters
5319 bool Hexahedron::isOutParam(const double uvw[3]) const
5321 return (( _grid->_coords[0][ _i ] - _grid->_tol > uvw[0] ) ||
5322 ( _grid->_coords[0][ _i+1 ] + _grid->_tol < uvw[0] ) ||
5323 ( _grid->_coords[1][ _j ] - _grid->_tol > uvw[1] ) ||
5324 ( _grid->_coords[1][ _j+1 ] + _grid->_tol < uvw[1] ) ||
5325 ( _grid->_coords[2][ _k ] - _grid->_tol > uvw[2] ) ||
5326 ( _grid->_coords[2][ _k+1 ] + _grid->_tol < uvw[2] ));
5328 //================================================================================
5330 * \brief Find existing triangulation of a polygon
5332 int findExistingTriangulation( const SMDS_MeshElement* polygon,
5333 //const SMDS_Mesh* mesh,
5334 std::vector< const SMDS_MeshNode* >& nodes )
5338 std::vector<const SMDS_MeshNode *> twoNodes(2);
5339 std::vector<const SMDS_MeshElement *> foundFaces; foundFaces.reserve(10);
5340 std::set< const SMDS_MeshElement * > avoidFaces; avoidFaces.insert( polygon );
5342 const int nbPolyNodes = polygon->NbCornerNodes();
5343 twoNodes[1] = polygon->GetNode( nbPolyNodes - 1 );
5344 for ( int iN = 0; iN < nbPolyNodes; ++iN ) // loop on border links of polygon
5346 twoNodes[0] = polygon->GetNode( iN );
5348 int nbFaces = SMDS_Mesh::GetElementsByNodes( twoNodes, foundFaces, SMDSAbs_Face );
5350 for ( int iF = 0; iF < nbFaces; ++iF ) // keep faces lying over polygon
5352 if ( avoidFaces.count( foundFaces[ iF ]))
5354 int i, nbFaceNodes = foundFaces[ iF ]->NbCornerNodes();
5355 for ( i = 0; i < nbFaceNodes; ++i )
5357 const SMDS_MeshNode* n = foundFaces[ iF ]->GetNode( i );
5358 bool isCommonNode = ( n == twoNodes[0] ||
5360 polygon->GetNodeIndex( n ) >= 0 );
5361 if ( !isCommonNode )
5364 if ( i == nbFaceNodes ) // all nodes of foundFaces[iF] are shared with polygon
5365 if ( nbOkFaces++ != iF )
5366 foundFaces[ nbOkFaces-1 ] = foundFaces[ iF ];
5368 if ( nbOkFaces > 0 )
5370 int iFaceSelected = 0;
5371 if ( nbOkFaces > 1 ) // select a face with minimal distance from polygon
5373 double minDist = Precision::Infinite();
5374 for ( int iF = 0; iF < nbOkFaces; ++iF )
5376 int i, nbFaceNodes = foundFaces[ iF ]->NbCornerNodes();
5377 gp_XYZ gc = SMESH_NodeXYZ( foundFaces[ iF ]->GetNode( 0 ));
5378 for ( i = 1; i < nbFaceNodes; ++i )
5379 gc += SMESH_NodeXYZ( foundFaces[ iF ]->GetNode( i ));
5382 double dist = SMESH_MeshAlgos::GetDistance( polygon, gc );
5383 if ( dist < minDist )
5390 if ( foundFaces[ iFaceSelected ]->NbCornerNodes() != 3 )
5392 nodes.insert( nodes.end(),
5393 foundFaces[ iFaceSelected ]->begin_nodes(),
5394 foundFaces[ iFaceSelected ]->end_nodes());
5395 if ( !SMESH_MeshAlgos::IsRightOrder( foundFaces[ iFaceSelected ],
5396 twoNodes[0], twoNodes[1] ))
5398 // reverse just added nodes
5399 std::reverse( nodes.end() - 3, nodes.end() );
5401 avoidFaces.insert( foundFaces[ iFaceSelected ]);
5405 twoNodes[1] = twoNodes[0];
5407 } // loop on polygon nodes
5411 //================================================================================
5413 * \brief Divide a polygon into triangles and modify accordingly an adjacent polyhedron
5415 void splitPolygon( const SMDS_MeshElement* polygon,
5416 SMDS_VolumeTool & volume,
5417 const int facetIndex,
5418 const TGeomID faceID,
5419 const TGeomID solidID,
5420 SMESH_MeshEditor::ElemFeatures& face,
5421 SMESH_MeshEditor& editor,
5422 const bool reinitVolume)
5424 SMESH_MeshAlgos::Triangulate divider(/*optimize=*/false);
5425 bool triangulationExist = false;
5426 int nbTrias = findExistingTriangulation( polygon, face.myNodes );
5428 triangulationExist = true;
5430 nbTrias = divider.GetTriangles( polygon, face.myNodes );
5431 face.myNodes.resize( nbTrias * 3 );
5433 SMESH_MeshEditor::ElemFeatures newVolumeDef;
5434 newVolumeDef.Init( volume.Element() );
5435 newVolumeDef.SetID( volume.Element()->GetID() );
5437 newVolumeDef.myPolyhedQuantities.reserve( volume.NbFaces() + nbTrias );
5438 newVolumeDef.myNodes.reserve( volume.NbNodes() + nbTrias * 3 );
5440 SMESHDS_Mesh* meshDS = editor.GetMeshDS();
5441 SMDS_MeshElement* newTriangle;
5442 for ( int iF = 0, nF = volume.NbFaces(); iF < nF; iF++ )
5444 if ( iF == facetIndex )
5446 newVolumeDef.myPolyhedQuantities.push_back( 3 );
5447 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(),
5448 face.myNodes.begin(),
5449 face.myNodes.begin() + 3 );
5450 meshDS->RemoveFreeElement( polygon, 0, false );
5451 if ( !triangulationExist )
5453 newTriangle = meshDS->AddFace( face.myNodes[0], face.myNodes[1], face.myNodes[2] );
5454 meshDS->SetMeshElementOnShape( newTriangle, faceID );
5459 const SMDS_MeshNode** nn = volume.GetFaceNodes( iF );
5460 const size_t nbFaceNodes = volume.NbFaceNodes ( iF );
5461 newVolumeDef.myPolyhedQuantities.push_back( nbFaceNodes );
5462 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(), nn, nn + nbFaceNodes );
5466 for ( size_t iN = 3; iN < face.myNodes.size(); iN += 3 )
5468 newVolumeDef.myPolyhedQuantities.push_back( 3 );
5469 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(),
5470 face.myNodes.begin() + iN,
5471 face.myNodes.begin() + iN + 3 );
5472 if ( !triangulationExist )
5474 newTriangle = meshDS->AddFace( face.myNodes[iN], face.myNodes[iN+1], face.myNodes[iN+2] );
5475 meshDS->SetMeshElementOnShape( newTriangle, faceID );
5479 meshDS->RemoveFreeElement( volume.Element(), 0, false );
5480 SMDS_MeshElement* newVolume = editor.AddElement( newVolumeDef.myNodes, newVolumeDef );
5481 meshDS->SetMeshElementOnShape( newVolume, solidID );
5486 volume.Set( newVolume );
5490 //================================================================================
5492 * \brief Look for a FACE supporting all given nodes made on EDGEs and VERTEXes
5494 TGeomID findCommonFace( const std::vector< const SMDS_MeshNode* > & nn,
5495 const SMESH_Mesh* mesh )
5498 TGeomID shapeIDs[20];
5499 for ( size_t iN = 0; iN < nn.size(); ++iN )
5500 shapeIDs[ iN ] = nn[ iN ]->GetShapeID();
5502 SMESH_subMesh* sm = mesh->GetSubMeshContaining( shapeIDs[ 0 ]);
5503 for ( const SMESH_subMesh * smFace : sm->GetAncestors() )
5505 if ( smFace->GetSubShape().ShapeType() != TopAbs_FACE )
5508 faceID = smFace->GetId();
5510 for ( size_t iN = 1; iN < nn.size() && faceID; ++iN )
5512 if ( !smFace->DependsOn( shapeIDs[ iN ]))
5520 //================================================================================
5522 * \brief Create mesh faces at free facets
5524 void Hexahedron::addFaces( SMESH_MesherHelper& helper,
5525 const vector< const SMDS_MeshElement* > & boundaryVolumes )
5527 if ( !_grid->_toCreateFaces )
5530 SMDS_VolumeTool vTool;
5531 vector<int> bndFacets;
5532 SMESH_MeshEditor editor( helper.GetMesh() );
5533 SMESH_MeshEditor::ElemFeatures face( SMDSAbs_Face );
5534 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
5536 // check if there are internal or shared FACEs
5537 bool hasInternal = ( !_grid->_geometry.IsOneSolid() ||
5538 _grid->_geometry._soleSolid.HasInternalFaces() );
5540 for ( size_t iV = 0; iV < boundaryVolumes.size(); ++iV )
5542 if ( !vTool.Set( boundaryVolumes[ iV ]))
5545 TGeomID solidID = vTool.Element()->GetShapeID();
5546 Solid * solid = _grid->GetOneOfSolids( solidID );
5548 // find boundary facets
5551 for ( int iF = 0, n = vTool.NbFaces(); iF < n; iF++ )
5553 const SMDS_MeshElement* otherVol;
5554 bool isBoundary = vTool.IsFreeFace( iF, &otherVol );
5557 bndFacets.push_back( iF );
5559 else if (( hasInternal ) ||
5560 ( !_grid->IsSolid( otherVol->GetShapeID() )))
5562 // check if all nodes are on internal/shared FACEs
5564 const SMDS_MeshNode** nn = vTool.GetFaceNodes( iF );
5565 const size_t nbFaceNodes = vTool.NbFaceNodes ( iF );
5566 for ( size_t iN = 0; iN < nbFaceNodes && isBoundary; ++iN )
5567 isBoundary = ( nn[ iN ]->GetShapeID() != solidID );
5569 bndFacets.push_back( -( iF+1 )); // !!! minus ==> to check the FACE
5572 if ( bndFacets.empty() )
5577 if ( !vTool.IsPoly() )
5578 vTool.SetExternalNormal();
5579 for ( size_t i = 0; i < bndFacets.size(); ++i ) // loop on boundary facets
5581 const bool isBoundary = ( bndFacets[i] >= 0 );
5582 const int iFacet = isBoundary ? bndFacets[i] : -bndFacets[i]-1;
5583 const SMDS_MeshNode** nn = vTool.GetFaceNodes( iFacet );
5584 const size_t nbFaceNodes = vTool.NbFaceNodes ( iFacet );
5585 face.myNodes.assign( nn, nn + nbFaceNodes );
5588 const SMDS_MeshElement* existFace = 0, *newFace = 0;
5590 if (( existFace = meshDS->FindElement( face.myNodes, SMDSAbs_Face )))
5592 if ( existFace->isMarked() )
5593 continue; // created by this method
5594 faceID = existFace->GetShapeID();
5598 // look for a supporting FACE
5599 for ( size_t iN = 0; iN < nbFaceNodes && !faceID; ++iN ) // look for a node on FACE
5601 if ( nn[ iN ]->GetPosition()->GetDim() == 2 )
5602 faceID = nn[ iN ]->GetShapeID();
5605 faceID = findCommonFace( face.myNodes, helper.GetMesh() );
5607 bool toCheckFace = faceID && (( !isBoundary ) ||
5608 ( hasInternal && _grid->_toUseThresholdForInternalFaces ));
5609 if ( toCheckFace ) // check if all nodes are on the found FACE
5611 SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMeshContaining( faceID );
5612 for ( size_t iN = 0; iN < nbFaceNodes && faceID; ++iN )
5614 TGeomID subID = nn[ iN ]->GetShapeID();
5615 if ( subID != faceID && !faceSM->DependsOn( subID ))
5618 // if ( !faceID && !isBoundary )
5621 if ( !faceID && !isBoundary )
5625 // orient a new face according to supporting FACE orientation in shape_to_mesh
5626 if ( !isBoundary && !solid->IsOutsideOriented( faceID ))
5629 editor.Reorient( existFace );
5631 std::reverse( face.myNodes.begin(), face.myNodes.end() );
5634 if ( ! ( newFace = existFace ))
5636 face.SetPoly( nbFaceNodes > 4 );
5637 newFace = editor.AddElement( face.myNodes, face );
5640 newFace->setIsMarked( true ); // to distinguish from face created in getBoundaryElems()
5643 if ( faceID && _grid->IsBoundaryFace( faceID )) // face is not shared
5645 // set newFace to the found FACE provided that it fully lies on the FACE
5646 for ( size_t iN = 0; iN < nbFaceNodes && faceID; ++iN )
5647 if ( nn[iN]->GetShapeID() == solidID )
5650 meshDS->UnSetMeshElementOnShape( existFace, _grid->Shape( faceID ));
5655 if ( faceID && nbFaceNodes > 4 &&
5656 !_grid->IsInternal( faceID ) &&
5657 !_grid->IsShared( faceID ) &&
5658 !_grid->IsBoundaryFace( faceID ))
5660 // split a polygon that will be used by other 3D algorithm
5662 splitPolygon( newFace, vTool, iFacet, faceID, solidID,
5663 face, editor, i+1 < bndFacets.size() );
5668 meshDS->SetMeshElementOnShape( newFace, faceID );
5670 meshDS->SetMeshElementOnShape( newFace, solidID );
5672 } // loop on bndFacets
5673 } // loop on boundaryVolumes
5676 // Orient coherently mesh faces on INTERNAL FACEs
5680 TopExp_Explorer faceExp( _grid->_geometry._mainShape, TopAbs_FACE );
5681 for ( ; faceExp.More(); faceExp.Next() )
5683 if ( faceExp.Current().Orientation() != TopAbs_INTERNAL )
5686 SMESHDS_SubMesh* sm = meshDS->MeshElements( faceExp.Current() );
5687 if ( !sm ) continue;
5689 TIDSortedElemSet facesToOrient;
5690 for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
5691 facesToOrient.insert( facesToOrient.end(), fIt->next() );
5692 if ( facesToOrient.size() < 2 )
5695 gp_Dir direction(1,0,0);
5696 TIDSortedElemSet refFaces;
5697 editor.Reorient2D( facesToOrient, direction, refFaces, /*allowNonManifold=*/true );
5703 //================================================================================
5705 * \brief Create mesh segments.
5707 void Hexahedron::addSegments( SMESH_MesherHelper& helper,
5708 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap )
5710 SMESHDS_Mesh* mesh = helper.GetMeshDS();
5712 std::vector<const SMDS_MeshNode*> nodes;
5713 std::vector<const SMDS_MeshElement *> elems;
5714 map< TGeomID, vector< TGeomID > >::const_iterator e2ff = edge2faceIDsMap.begin();
5715 for ( ; e2ff != edge2faceIDsMap.end(); ++e2ff )
5717 const TopoDS_Edge& edge = TopoDS::Edge( _grid->Shape( e2ff->first ));
5718 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( e2ff->second[0] ));
5719 StdMeshers_FaceSide side( face, edge, helper.GetMesh(), /*isFwd=*/true, /*skipMed=*/true );
5720 nodes = side.GetOrderedNodes();
5723 if ( nodes.size() == 2 )
5724 // check that there is an element connecting two nodes
5725 if ( !mesh->GetElementsByNodes( nodes, elems ))
5728 for ( size_t i = 1; i < nodes.size(); i++ )
5730 if ( mesh->FindEdge( nodes[i-1], nodes[i] ))
5732 SMDS_MeshElement* segment = mesh->AddEdge( nodes[i-1], nodes[i] );
5733 mesh->SetMeshElementOnShape( segment, e2ff->first );
5739 //================================================================================
5741 * \brief Return created volumes and volumes that can have free facet because of
5742 * skipped small volume. Also create mesh faces on free facets
5743 * of adjacent not-cut volumes if the result volume is too small.
5745 void Hexahedron::getBoundaryElems( vector< const SMDS_MeshElement* > & boundaryElems )
5747 if ( _hasTooSmall /*|| _volumeDefs.IsEmpty()*/ )
5749 // create faces around a missing small volume
5751 SMESH_MeshEditor editor( _grid->_helper->GetMesh() );
5752 SMESH_MeshEditor::ElemFeatures polygon( SMDSAbs_Face );
5753 SMESHDS_Mesh* meshDS = _grid->_helper->GetMeshDS();
5754 std::vector<const SMDS_MeshElement *> adjVolumes(2);
5755 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
5757 const size_t nbLinks = _polygons[ iF ]._links.size();
5758 if ( nbLinks != 4 ) continue;
5759 polygon.myNodes.resize( nbLinks );
5760 polygon.myNodes.back() = 0;
5761 for ( size_t iL = 0, iN = nbLinks - 1; iL < nbLinks; ++iL, --iN )
5762 if ( ! ( polygon.myNodes[iN] = _polygons[ iF ]._links[ iL ].FirstNode()->Node() ))
5764 if ( !polygon.myNodes.back() )
5767 meshDS->GetElementsByNodes( polygon.myNodes, adjVolumes, SMDSAbs_Volume );
5768 if ( adjVolumes.size() != 1 )
5770 if ( !adjVolumes[0]->isMarked() )
5772 boundaryElems.push_back( adjVolumes[0] );
5773 adjVolumes[0]->setIsMarked( true );
5776 bool sameShape = true;
5777 TGeomID shapeID = polygon.myNodes[0]->GetShapeID();
5778 for ( size_t i = 1; i < polygon.myNodes.size() && sameShape; ++i )
5779 sameShape = ( shapeID == polygon.myNodes[i]->GetShapeID() );
5781 if ( !sameShape || !_grid->IsSolid( shapeID ))
5782 continue; // some of shapes must be FACE
5786 faceID = getAnyFace();
5789 if ( _grid->IsInternal( faceID ) ||
5790 _grid->IsShared( faceID ) //||
5791 //_grid->IsBoundaryFace( faceID ) -- commented for #19887
5793 break; // create only if a new face will be used by other 3D algo
5796 Solid * solid = _grid->GetOneOfSolids( adjVolumes[0]->GetShapeID() );
5797 if ( !solid->IsOutsideOriented( faceID ))
5798 std::reverse( polygon.myNodes.begin(), polygon.myNodes.end() );
5800 //polygon.SetPoly( polygon.myNodes.size() > 4 );
5801 const SMDS_MeshElement* newFace = editor.AddElement( polygon.myNodes, polygon );
5802 meshDS->SetMeshElementOnShape( newFace, faceID );
5806 // return created volumes
5807 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
5809 if ( volDef ->_volume &&
5810 !volDef->_volume->IsNull() &&
5811 !volDef->_volume->isMarked() )
5813 volDef->_volume->setIsMarked( true );
5814 boundaryElems.push_back( volDef->_volume );
5816 if ( _grid->IsToCheckNodePos() ) // un-mark nodes marked in addVolumes()
5817 for ( size_t iN = 0; iN < volDef->_nodes.size(); ++iN )
5818 volDef->_nodes[iN].Node()->setIsMarked( false );
5823 //================================================================================
5825 * \brief Remove edges and nodes dividing a hexa side in the case if an adjacent
5826 * volume also sharing the dividing edge is missing due to its small side.
5829 //================================================================================
5831 void Hexahedron::removeExcessSideDivision(const vector< Hexahedron* >& allHexa)
5833 if ( ! _volumeDefs.IsPolyhedron() )
5834 return; // not a polyhedron
5836 // look for a divided side adjacent to a small hexahedron
5838 int di[6] = { 0, 0, 0, 0,-1, 1 };
5839 int dj[6] = { 0, 0,-1, 1, 0, 0 };
5840 int dk[6] = {-1, 1, 0, 0, 0, 0 };
5842 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
5844 size_t neighborIndex = _grid->CellIndex( _i + di[iF],
5847 if ( neighborIndex >= allHexa.size() ||
5848 !allHexa[ neighborIndex ] ||
5849 !allHexa[ neighborIndex ]->_hasTooSmall )
5852 // check if a side is divided into several polygons
5853 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
5855 int nbPolygons = 0, nbNodes = 0;
5856 for ( size_t i = 0; i < volDef->_names.size(); ++i )
5857 if ( volDef->_names[ i ] == _hexQuads[ iF ]._name )
5860 nbNodes += volDef->_quantities[ i ];
5862 if ( nbPolygons < 2 )
5865 // construct loops from polygons
5866 typedef _volumeDef::_linkDef TLinkDef;
5867 std::vector< TLinkDef* > loops;
5868 std::vector< TLinkDef > links( nbNodes );
5869 for ( size_t i = 0, iN = 0, iLoop = 0; iLoop < volDef->_quantities.size(); ++iLoop )
5871 size_t nbLinks = volDef->_quantities[ iLoop ];
5872 if ( volDef->_names[ iLoop ] != _hexQuads[ iF ]._name )
5877 loops.push_back( & links[i] );
5878 for ( size_t n = 0; n < nbLinks-1; ++n, ++i, ++iN )
5880 links[i].init( volDef->_nodes[iN], volDef->_nodes[iN+1], iLoop );
5881 links[i].setNext( &links[i+1] );
5883 links[i].init( volDef->_nodes[iN], volDef->_nodes[iN-nbLinks+1], iLoop );
5884 links[i].setNext( &links[i-nbLinks+1] );
5888 // look for equal links in different loops and join such loops
5889 bool loopsJoined = false;
5890 std::set< TLinkDef > linkSet;
5891 for ( size_t iLoop = 0; iLoop < loops.size(); ++iLoop )
5894 for ( TLinkDef* l = loops[ iLoop ]; l != beg; l = l->_next ) // walk around the iLoop
5896 std::pair< std::set< TLinkDef >::iterator, bool > it2new = linkSet.insert( *l );
5897 if ( !it2new.second ) // equal found, join loops
5899 const TLinkDef* equal = &(*it2new.first);
5900 if ( equal->_loopIndex == l->_loopIndex )
5905 for ( size_t i = iLoop - 1; i < loops.size(); --i )
5906 if ( loops[ i ] && loops[ i ]->_loopIndex == equal->_loopIndex )
5909 // exclude l and equal and join two loops
5910 if ( l->_prev != equal )
5911 l->_prev->setNext( equal->_next );
5912 if ( equal->_prev != l )
5913 equal->_prev->setNext( l->_next );
5915 if ( volDef->_quantities[ l->_loopIndex ] > 0 )
5916 volDef->_quantities[ l->_loopIndex ] *= -1;
5917 if ( volDef->_quantities[ equal->_loopIndex ] > 0 )
5918 volDef->_quantities[ equal->_loopIndex ] *= -1;
5920 if ( loops[ iLoop ] == l )
5921 loops[ iLoop ] = l->_prev->_next;
5923 beg = loops[ iLoop ];
5929 // set unchanged polygons
5930 std::vector< int > newQuantities;
5931 std::vector< _volumeDef::_nodeDef > newNodes;
5932 vector< SMESH_Block::TShapeID > newNames;
5933 newQuantities.reserve( volDef->_quantities.size() );
5934 newNodes.reserve ( volDef->_nodes.size() );
5935 newNames.reserve ( volDef->_names.size() );
5936 for ( size_t i = 0, iLoop = 0; iLoop < volDef->_quantities.size(); ++iLoop )
5938 if ( volDef->_quantities[ iLoop ] < 0 )
5940 i -= volDef->_quantities[ iLoop ];
5943 newQuantities.push_back( volDef->_quantities[ iLoop ]);
5944 newNodes.insert( newNodes.end(),
5945 volDef->_nodes.begin() + i,
5946 volDef->_nodes.begin() + i + newQuantities.back() );
5947 newNames.push_back( volDef->_names[ iLoop ]);
5948 i += volDef->_quantities[ iLoop ];
5952 for ( size_t iLoop = 0; iLoop < loops.size(); ++iLoop )
5954 if ( !loops[ iLoop ] )
5956 newQuantities.push_back( 0 );
5958 for ( TLinkDef* l = loops[ iLoop ]; l != beg; l = l->_next, ++newQuantities.back() )
5960 newNodes.push_back( l->_node1 );
5961 beg = loops[ iLoop ];
5963 newNames.push_back( _hexQuads[ iF ]._name );
5965 volDef->_quantities.swap( newQuantities );
5966 volDef->_nodes.swap( newNodes );
5967 volDef->_names.swap( newNames );
5969 } // loop on volDef's
5970 } // loop on hex sides
5973 } // removeExcessSideDivision()
5976 //================================================================================
5978 * \brief Remove nodes splitting Cartesian cell edges in the case if a node
5979 * is used in every cells only by two polygons sharing the edge
5982 //================================================================================
5984 void Hexahedron::removeExcessNodes(vector< Hexahedron* >& allHexa)
5986 if ( ! _volumeDefs.IsPolyhedron() )
5987 return; // not a polyhedron
5989 typedef vector< _volumeDef::_nodeDef >::iterator TNodeIt;
5990 vector< int > nodesInPoly[ 4 ]; // node index in _volumeDefs._nodes
5991 vector< int > volDefInd [ 4 ]; // index of a _volumeDefs
5992 Hexahedron* hexa [ 4 ];
5993 int i,j,k, cellIndex, iLink = 0, iCellLink;
5994 for ( int iDir = 0; iDir < 3; ++iDir )
5996 CellsAroundLink fourCells( _grid, iDir );
5997 for ( int iL = 0; iL < 4; ++iL, ++iLink ) // 4 links in a direction
5999 _Link& link = _hexLinks[ iLink ];
6000 fourCells.Init( _i, _j, _k, iLink );
6002 for ( size_t iP = 0; iP < link._fIntPoints.size(); ++iP ) // loop on nodes on the link
6004 bool nodeRemoved = true;
6005 _volumeDef::_nodeDef node; node._intPoint = link._fIntPoints[iP];
6007 for ( size_t i = 0, nb = _volumeDefs.size(); i < nb && nodeRemoved; ++i )
6008 if ( _volumeDef* vol = _volumeDefs.at( i ))
6010 ( std::find( vol->_nodes.begin(), vol->_nodes.end(), node ) == vol->_nodes.end() );
6012 continue; // node already removed
6014 // check if a node encounters zero or two times in 4 cells sharing iLink
6015 // if so, the node can be removed from the cells
6016 bool nodeIsOnEdge = true;
6017 int nbPolyhedraWithNode = 0;
6018 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing a link
6020 nodesInPoly[ iC ].clear();
6021 volDefInd [ iC ].clear();
6023 if ( !fourCells.GetCell( iC, i,j,k, cellIndex, iCellLink ))
6025 hexa[ iC ] = allHexa[ cellIndex ];
6028 for ( size_t i = 0, nb = hexa[ iC ]->_volumeDefs.size(); i < nb; ++i )
6029 if ( _volumeDef* vol = hexa[ iC ]->_volumeDefs.at( i ))
6031 for ( TNodeIt nIt = vol->_nodes.begin(); nIt != vol->_nodes.end(); ++nIt )
6033 nIt = std::find( nIt, vol->_nodes.end(), node );
6034 if ( nIt != vol->_nodes.end() )
6036 nodesInPoly[ iC ].push_back( std::distance( vol->_nodes.begin(), nIt ));
6037 volDefInd [ iC ].push_back( i );
6042 nbPolyhedraWithNode += ( !nodesInPoly[ iC ].empty() );
6044 if ( nodesInPoly[ iC ].size() != 0 &&
6045 nodesInPoly[ iC ].size() != 2 )
6047 nodeIsOnEdge = false;
6050 } // loop on 4 cells
6052 // remove nodes from polyhedra
6053 if ( nbPolyhedraWithNode > 0 && nodeIsOnEdge )
6055 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing the link
6057 if ( nodesInPoly[ iC ].empty() )
6059 for ( int i = volDefInd[ iC ].size() - 1; i >= 0; --i )
6061 _volumeDef* vol = hexa[ iC ]->_volumeDefs.at( volDefInd[ iC ][ i ]);
6062 int nIndex = nodesInPoly[ iC ][ i ];
6063 // decrement _quantities
6064 for ( size_t iQ = 0; iQ < vol->_quantities.size(); ++iQ )
6065 if ( nIndex < vol->_quantities[ iQ ])
6067 vol->_quantities[ iQ ]--;
6072 nIndex -= vol->_quantities[ iQ ];
6074 vol->_nodes.erase( vol->_nodes.begin() + nodesInPoly[ iC ][ i ]);
6077 vol->_nodes.size() == 6 * 4 &&
6078 vol->_quantities.size() == 6 ) // polyhedron becomes hexahedron?
6080 bool allQuads = true;
6081 for ( size_t iQ = 0; iQ < vol->_quantities.size() && allQuads; ++iQ )
6082 allQuads = ( vol->_quantities[ iQ ] == 4 );
6085 // set side nodes as this: bottom, top, top, ...
6086 int iTop = 0, iBot = 0; // side indices
6087 for ( int iS = 0; iS < 6; ++iS )
6089 if ( vol->_names[ iS ] == SMESH_Block::ID_Fxy0 )
6091 if ( vol->_names[ iS ] == SMESH_Block::ID_Fxy1 )
6098 std::copy( vol->_nodes.begin(),
6099 vol->_nodes.begin() + 4,
6100 vol->_nodes.begin() + 4 );
6103 std::copy( vol->_nodes.begin() + 4 * iBot,
6104 vol->_nodes.begin() + 4 * ( iBot + 1),
6105 vol->_nodes.begin() );
6108 std::copy( vol->_nodes.begin() + 4 * iTop,
6109 vol->_nodes.begin() + 4 * ( iTop + 1),
6110 vol->_nodes.begin() + 4 );
6112 std::copy( vol->_nodes.begin() + 4,
6113 vol->_nodes.begin() + 8,
6114 vol->_nodes.begin() + 8 );
6115 // set up top facet nodes by comparing their uvw with bottom nodes
6116 E_IntersectPoint ip[8];
6117 for ( int iN = 0; iN < 8; ++iN )
6119 SMESH_NodeXYZ p = vol->_nodes[ iN ].Node();
6120 _grid->ComputeUVW( p, ip[ iN ]._uvw );
6122 const double tol2 = _grid->_tol * _grid->_tol;
6123 for ( int iN = 0; iN < 4; ++iN )
6125 gp_Pnt2d pBot( ip[ iN ]._uvw[0], ip[ iN ]._uvw[1] );
6126 for ( int iT = 4; iT < 8; ++iT )
6128 gp_Pnt2d pTop( ip[ iT ]._uvw[0], ip[ iT ]._uvw[1] );
6129 if ( pBot.SquareDistance( pTop ) < tol2 )
6131 // vol->_nodes[ iN + 4 ]._node = ip[ iT ]._node;
6132 // vol->_nodes[ iN + 4 ]._intPoint = 0;
6133 vol->_nodes[ iN + 4 ] = vol->_nodes[ iT + 4 ];
6138 vol->_nodes.resize( 8 );
6139 vol->_quantities.clear();
6140 //vol->_names.clear();
6143 } // loop on _volumeDefs
6144 } // loop on 4 cell abound a link
6145 } // if ( nodeIsOnEdge )
6146 } // loop on intersection points of a link
6147 } // loop on 4 links of a direction
6148 } // loop on 3 directions
6152 } // removeExcessNodes()
6154 //================================================================================
6156 * \brief [Issue #19913] Modify _hexLinks._splits to prevent creating overlapping volumes
6158 //================================================================================
6160 void Hexahedron::preventVolumesOverlapping()
6162 // Cut off a quadrangle corner if two links sharing the corner
6163 // are shared by same two solids, in this case each of solids gets
6164 // a triangle for it-self.
6165 std::vector< TGeomID > soIDs[4];
6166 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
6168 _Face& quad = _hexQuads[ iF ] ;
6170 int iFOpposite = iF + ( iF % 2 ? -1 : 1 );
6171 _Face& quadOpp = _hexQuads[ iFOpposite ] ;
6173 int nbSides = 0, nbSidesOpp = 0;
6174 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
6176 nbSides += ( quad._links [ iE ].NbResultLinks() > 0 );
6177 nbSidesOpp += ( quadOpp._links[ iE ].NbResultLinks() > 0 );
6179 if ( nbSides < 4 || nbSidesOpp != 2 )
6182 for ( int iE = 0; iE < 4; ++iE )
6184 soIDs[ iE ].clear();
6185 _Node* n = quad._links[ iE ].FirstNode();
6186 if ( n->_intPoint && n->_intPoint->_faceIDs.size() )
6187 soIDs[ iE ] = _grid->GetSolidIDs( n->_intPoint->_faceIDs[0] );
6189 if ((( soIDs[0].size() >= 2 ) +
6190 ( soIDs[1].size() >= 2 ) +
6191 ( soIDs[2].size() >= 2 ) +
6192 ( soIDs[3].size() >= 2 ) ) < 3 )
6196 for ( int i = 0; i < 4; ++i )
6198 int i1 = _grid->_helper->WrapIndex( i + 1, 4 );
6199 int i2 = _grid->_helper->WrapIndex( i + 2, 4 );
6200 int i3 = _grid->_helper->WrapIndex( i + 3, 4 );
6201 if ( soIDs[i1].size() == 2 && soIDs[i ] != soIDs[i1] &&
6202 soIDs[i2].size() == 2 && soIDs[i1] == soIDs[i2] &&
6203 soIDs[i3].size() == 2 && soIDs[i2] == soIDs[i3] )
6205 quad._links[ i1 ]._link->_splits.clear();
6206 quad._links[ i2 ]._link->_splits.clear();
6215 } // preventVolumesOverlapping()
6217 //================================================================================
6219 * \brief Set to _hexLinks a next portion of splits located on one side of INTERNAL FACEs
6221 bool Hexahedron::_SplitIterator::Next()
6223 if ( _iterationNb > 0 )
6224 // count used splits
6225 for ( size_t i = 0; i < _splits.size(); ++i )
6227 if ( _splits[i]._iCheckIteration == _iterationNb )
6229 _splits[i]._isUsed = _splits[i]._checkedSplit->_faces[1];
6230 _nbUsed += _splits[i]._isUsed;
6238 bool toTestUsed = ( _nbChecked >= _splits.size() );
6241 // all splits are checked; find all not used splits
6242 for ( size_t i = 0; i < _splits.size(); ++i )
6243 if ( !_splits[i].IsCheckedOrUsed( toTestUsed ))
6244 _splits[i]._iCheckIteration = _iterationNb;
6246 _nbUsed = _splits.size(); // to stop iteration
6250 // get any not used/checked split to start from
6252 for ( size_t i = 0; i < _splits.size(); ++i )
6254 if ( !_splits[i].IsCheckedOrUsed( toTestUsed ))
6256 _freeNodes.push_back( _splits[i]._nodes[0] );
6257 _freeNodes.push_back( _splits[i]._nodes[1] );
6258 _splits[i]._iCheckIteration = _iterationNb;
6262 // find splits connected to the start one via _freeNodes
6263 for ( size_t iN = 0; iN < _freeNodes.size(); ++iN )
6265 for ( size_t iS = 0; iS < _splits.size(); ++iS )
6267 if ( _splits[iS].IsCheckedOrUsed( toTestUsed ))
6270 if ( _freeNodes[iN] == _splits[iS]._nodes[0] )
6272 else if ( _freeNodes[iN] == _splits[iS]._nodes[1] )
6276 if ( _freeNodes[iN]->_isInternalFlags > 0 )
6278 if ( _splits[iS]._nodes[ iN2 ]->_isInternalFlags == 0 )
6280 if ( !_splits[iS]._nodes[ iN2 ]->IsLinked( _freeNodes[iN]->_intPoint ))
6283 _splits[iS]._iCheckIteration = _iterationNb;
6284 _freeNodes.push_back( _splits[iS]._nodes[ iN2 ]);
6288 // set splits to hex links
6290 for ( int iL = 0; iL < 12; ++iL )
6291 _hexLinks[ iL ]._splits.clear();
6294 for ( size_t i = 0; i < _splits.size(); ++i )
6296 if ( _splits[i]._iCheckIteration == _iterationNb )
6298 split._nodes[0] = _splits[i]._nodes[0];
6299 split._nodes[1] = _splits[i]._nodes[1];
6300 _Link & hexLink = _hexLinks[ _splits[i]._linkID ];
6301 hexLink._splits.push_back( split );
6302 _splits[i]._checkedSplit = & hexLink._splits.back();
6309 //================================================================================
6311 * \brief computes exact bounding box with axes parallel to given ones
6313 //================================================================================
6315 void getExactBndBox( const vector< TopoDS_Shape >& faceVec,
6316 const double* axesDirs,
6320 TopoDS_Compound allFacesComp;
6321 b.MakeCompound( allFacesComp );
6322 for ( size_t iF = 0; iF < faceVec.size(); ++iF )
6323 b.Add( allFacesComp, faceVec[ iF ] );
6325 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
6326 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
6328 for ( int i = 0; i < 6; ++i )
6329 farDist = Max( farDist, 10 * sP[i] );
6331 gp_XYZ axis[3] = { gp_XYZ( axesDirs[0], axesDirs[1], axesDirs[2] ),
6332 gp_XYZ( axesDirs[3], axesDirs[4], axesDirs[5] ),
6333 gp_XYZ( axesDirs[6], axesDirs[7], axesDirs[8] ) };
6334 axis[0].Normalize();
6335 axis[1].Normalize();
6336 axis[2].Normalize();
6338 gp_Mat basis( axis[0], axis[1], axis[2] );
6339 gp_Mat bi = basis.Inverted();
6342 for ( int iDir = 0; iDir < 3; ++iDir )
6344 gp_XYZ axis0 = axis[ iDir ];
6345 gp_XYZ axis1 = axis[ ( iDir + 1 ) % 3 ];
6346 gp_XYZ axis2 = axis[ ( iDir + 2 ) % 3 ];
6347 for ( int isMax = 0; isMax < 2; ++isMax )
6349 double shift = isMax ? farDist : -farDist;
6350 gp_XYZ orig = shift * axis0;
6351 gp_XYZ norm = axis1 ^ axis2;
6352 gp_Pln pln( orig, norm );
6353 norm = pln.Axis().Direction().XYZ();
6354 BRepBuilderAPI_MakeFace plane( pln, -farDist, farDist, -farDist, farDist );
6356 gp_Pnt& pAxis = isMax ? pMax : pMin;
6357 gp_Pnt pPlane, pFaces;
6358 double dist = GEOMUtils::GetMinDistance( plane, allFacesComp, pPlane, pFaces );
6363 for ( int i = 0; i < 2; ++i ) {
6364 corner.SetCoord( 1, sP[ i*3 ]);
6365 for ( int j = 0; j < 2; ++j ) {
6366 corner.SetCoord( 2, sP[ i*3 + 1 ]);
6367 for ( int k = 0; k < 2; ++k )
6369 corner.SetCoord( 3, sP[ i*3 + 2 ]);
6375 corner = isMax ? bb.CornerMax() : bb.CornerMin();
6376 pAxis.SetCoord( iDir+1, corner.Coord( iDir+1 ));
6380 gp_XYZ pf = pFaces.XYZ() * bi;
6381 pAxis.SetCoord( iDir+1, pf.Coord( iDir+1 ) );
6387 shapeBox.Add( pMin );
6388 shapeBox.Add( pMax );
6395 //=============================================================================
6397 * \brief Generates 3D structured Cartesian mesh in the internal part of
6398 * solid shapes and polyhedral volumes near the shape boundary.
6399 * \param theMesh - mesh to fill in
6400 * \param theShape - a compound of all SOLIDs to mesh
6401 * \retval bool - true in case of success
6403 //=============================================================================
6405 bool StdMeshers_Cartesian_3D::Compute(SMESH_Mesh & theMesh,
6406 const TopoDS_Shape & theShape)
6408 if ( _hypViscousLayers )
6410 const StdMeshers_ViscousLayers* hypViscousLayers = _hypViscousLayers;
6411 _hypViscousLayers = nullptr;
6413 StdMeshers_Cartesian_VL::ViscousBuilder builder( hypViscousLayers, theMesh, theShape );
6416 TopoDS_Shape offsetShape = builder.MakeOffsetShape( theShape, theMesh, error );
6417 if ( offsetShape.IsNull() )
6418 throw SALOME_Exception( error );
6420 SMESH_Mesh* offsetMesh = new TmpMesh();
6421 offsetMesh->ShapeToMesh( offsetShape );
6422 offsetMesh->GetSubMesh( offsetShape )->DependsOn();
6424 this->_isComputeOffset = true;
6425 if ( ! this->Compute( *offsetMesh, offsetShape ))
6428 return builder.MakeViscousLayers( *offsetMesh, theMesh, theShape );
6431 // The algorithm generates the mesh in following steps:
6433 // 1) Intersection of grid lines with the geometry boundary.
6434 // This step allows to find out if a given node of the initial grid is
6435 // inside or outside the geometry.
6437 // 2) For each cell of the grid, check how many of it's nodes are outside
6438 // of the geometry boundary. Depending on a result of this check
6439 // - skip a cell, if all it's nodes are outside
6440 // - skip a cell, if it is too small according to the size threshold
6441 // - add a hexahedron in the mesh, if all nodes are inside
6442 // - add a polyhedron in the mesh, if some nodes are inside and some outside
6444 _computeCanceled = false;
6446 SMESH_MesherHelper helper( theMesh );
6447 SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
6452 grid._helper = &helper;
6453 grid._toAddEdges = _hyp->GetToAddEdges();
6454 grid._toCreateFaces = _hyp->GetToCreateFaces();
6455 grid._toConsiderInternalFaces = _hyp->GetToConsiderInternalFaces();
6456 grid._toUseThresholdForInternalFaces = _hyp->GetToUseThresholdForInternalFaces();
6457 grid._sizeThreshold = _hyp->GetSizeThreshold();
6458 if ( _isComputeOffset )
6460 grid._toAddEdges = true;
6461 grid._toCreateFaces = true;
6463 grid.InitGeometry( theShape );
6465 vector< TopoDS_Shape > faceVec;
6467 TopTools_MapOfShape faceMap;
6468 TopExp_Explorer fExp;
6469 for ( fExp.Init( theShape, TopAbs_FACE ); fExp.More(); fExp.Next() )
6471 bool isNewFace = faceMap.Add( fExp.Current() );
6472 if ( !grid._toConsiderInternalFaces )
6473 if ( !isNewFace || fExp.Current().Orientation() == TopAbs_INTERNAL )
6474 // remove an internal face
6475 faceMap.Remove( fExp.Current() );
6477 faceVec.reserve( faceMap.Extent() );
6478 faceVec.assign( faceMap.cbegin(), faceMap.cend() );
6480 vector<FaceGridIntersector> facesItersectors( faceVec.size() );
6482 for ( size_t i = 0; i < faceVec.size(); ++i )
6484 facesItersectors[i]._face = TopoDS::Face( faceVec[i] );
6485 facesItersectors[i]._faceID = grid.ShapeID( faceVec[i] );
6486 facesItersectors[i]._grid = &grid;
6487 shapeBox.Add( facesItersectors[i].GetFaceBndBox() );
6489 getExactBndBox( faceVec, _hyp->GetAxisDirs(), shapeBox );
6492 vector<double> xCoords, yCoords, zCoords;
6493 _hyp->GetCoordinates( xCoords, yCoords, zCoords, shapeBox );
6495 grid.SetCoordinates( xCoords, yCoords, zCoords, _hyp->GetAxisDirs(), shapeBox );
6497 if ( _computeCanceled ) return false;
6500 { // copy partner faces and curves of not thread-safe types
6501 set< const Standard_Transient* > tshapes;
6502 BRepBuilderAPI_Copy copier;
6503 for ( size_t i = 0; i < facesItersectors.size(); ++i )
6505 if ( !facesItersectors[i].IsThreadSafe( tshapes ))
6507 copier.Perform( facesItersectors[i]._face );
6508 facesItersectors[i]._face = TopoDS::Face( copier );
6512 // Intersection of grid lines with the geometry boundary.
6513 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, facesItersectors.size() ),
6514 ParallelIntersector( facesItersectors ),
6515 tbb::simple_partitioner());
6517 for ( size_t i = 0; i < facesItersectors.size(); ++i )
6518 facesItersectors[i].Intersect();
6521 // put intersection points onto the GridLine's; this is done after intersection
6522 // to avoid contention of facesItersectors for writing into the same GridLine
6523 // in case of parallel work of facesItersectors
6524 for ( size_t i = 0; i < facesItersectors.size(); ++i )
6525 facesItersectors[i].StoreIntersections();
6527 if ( _computeCanceled ) return false;
6529 // create nodes on the geometry
6530 grid.ComputeNodes( helper );
6532 if ( _computeCanceled ) return false;
6534 // get EDGEs to take into account
6535 map< TGeomID, vector< TGeomID > > edge2faceIDsMap;
6536 grid.GetEdgesToImplement( edge2faceIDsMap, theShape, faceVec );
6538 // create volume elements
6539 Hexahedron hex( &grid );
6540 int nbAdded = hex.MakeElements( helper, edge2faceIDsMap );
6544 if ( !grid._toConsiderInternalFaces )
6546 // make all SOLIDs computed
6547 TopExp_Explorer solidExp( theShape, TopAbs_SOLID );
6548 if ( SMESHDS_SubMesh* sm1 = meshDS->MeshElements( solidExp.Current()) )
6550 SMDS_ElemIteratorPtr volIt = sm1->GetElements();
6551 for ( ; solidExp.More() && volIt->more(); solidExp.Next() )
6553 const SMDS_MeshElement* vol = volIt->next();
6554 sm1->RemoveElement( vol );
6555 meshDS->SetMeshElementOnShape( vol, solidExp.Current() );
6559 // make other sub-shapes computed
6560 setSubmeshesComputed( theMesh, theShape );
6563 // remove free nodes
6564 //if ( SMESHDS_SubMesh * smDS = meshDS->MeshElements( helper.GetSubShapeID() ))
6566 std::vector< const SMDS_MeshNode* > nodesToRemove;
6567 // get intersection nodes
6568 for ( int iDir = 0; iDir < 3; ++iDir )
6570 vector< GridLine >& lines = grid._lines[ iDir ];
6571 for ( size_t i = 0; i < lines.size(); ++i )
6573 multiset< F_IntersectPoint >::iterator ip = lines[i]._intPoints.begin();
6574 for ( ; ip != lines[i]._intPoints.end(); ++ip )
6576 !ip->_node->IsNull() &&
6577 ip->_node->NbInverseElements() == 0 &&
6578 !ip->_node->isMarked() )
6580 nodesToRemove.push_back( ip->_node );
6581 ip->_node->setIsMarked( true );
6586 for ( size_t i = 0; i < grid._nodes.size(); ++i )
6587 if ( grid._nodes[i] &&
6588 !grid._nodes[i]->IsNull() &&
6589 grid._nodes[i]->NbInverseElements() == 0 &&
6590 !grid._nodes[i]->isMarked() )
6592 nodesToRemove.push_back( grid._nodes[i] );
6593 grid._nodes[i]->setIsMarked( true );
6597 for ( size_t i = 0; i < nodesToRemove.size(); ++i )
6598 meshDS->RemoveFreeNode( nodesToRemove[i], /*smD=*/0, /*fromGroups=*/false );
6604 // SMESH_ComputeError is not caught at SMESH_submesh level for an unknown reason
6605 catch ( SMESH_ComputeError& e)
6607 return error( SMESH_ComputeErrorPtr( new SMESH_ComputeError( e )));
6612 //=============================================================================
6616 //=============================================================================
6618 bool StdMeshers_Cartesian_3D::Evaluate(SMESH_Mesh & /*theMesh*/,
6619 const TopoDS_Shape & /*theShape*/,
6620 MapShapeNbElems& /*theResMap*/)
6623 // std::vector<int> aResVec(SMDSEntity_Last);
6624 // for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
6625 // if(IsQuadratic) {
6626 // aResVec[SMDSEntity_Quad_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
6627 // int nb1d_face0_int = ( nb2d_face0*4 - nb1d ) / 2;
6628 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
6631 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
6632 // aResVec[SMDSEntity_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
6634 // SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
6635 // aResMap.insert(std::make_pair(sm,aResVec));
6640 //=============================================================================
6644 * \brief Event listener setting/unsetting _alwaysComputed flag to
6645 * submeshes of inferior levels to prevent their computing
6647 struct _EventListener : public SMESH_subMeshEventListener
6651 _EventListener(const string& algoName):
6652 SMESH_subMeshEventListener(/*isDeletable=*/true,"StdMeshers_Cartesian_3D::_EventListener"),
6655 // --------------------------------------------------------------------------------
6656 // setting/unsetting _alwaysComputed flag to submeshes of inferior levels
6658 static void setAlwaysComputed( const bool isComputed,
6659 SMESH_subMesh* subMeshOfSolid)
6661 SMESH_subMeshIteratorPtr smIt =
6662 subMeshOfSolid->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
6663 while ( smIt->more() )
6665 SMESH_subMesh* sm = smIt->next();
6666 sm->SetIsAlwaysComputed( isComputed );
6668 subMeshOfSolid->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
6671 // --------------------------------------------------------------------------------
6672 // unsetting _alwaysComputed flag if "Cartesian_3D" was removed
6674 virtual void ProcessEvent(const int /*event*/,
6675 const int eventType,
6676 SMESH_subMesh* subMeshOfSolid,
6677 SMESH_subMeshEventListenerData* /*data*/,
6678 const SMESH_Hypothesis* /*hyp*/ = 0)
6680 if ( eventType == SMESH_subMesh::COMPUTE_EVENT )
6682 setAlwaysComputed( subMeshOfSolid->GetComputeState() == SMESH_subMesh::COMPUTE_OK,
6687 SMESH_Algo* algo3D = subMeshOfSolid->GetAlgo();
6688 if ( !algo3D || _algoName != algo3D->GetName() )
6689 setAlwaysComputed( false, subMeshOfSolid );
6693 // --------------------------------------------------------------------------------
6694 // set the event listener
6696 static void SetOn( SMESH_subMesh* subMeshOfSolid, const string& algoName )
6698 subMeshOfSolid->SetEventListener( new _EventListener( algoName ),
6703 }; // struct _EventListener
6707 //================================================================================
6709 * \brief Sets event listener to submeshes if necessary
6710 * \param subMesh - submesh where algo is set
6711 * This method is called when a submesh gets HYP_OK algo_state.
6712 * After being set, event listener is notified on each event of a submesh.
6714 //================================================================================
6716 void StdMeshers_Cartesian_3D::SetEventListener(SMESH_subMesh* subMesh)
6718 _EventListener::SetOn( subMesh, GetName() );
6721 //================================================================================
6723 * \brief Set _alwaysComputed flag to submeshes of inferior levels to avoid their computing
6725 //================================================================================
6727 void StdMeshers_Cartesian_3D::setSubmeshesComputed(SMESH_Mesh& theMesh,
6728 const TopoDS_Shape& theShape)
6730 for ( TopExp_Explorer soExp( theShape, TopAbs_SOLID ); soExp.More(); soExp.Next() )
6731 _EventListener::setAlwaysComputed( true, theMesh.GetSubMesh( soExp.Current() ));