1 // Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : StdMeshers_Cartesian_3D.cxx
25 #include "StdMeshers_Cartesian_3D.hxx"
26 #include "StdMeshers_CartesianParameters3D.hxx"
28 #include "ObjectPool.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_VolumeTool.hxx"
31 #include "SMESHDS_Mesh.hxx"
32 #include "SMESH_Block.hxx"
33 #include "SMESH_Comment.hxx"
34 #include "SMESH_ControlsDef.hxx"
35 #include "SMESH_Mesh.hxx"
36 #include "SMESH_MeshAlgos.hxx"
37 #include "SMESH_MeshEditor.hxx"
38 #include "SMESH_MesherHelper.hxx"
39 #include "SMESH_subMesh.hxx"
40 #include "SMESH_subMeshEventListener.hxx"
41 #include "StdMeshers_FaceSide.hxx"
43 #include <utilities.h>
44 #include <Utils_ExceptHandlers.hxx>
46 #include <GEOMUtils.hxx>
48 #include <BRepAdaptor_Curve.hxx>
49 #include <BRepAdaptor_Surface.hxx>
50 #include <BRepBndLib.hxx>
51 #include <BRepBuilderAPI_Copy.hxx>
52 #include <BRepBuilderAPI_MakeFace.hxx>
53 #include <BRepTools.hxx>
54 #include <BRepTopAdaptor_FClass2d.hxx>
55 #include <BRep_Builder.hxx>
56 #include <BRep_Tool.hxx>
57 #include <Bnd_B3d.hxx>
58 #include <Bnd_Box.hxx>
60 #include <GCPnts_UniformDeflection.hxx>
61 #include <Geom2d_BSplineCurve.hxx>
62 #include <Geom2d_BezierCurve.hxx>
63 #include <Geom2d_TrimmedCurve.hxx>
64 #include <GeomAPI_ProjectPointOnSurf.hxx>
65 #include <GeomLib.hxx>
66 #include <Geom_BSplineCurve.hxx>
67 #include <Geom_BSplineSurface.hxx>
68 #include <Geom_BezierCurve.hxx>
69 #include <Geom_BezierSurface.hxx>
70 #include <Geom_RectangularTrimmedSurface.hxx>
71 #include <Geom_TrimmedCurve.hxx>
72 #include <IntAna_IntConicQuad.hxx>
73 #include <IntAna_IntLinTorus.hxx>
74 #include <IntAna_Quadric.hxx>
75 #include <IntCurveSurface_TransitionOnCurve.hxx>
76 #include <IntCurvesFace_Intersector.hxx>
77 #include <Poly_Triangulation.hxx>
78 #include <Precision.hxx>
80 #include <TopExp_Explorer.hxx>
81 #include <TopLoc_Location.hxx>
82 #include <TopTools_IndexedMapOfShape.hxx>
83 #include <TopTools_MapOfShape.hxx>
85 #include <TopoDS_Compound.hxx>
86 #include <TopoDS_Face.hxx>
87 #include <TopoDS_TShape.hxx>
88 #include <gp_Cone.hxx>
89 #include <gp_Cylinder.hxx>
92 #include <gp_Pnt2d.hxx>
93 #include <gp_Sphere.hxx>
94 #include <gp_Torus.hxx>
98 #include <boost/container/flat_map.hpp>
104 // See https://docs.microsoft.com/en-gb/cpp/porting/modifying-winver-and-win32-winnt?view=vs-2019
105 // Windows 10 = 0x0A00
106 #define WINVER 0x0A00
107 #define _WIN32_WINNT 0x0A00
110 #include <tbb/parallel_for.h>
111 //#include <tbb/enumerable_thread_specific.h>
115 using namespace SMESH;
121 //=============================================================================
125 //=============================================================================
127 StdMeshers_Cartesian_3D::StdMeshers_Cartesian_3D(int hypId, SMESH_Gen * gen)
128 :SMESH_3D_Algo(hypId, gen)
130 _name = "Cartesian_3D";
131 _shapeType = (1 << TopAbs_SOLID); // 1 bit /shape type
132 _compatibleHypothesis.push_back("CartesianParameters3D");
134 _onlyUnaryInput = false; // to mesh all SOLIDs at once
135 _requireDiscreteBoundary = false; // 2D mesh not needed
136 _supportSubmeshes = false; // do not use any existing mesh
139 //=============================================================================
141 * Check presence of a hypothesis
143 //=============================================================================
145 bool StdMeshers_Cartesian_3D::CheckHypothesis (SMESH_Mesh& aMesh,
146 const TopoDS_Shape& aShape,
147 Hypothesis_Status& aStatus)
149 aStatus = SMESH_Hypothesis::HYP_MISSING;
151 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape);
152 list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
153 if ( h == hyps.end())
158 for ( ; h != hyps.end(); ++h )
160 if (( _hyp = dynamic_cast<const StdMeshers_CartesianParameters3D*>( *h )))
162 aStatus = _hyp->IsDefined() ? HYP_OK : HYP_BAD_PARAMETER;
167 return aStatus == HYP_OK;
172 typedef int TGeomID; // IDs of sub-shapes
174 //=============================================================================
175 // Definitions of internal utils
176 // --------------------------------------------------------------------------
178 Trans_TANGENT = IntCurveSurface_Tangent,
179 Trans_IN = IntCurveSurface_In,
180 Trans_OUT = IntCurveSurface_Out,
182 Trans_INTERNAL // for INTERNAL FACE
184 // --------------------------------------------------------------------------
186 * \brief Container of IDs of SOLID sub-shapes
188 class Solid // sole SOLID contains all sub-shapes
190 TGeomID _id; // SOLID id
191 bool _hasInternalFaces;
194 virtual bool Contains( TGeomID /*subID*/ ) const { return true; }
195 virtual bool ContainsAny( const vector< TGeomID>& /*subIDs*/ ) const { return true; }
196 virtual TopAbs_Orientation Orientation( const TopoDS_Shape& s ) const { return s.Orientation(); }
197 virtual bool IsOutsideOriented( TGeomID /*faceID*/ ) const { return true; }
198 void SetID( TGeomID id ) { _id = id; }
199 TGeomID ID() const { return _id; }
200 void SetHasInternalFaces( bool has ) { _hasInternalFaces = has; }
201 bool HasInternalFaces() const { return _hasInternalFaces; }
203 // --------------------------------------------------------------------------
204 class OneOfSolids : public Solid
206 TColStd_MapOfInteger _subIDs;
207 TopTools_MapOfShape _faces; // keep FACE orientation
208 TColStd_MapOfInteger _outFaceIDs; // FACEs of shape_to_mesh oriented outside the SOLID
210 void Init( const TopoDS_Shape& solid,
211 TopAbs_ShapeEnum subType,
212 const SMESHDS_Mesh* mesh );
213 virtual bool Contains( TGeomID i ) const { return i == ID() || _subIDs.Contains( i ); }
214 virtual bool ContainsAny( const vector< TGeomID>& subIDs ) const
216 for ( size_t i = 0; i < subIDs.size(); ++i ) if ( Contains( subIDs[ i ])) return true;
219 virtual TopAbs_Orientation Orientation( const TopoDS_Shape& face ) const
221 const TopoDS_Shape& sInMap = const_cast< OneOfSolids* >(this)->_faces.Added( face );
222 return sInMap.Orientation();
224 virtual bool IsOutsideOriented( TGeomID faceID ) const
226 return faceID == 0 || _outFaceIDs.Contains( faceID );
229 // --------------------------------------------------------------------------
235 TopoDS_Shape _mainShape;
236 vector< vector< TGeomID > > _solidIDsByShapeID;// V/E/F ID -> SOLID IDs
238 map< TGeomID, OneOfSolids > _solidByID;
239 TColStd_MapOfInteger _boundaryFaces; // FACEs on boundary of mesh->ShapeToMesh()
240 TColStd_MapOfInteger _strangeEdges; // EDGEs shared by strange FACEs
241 TGeomID _extIntFaceID; // pseudo FACE - extension of INTERNAL FACE
243 Controls::ElementsOnShape _edgeClassifier;
244 Controls::ElementsOnShape _vertexClassifier;
246 bool IsOneSolid() const { return _solidByID.size() < 2; }
248 // --------------------------------------------------------------------------
250 * \brief Common data of any intersection between a Grid and a shape
252 struct B_IntersectPoint
254 mutable const SMDS_MeshNode* _node;
255 mutable vector< TGeomID > _faceIDs;
257 B_IntersectPoint(): _node(NULL) {}
258 void Add( const vector< TGeomID >& fIDs, const SMDS_MeshNode* n=0 ) const;
259 int HasCommonFace( const B_IntersectPoint * other, int avoidFace=-1 ) const;
260 bool IsOnFace( int faceID ) const;
261 virtual ~B_IntersectPoint() {}
263 // --------------------------------------------------------------------------
265 * \brief Data of intersection between a GridLine and a TopoDS_Face
267 struct F_IntersectPoint : public B_IntersectPoint
271 mutable Transition _transition;
272 mutable size_t _indexOnLine;
274 bool operator< ( const F_IntersectPoint& o ) const { return _paramOnLine < o._paramOnLine; }
276 // --------------------------------------------------------------------------
278 * \brief Data of intersection between GridPlanes and a TopoDS_EDGE
280 struct E_IntersectPoint : public B_IntersectPoint
284 TGeomID _shapeID; // ID of EDGE or VERTEX
286 // --------------------------------------------------------------------------
288 * \brief A line of the grid and its intersections with 2D geometry
293 double _length; // line length
294 multiset< F_IntersectPoint > _intPoints;
296 void RemoveExcessIntPoints( const double tol );
297 TGeomID GetSolidIDBefore( multiset< F_IntersectPoint >::iterator ip,
298 const TGeomID prevID,
299 const Geometry& geom);
301 // --------------------------------------------------------------------------
303 * \brief Planes of the grid used to find intersections of an EDGE with a hexahedron
308 vector< gp_XYZ > _origins; // origin points of all planes in one direction
309 vector< double > _zProjs; // projections of origins to _zNorm
311 // --------------------------------------------------------------------------
313 * \brief Iterator on the parallel grid lines of one direction
319 size_t _iVar1, _iVar2, _iConst;
320 string _name1, _name2, _nameConst;
322 LineIndexer( size_t sz1, size_t sz2, size_t sz3,
323 size_t iv1, size_t iv2, size_t iConst,
324 const string& nv1, const string& nv2, const string& nConst )
326 _size[0] = sz1; _size[1] = sz2; _size[2] = sz3;
327 _curInd[0] = _curInd[1] = _curInd[2] = 0;
328 _iVar1 = iv1; _iVar2 = iv2; _iConst = iConst;
329 _name1 = nv1; _name2 = nv2; _nameConst = nConst;
332 size_t I() const { return _curInd[0]; }
333 size_t J() const { return _curInd[1]; }
334 size_t K() const { return _curInd[2]; }
335 void SetIJK( size_t i, size_t j, size_t k )
337 _curInd[0] = i; _curInd[1] = j; _curInd[2] = k;
341 if ( ++_curInd[_iVar1] == _size[_iVar1] )
342 _curInd[_iVar1] = 0, ++_curInd[_iVar2];
344 bool More() const { return _curInd[_iVar2] < _size[_iVar2]; }
345 size_t LineIndex () const { return _curInd[_iVar1] + _curInd[_iVar2]* _size[_iVar1]; }
346 size_t LineIndex10 () const { return (_curInd[_iVar1] + 1 ) + _curInd[_iVar2]* _size[_iVar1]; }
347 size_t LineIndex01 () const { return _curInd[_iVar1] + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
348 size_t LineIndex11 () const { return (_curInd[_iVar1] + 1 ) + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
349 void SetIndexOnLine (size_t i) { _curInd[ _iConst ] = i; }
350 size_t NbLines() const { return _size[_iVar1] * _size[_iVar2]; }
352 // --------------------------------------------------------------------------
354 * \brief Container of GridLine's
358 vector< double > _coords[3]; // coordinates of grid nodes
359 gp_XYZ _axes [3]; // axis directions
360 vector< GridLine > _lines [3]; // in 3 directions
361 double _tol, _minCellSize;
363 gp_Mat _invB; // inverted basis of _axes
365 // index shift within _nodes of nodes of a cell from the 1st node
368 vector< const SMDS_MeshNode* > _nodes; // mesh nodes at grid nodes
369 vector< const F_IntersectPoint* > _gridIntP; // grid node intersection with geometry
370 ObjectPool< E_IntersectPoint > _edgeIntPool; // intersections with EDGEs
371 ObjectPool< F_IntersectPoint > _extIntPool; // intersections with extended INTERNAL FACEs
372 //list< E_IntersectPoint > _edgeIntP; // intersections with EDGEs
377 bool _toConsiderInternalFaces;
378 bool _toUseThresholdForInternalFaces;
379 double _sizeThreshold;
381 SMESH_MesherHelper* _helper;
383 size_t CellIndex( size_t i, size_t j, size_t k ) const
385 return i + j*(_coords[0].size()-1) + k*(_coords[0].size()-1)*(_coords[1].size()-1);
387 size_t NodeIndex( size_t i, size_t j, size_t k ) const
389 return i + j*_coords[0].size() + k*_coords[0].size()*_coords[1].size();
391 size_t NodeIndexDX() const { return 1; }
392 size_t NodeIndexDY() const { return _coords[0].size(); }
393 size_t NodeIndexDZ() const { return _coords[0].size() * _coords[1].size(); }
395 LineIndexer GetLineIndexer(size_t iDir) const;
397 E_IntersectPoint* Add( const E_IntersectPoint& ip )
399 E_IntersectPoint* eip = _edgeIntPool.getNew();
403 void Remove( E_IntersectPoint* eip ) { _edgeIntPool.destroy( eip ); }
405 TGeomID ShapeID( const TopoDS_Shape& s ) const;
406 const TopoDS_Shape& Shape( TGeomID id ) const;
407 TopAbs_ShapeEnum ShapeType( TGeomID id ) const { return Shape(id).ShapeType(); }
408 void InitGeometry( const TopoDS_Shape& theShape );
409 void InitClassifier( const TopoDS_Shape& mainShape,
410 TopAbs_ShapeEnum shapeType,
411 Controls::ElementsOnShape& classifier );
412 void GetEdgesToImplement( map< TGeomID, vector< TGeomID > > & edge2faceMap,
413 const TopoDS_Shape& shape,
414 const vector< TopoDS_Shape >& faces );
415 void SetSolidFather( const TopoDS_Shape& s, const TopoDS_Shape& theShapeToMesh );
416 bool IsShared( TGeomID faceID ) const;
417 bool IsAnyShared( const std::vector< TGeomID >& faceIDs ) const;
418 bool IsInternal( TGeomID faceID ) const {
419 return ( faceID == PseudoIntExtFaceID() ||
420 Shape( faceID ).Orientation() == TopAbs_INTERNAL ); }
421 bool IsSolid( TGeomID shapeID ) const {
422 if ( _geometry.IsOneSolid() ) return _geometry._soleSolid.ID() == shapeID;
423 else return _geometry._solidByID.count( shapeID ); }
424 bool IsStrangeEdge( TGeomID id ) const { return _geometry._strangeEdges.Contains( id ); }
425 TGeomID PseudoIntExtFaceID() const { return _geometry._extIntFaceID; }
426 Solid* GetSolid( TGeomID solidID = 0 );
427 Solid* GetOneOfSolids( TGeomID solidID );
428 const vector< TGeomID > & GetSolidIDs( TGeomID subShapeID ) const;
429 bool IsCorrectTransition( TGeomID faceID, const Solid* solid );
430 bool IsBoundaryFace( TGeomID face ) const { return _geometry._boundaryFaces.Contains( face ); }
431 void SetOnShape( const SMDS_MeshNode* n, const F_IntersectPoint& ip, bool unset=false );
432 bool IsToCheckNodePos() const { return !_toAddEdges && _toCreateFaces; }
433 bool IsToRemoveExcessEntities() const { return !_toAddEdges; }
435 void SetCoordinates(const vector<double>& xCoords,
436 const vector<double>& yCoords,
437 const vector<double>& zCoords,
438 const double* axesDirs,
439 const Bnd_Box& bndBox );
440 void ComputeUVW(const gp_XYZ& p, double uvw[3]);
441 void ComputeNodes(SMESH_MesherHelper& helper);
443 // --------------------------------------------------------------------------
445 * \brief Return cells sharing a link
447 struct CellsAroundLink
455 CellsAroundLink( Grid* grid, int iDir ):
457 _dInd{ {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} },
458 _nbCells{ grid->_coords[0].size() - 1,
459 grid->_coords[1].size() - 1,
460 grid->_coords[2].size() - 1 },
463 const int iDirOther[3][2] = {{ 1,2 },{ 0,2 },{ 0,1 }};
464 _dInd[1][ iDirOther[iDir][0] ] = -1;
465 _dInd[2][ iDirOther[iDir][1] ] = -1;
466 _dInd[3][ iDirOther[iDir][0] ] = -1; _dInd[3][ iDirOther[iDir][1] ] = -1;
468 void Init( int i, int j, int k, int link12 = 0 )
471 _i = i - _dInd[iL][0];
472 _j = j - _dInd[iL][1];
473 _k = k - _dInd[iL][2];
475 bool GetCell( int iL, int& i, int& j, int& k, int& cellIndex, int& linkIndex )
477 i = _i + _dInd[iL][0];
478 j = _j + _dInd[iL][1];
479 k = _k + _dInd[iL][2];
480 if ( i < 0 || i >= (int)_nbCells[0] ||
481 j < 0 || j >= (int)_nbCells[1] ||
482 k < 0 || k >= (int)_nbCells[2] )
484 cellIndex = _grid->CellIndex( i,j,k );
485 linkIndex = iL + _iDir * 4;
489 // --------------------------------------------------------------------------
491 * \brief Intersector of TopoDS_Face with all GridLine's
493 struct FaceGridIntersector
499 IntCurvesFace_Intersector* _surfaceInt;
500 vector< std::pair< GridLine*, F_IntersectPoint > > _intersections;
502 FaceGridIntersector(): _grid(0), _surfaceInt(0) {}
505 void StoreIntersections()
507 for ( size_t i = 0; i < _intersections.size(); ++i )
509 multiset< F_IntersectPoint >::iterator ip =
510 _intersections[i].first->_intPoints.insert( _intersections[i].second );
511 ip->_faceIDs.reserve( 1 );
512 ip->_faceIDs.push_back( _faceID );
515 const Bnd_Box& GetFaceBndBox()
517 GetCurveFaceIntersector();
520 IntCurvesFace_Intersector* GetCurveFaceIntersector()
524 _surfaceInt = new IntCurvesFace_Intersector( _face, Precision::PConfusion() );
525 _bndBox = _surfaceInt->Bounding();
526 if ( _bndBox.IsVoid() )
527 BRepBndLib::Add (_face, _bndBox);
531 bool IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const;
533 // --------------------------------------------------------------------------
535 * \brief Intersector of a surface with a GridLine
537 struct FaceLineIntersector
540 double _u, _v, _w; // params on the face and the line
541 Transition _transition; // transition at intersection (see IntCurveSurface.cdl)
542 Transition _transIn, _transOut; // IN and OUT transitions depending of face orientation
545 gp_Cylinder _cylinder;
549 IntCurvesFace_Intersector* _surfaceInt;
551 vector< F_IntersectPoint > _intPoints;
553 void IntersectWithPlane (const GridLine& gridLine);
554 void IntersectWithCylinder(const GridLine& gridLine);
555 void IntersectWithCone (const GridLine& gridLine);
556 void IntersectWithSphere (const GridLine& gridLine);
557 void IntersectWithTorus (const GridLine& gridLine);
558 void IntersectWithSurface (const GridLine& gridLine);
560 bool UVIsOnFace() const;
561 void addIntPoint(const bool toClassify=true);
562 bool isParamOnLineOK( const double linLength )
564 return -_tol < _w && _w < linLength + _tol;
566 FaceLineIntersector():_surfaceInt(0) {}
567 ~FaceLineIntersector() { if (_surfaceInt ) delete _surfaceInt; _surfaceInt = 0; }
569 // --------------------------------------------------------------------------
571 * \brief Class representing topology of the hexahedron and creating a mesh
572 * volume basing on analysis of hexahedron intersection with geometry
576 // --------------------------------------------------------------------------------
579 enum IsInternalFlag { IS_NOT_INTERNAL, IS_INTERNAL, IS_CUT_BY_INTERNAL_FACE };
580 // --------------------------------------------------------------------------------
581 struct _Node //!< node either at a hexahedron corner or at intersection
583 const SMDS_MeshNode* _node; // mesh node at hexahedron corner
584 const B_IntersectPoint* _intPoint;
585 const _Face* _usedInFace;
586 char _isInternalFlags;
588 _Node(const SMDS_MeshNode* n=0, const B_IntersectPoint* ip=0)
589 :_node(n), _intPoint(ip), _usedInFace(0), _isInternalFlags(0) {}
590 const SMDS_MeshNode* Node() const
591 { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
592 const E_IntersectPoint* EdgeIntPnt() const
593 { return static_cast< const E_IntersectPoint* >( _intPoint ); }
594 const F_IntersectPoint* FaceIntPnt() const
595 { return static_cast< const F_IntersectPoint* >( _intPoint ); }
596 const vector< TGeomID >& faces() const { return _intPoint->_faceIDs; }
597 TGeomID face(size_t i) const { return _intPoint->_faceIDs[ i ]; }
598 void SetInternal( IsInternalFlag intFlag ) { _isInternalFlags |= intFlag; }
599 bool IsCutByInternal() const { return _isInternalFlags & IS_CUT_BY_INTERNAL_FACE; }
600 bool IsUsedInFace( const _Face* polygon = 0 )
602 return polygon ? ( _usedInFace == polygon ) : bool( _usedInFace );
604 TGeomID IsLinked( const B_IntersectPoint* other,
605 TGeomID avoidFace=-1 ) const // returns id of a common face
607 return _intPoint ? _intPoint->HasCommonFace( other, avoidFace ) : 0;
609 bool IsOnFace( TGeomID faceID ) const // returns true if faceID is found
611 return _intPoint ? _intPoint->IsOnFace( faceID ) : false;
615 if ( const SMDS_MeshNode* n = Node() )
616 return SMESH_NodeXYZ( n );
617 if ( const E_IntersectPoint* eip =
618 dynamic_cast< const E_IntersectPoint* >( _intPoint ))
620 return gp_Pnt( 1e100, 0, 0 );
622 TGeomID ShapeID() const
624 if ( const E_IntersectPoint* eip = dynamic_cast< const E_IntersectPoint* >( _intPoint ))
625 return eip->_shapeID;
628 void Add( const E_IntersectPoint* ip )
630 // Possible cases before Add(ip):
631 /// 1) _node != 0 --> _Node at hex corner ( _intPoint == 0 || _intPoint._node == 0 )
632 /// 2) _node == 0 && _intPoint._node != 0 --> link intersected by FACE
633 /// 3) _node == 0 && _intPoint._node == 0 --> _Node at EDGE intersection
635 // If ip is added in cases 1) and 2) _node position must be changed to ip._shapeID
636 // at creation of elements
637 // To recognize this case, set _intPoint._node = Node()
638 const SMDS_MeshNode* node = Node();
643 ip->Add( _intPoint->_faceIDs );
647 _node = _intPoint->_node = node;
650 // --------------------------------------------------------------------------------
651 struct _Link // link connecting two _Node's
654 _Face* _faces[2]; // polygons sharing a link
655 vector< const F_IntersectPoint* > _fIntPoints; // GridLine intersections with FACEs
656 vector< _Node* > _fIntNodes; // _Node's at _fIntPoints
657 vector< _Link > _splits;
658 _Link(): _faces{ 0, 0 } {}
660 // --------------------------------------------------------------------------------
665 _OrientedLink( _Link* link=0, bool reverse=false ): _link(link), _reverse(reverse) {}
666 void Reverse() { _reverse = !_reverse; }
667 int NbResultLinks() const { return _link->_splits.size(); }
668 _OrientedLink ResultLink(int i) const
670 return _OrientedLink(&_link->_splits[_reverse ? NbResultLinks()-i-1 : i],_reverse);
672 _Node* FirstNode() const { return _link->_nodes[ _reverse ]; }
673 _Node* LastNode() const { return _link->_nodes[ !_reverse ]; }
674 operator bool() const { return _link; }
675 vector< TGeomID > GetNotUsedFace(const set<TGeomID>& usedIDs ) const // returns supporting FACEs
677 vector< TGeomID > faces;
678 const B_IntersectPoint *ip0, *ip1;
679 if (( ip0 = _link->_nodes[0]->_intPoint ) &&
680 ( ip1 = _link->_nodes[1]->_intPoint ))
682 for ( size_t i = 0; i < ip0->_faceIDs.size(); ++i )
683 if ( ip1->IsOnFace ( ip0->_faceIDs[i] ) &&
684 !usedIDs.count( ip0->_faceIDs[i] ) )
685 faces.push_back( ip0->_faceIDs[i] );
689 bool HasEdgeNodes() const
691 return ( dynamic_cast< const E_IntersectPoint* >( _link->_nodes[0]->_intPoint ) ||
692 dynamic_cast< const E_IntersectPoint* >( _link->_nodes[1]->_intPoint ));
696 return !_link->_faces[0] ? 0 : 1 + bool( _link->_faces[1] );
698 void AddFace( _Face* f )
700 if ( _link->_faces[0] )
702 _link->_faces[1] = f;
706 _link->_faces[0] = f;
707 _link->_faces[1] = 0;
710 void RemoveFace( _Face* f )
712 if ( !_link->_faces[0] ) return;
714 if ( _link->_faces[1] == f )
716 _link->_faces[1] = 0;
718 else if ( _link->_faces[0] == f )
720 _link->_faces[0] = 0;
721 if ( _link->_faces[1] )
723 _link->_faces[0] = _link->_faces[1];
724 _link->_faces[1] = 0;
729 // --------------------------------------------------------------------------------
730 struct _SplitIterator //! set to _hexLinks splits on one side of INTERNAL FACEs
732 struct _Split // data of a link split
734 int _linkID; // hex link ID
736 int _iCheckIteration; // iteration where split is tried as Hexahedron split
737 _Link* _checkedSplit; // split set to hex links
738 bool _isUsed; // used in a volume
740 _Split( _Link & split, int iLink ):
741 _linkID( iLink ), _nodes{ split._nodes[0], split._nodes[1] },
742 _iCheckIteration( 0 ), _isUsed( false )
744 bool IsCheckedOrUsed( bool used ) const { return used ? _isUsed : _iCheckIteration > 0; }
747 std::vector< _Split > _splits;
751 std::vector< _Node* > _freeNodes; // nodes reached while composing a split set
753 _SplitIterator( _Link* hexLinks ):
754 _hexLinks( hexLinks ), _iterationNb(0), _nbChecked(0), _nbUsed(0)
756 _freeNodes.reserve( 12 );
757 _splits.reserve( 24 );
758 for ( int iL = 0; iL < 12; ++iL )
759 for ( size_t iS = 0; iS < _hexLinks[ iL ]._splits.size(); ++iS )
760 _splits.emplace_back( _hexLinks[ iL ]._splits[ iS ], iL );
763 bool More() const { return _nbUsed < _splits.size(); }
766 // --------------------------------------------------------------------------------
769 SMESH_Block::TShapeID _name;
770 vector< _OrientedLink > _links; // links on GridLine's
771 vector< _Link > _polyLinks; // links added to close a polygonal face
772 vector< _Node* > _eIntNodes; // nodes at intersection with EDGEs
774 _Face():_name( SMESH_Block::ID_NONE )
776 bool IsPolyLink( const _OrientedLink& ol )
778 return _polyLinks.empty() ? false :
779 ( &_polyLinks[0] <= ol._link && ol._link <= &_polyLinks.back() );
781 void AddPolyLink(_Node* n0, _Node* n1, _Face* faceToFindEqual=0)
783 if ( faceToFindEqual && faceToFindEqual != this ) {
784 for ( size_t iL = 0; iL < faceToFindEqual->_polyLinks.size(); ++iL )
785 if ( faceToFindEqual->_polyLinks[iL]._nodes[0] == n1 &&
786 faceToFindEqual->_polyLinks[iL]._nodes[1] == n0 )
789 ( _OrientedLink( & faceToFindEqual->_polyLinks[iL], /*reverse=*/true ));
796 _polyLinks.push_back( l );
797 _links.push_back( _OrientedLink( &_polyLinks.back() ));
800 // --------------------------------------------------------------------------------
801 struct _volumeDef // holder of nodes of a volume mesh element
807 const SMDS_MeshNode* _node; // mesh node at hexahedron corner
808 const B_IntersectPoint* _intPoint;
810 _nodeDef(): _node(0), _intPoint(0) {}
811 _nodeDef( _Node* n ): _node( n->_node), _intPoint( n->_intPoint ) {}
812 const SMDS_MeshNode* Node() const
813 { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
814 const E_IntersectPoint* EdgeIntPnt() const
815 { return static_cast< const E_IntersectPoint* >( _intPoint ); }
816 _ptr Ptr() const { return Node() ? (_ptr) Node() : (_ptr) EdgeIntPnt(); }
817 bool operator==(const _nodeDef& other ) const { return Ptr() == other.Ptr(); }
820 vector< _nodeDef > _nodes;
821 vector< int > _quantities;
822 _volumeDef* _next; // to store several _volumeDefs in a chain
824 const SMDS_MeshElement* _volume; // new volume
826 vector< SMESH_Block::TShapeID > _names; // name of side a polygon originates from
828 _volumeDef(): _next(0), _solidID(0), _volume(0) {}
829 ~_volumeDef() { delete _next; }
830 _volumeDef( _volumeDef& other ):
831 _next(0), _solidID( other._solidID ), _volume( other._volume )
832 { _nodes.swap( other._nodes ); _quantities.swap( other._quantities ); other._volume = 0;
833 _names.swap( other._names ); }
835 size_t size() const { return 1 + ( _next ? _next->size() : 0 ); }
836 _volumeDef* at(int index)
837 { return index == 0 ? this : ( _next ? _next->at(index-1) : _next ); }
839 void Set( _Node** nodes, int nb )
840 { _nodes.assign( nodes, nodes + nb ); }
842 void SetNext( _volumeDef* vd )
843 { if ( _next ) { _next->SetNext( vd ); } else { _next = vd; }}
845 bool IsEmpty() const { return (( _nodes.empty() ) &&
846 ( !_next || _next->IsEmpty() )); }
847 bool IsPolyhedron() const { return ( !_quantities.empty() ||
848 ( _next && !_next->_quantities.empty() )); }
851 struct _linkDef: public std::pair<_ptr,_ptr> // to join polygons in removeExcessSideDivision()
853 _nodeDef _node1;//, _node2;
854 mutable /*const */_linkDef *_prev, *_next;
857 _linkDef():_prev(0), _next(0) {}
859 void init( const _nodeDef& n1, const _nodeDef& n2, size_t iLoop )
861 _node1 = n1; //_node2 = n2;
865 if ( first > second ) std::swap( first, second );
867 void setNext( _linkDef* next )
875 // topology of a hexahedron
877 _Link _hexLinks [12];
880 // faces resulted from hexahedron intersection
881 vector< _Face > _polygons;
883 // intresections with EDGEs
884 vector< const E_IntersectPoint* > _eIntPoints;
886 // additional nodes created at intersection points
887 vector< _Node > _intNodes;
889 // nodes inside the hexahedron (at VERTEXes) refer to _intNodes
890 vector< _Node* > _vIntNodes;
892 // computed volume elements
893 _volumeDef _volumeDefs;
896 double _sideLength[3];
897 int _nbCornerNodes, _nbFaceIntNodes, _nbBndNodes;
898 int _origNodeInd; // index of _hexNodes[0] node within the _grid
907 Hexahedron(Grid* grid);
908 int MakeElements(SMESH_MesherHelper& helper,
909 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
910 void computeElements( const Solid* solid = 0, int solidIndex = -1 );
913 Hexahedron(const Hexahedron& other, size_t i, size_t j, size_t k, int cellID );
914 void init( size_t i, size_t j, size_t k, const Solid* solid=0 );
915 void init( size_t i );
916 void setIJK( size_t i );
917 bool compute( const Solid* solid, const IsInternalFlag intFlag );
918 size_t getSolids( TGeomID ids[] );
919 bool isCutByInternalFace( IsInternalFlag & maxFlag );
920 void addEdges(SMESH_MesherHelper& helper,
921 vector< Hexahedron* >& intersectedHex,
922 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
923 gp_Pnt findIntPoint( double u1, double proj1, double u2, double proj2,
924 double proj, BRepAdaptor_Curve& curve,
925 const gp_XYZ& axis, const gp_XYZ& origin );
926 int getEntity( const E_IntersectPoint* ip, int* facets, int& sub );
927 bool addIntersection( const E_IntersectPoint* ip,
928 vector< Hexahedron* >& hexes,
929 int ijk[], int dIJK[] );
930 bool findChain( _Node* n1, _Node* n2, _Face& quad, vector<_Node*>& chainNodes );
931 bool closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const;
932 bool findChainOnEdge( const vector< _OrientedLink >& splits,
933 const _OrientedLink& prevSplit,
934 const _OrientedLink& avoidSplit,
937 vector<_Node*>& chn);
938 int addVolumes(SMESH_MesherHelper& helper );
939 void addFaces( SMESH_MesherHelper& helper,
940 const vector< const SMDS_MeshElement* > & boundaryVolumes );
941 void addSegments( SMESH_MesherHelper& helper,
942 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap );
943 void getVolumes( vector< const SMDS_MeshElement* > & volumes );
944 void getBoundaryElems( vector< const SMDS_MeshElement* > & boundaryVolumes );
945 void removeExcessSideDivision(const vector< Hexahedron* >& allHexa);
946 void removeExcessNodes(vector< Hexahedron* >& allHexa);
947 void preventVolumesOverlapping();
948 TGeomID getAnyFace() const;
949 void cutByExtendedInternal( std::vector< Hexahedron* >& hexes,
950 const TColStd_MapOfInteger& intEdgeIDs );
951 gp_Pnt mostDistantInternalPnt( int hexIndex, const gp_Pnt& p1, const gp_Pnt& p2 );
952 bool isOutPoint( _Link& link, int iP, SMESH_MesherHelper& helper, const Solid* solid ) const;
953 void sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID face);
954 bool isInHole() const;
955 bool hasStrangeEdge() const;
956 bool checkPolyhedronSize( bool isCutByInternalFace ) const;
961 bool debugDumpLink( _Link* link );
962 _Node* findEqualNode( vector< _Node* >& nodes,
963 const E_IntersectPoint* ip,
966 for ( size_t i = 0; i < nodes.size(); ++i )
967 if ( nodes[i]->EdgeIntPnt() == ip ||
968 nodes[i]->Point().SquareDistance( ip->_point ) <= tol2 )
972 bool isImplementEdges() const { return _grid->_edgeIntPool.nbElements(); }
973 bool isOutParam(const double uvw[3]) const;
975 typedef boost::container::flat_map< TGeomID, size_t > TID2Nb;
976 static void insertAndIncrement( TGeomID id, TID2Nb& id2nbMap )
978 TID2Nb::value_type s0( id, 0 );
979 TID2Nb::iterator id2nb = id2nbMap.insert( s0 ).first;
982 }; // class Hexahedron
985 // --------------------------------------------------------------------------
987 * \brief Hexahedron computing volumes in one thread
989 struct ParallelHexahedron
991 vector< Hexahedron* >& _hexVec;
992 ParallelHexahedron( vector< Hexahedron* >& hv ): _hexVec(hv) {}
993 void operator() ( const tbb::blocked_range<size_t>& r ) const
995 for ( size_t i = r.begin(); i != r.end(); ++i )
996 if ( Hexahedron* hex = _hexVec[ i ] )
997 hex->computeElements();
1000 // --------------------------------------------------------------------------
1002 * \brief Structure intersecting certain nb of faces with GridLine's in one thread
1004 struct ParallelIntersector
1006 vector< FaceGridIntersector >& _faceVec;
1007 ParallelIntersector( vector< FaceGridIntersector >& faceVec): _faceVec(faceVec){}
1008 void operator() ( const tbb::blocked_range<size_t>& r ) const
1010 for ( size_t i = r.begin(); i != r.end(); ++i )
1011 _faceVec[i].Intersect();
1016 //=============================================================================
1017 // Implementation of internal utils
1018 //=============================================================================
1020 * \brief adjust \a i to have \a val between values[i] and values[i+1]
1022 inline void locateValue( int & i, double val, const vector<double>& values,
1023 int& di, double tol )
1025 //val += values[0]; // input \a val is measured from 0.
1026 if ( i > (int) values.size()-2 )
1027 i = values.size()-2;
1029 while ( i+2 < (int) values.size() && val > values[ i+1 ])
1031 while ( i > 0 && val < values[ i ])
1034 if ( i > 0 && val - values[ i ] < tol )
1036 else if ( i+2 < (int) values.size() && values[ i+1 ] - val < tol )
1041 //=============================================================================
1043 * Remove coincident intersection points
1045 void GridLine::RemoveExcessIntPoints( const double tol )
1047 if ( _intPoints.size() < 2 ) return;
1049 set< Transition > tranSet;
1050 multiset< F_IntersectPoint >::iterator ip1, ip2 = _intPoints.begin();
1051 while ( ip2 != _intPoints.end() )
1055 while ( ip2 != _intPoints.end() && ip2->_paramOnLine - ip1->_paramOnLine <= tol )
1057 tranSet.insert( ip1->_transition );
1058 tranSet.insert( ip2->_transition );
1059 ip2->Add( ip1->_faceIDs );
1060 _intPoints.erase( ip1 );
1063 if ( tranSet.size() > 1 ) // points with different transition coincide
1065 bool isIN = tranSet.count( Trans_IN );
1066 bool isOUT = tranSet.count( Trans_OUT );
1067 if ( isIN && isOUT )
1068 (*ip1)._transition = Trans_TANGENT;
1070 (*ip1)._transition = isIN ? Trans_IN : Trans_OUT;
1074 //================================================================================
1076 * Return ID of SOLID for nodes before the given intersection point
1078 TGeomID GridLine::GetSolidIDBefore( multiset< F_IntersectPoint >::iterator ip,
1079 const TGeomID prevID,
1080 const Geometry& geom )
1082 if ( ip == _intPoints.begin() )
1085 if ( geom.IsOneSolid() )
1088 switch ( ip->_transition ) {
1089 case Trans_IN: isOut = true; break;
1090 case Trans_OUT: isOut = false; break;
1091 case Trans_TANGENT: isOut = ( prevID != 0 ); break;
1094 // singularity point (apex of a cone)
1095 multiset< F_IntersectPoint >::iterator ipBef = ip, ipAft = ++ip;
1096 if ( ipAft == _intPoints.end() )
1101 if ( ipBef->_transition != ipAft->_transition )
1102 isOut = ( ipBef->_transition == Trans_OUT );
1104 isOut = ( ipBef->_transition != Trans_OUT );
1108 case Trans_INTERNAL: isOut = false;
1111 return isOut ? 0 : geom._soleSolid.ID();
1114 const vector< TGeomID >& solids = geom._solidIDsByShapeID[ ip->_faceIDs[ 0 ]];
1117 if ( ip->_transition == Trans_INTERNAL )
1120 const vector< TGeomID >& solidsBef = geom._solidIDsByShapeID[ ip->_faceIDs[ 0 ]];
1122 if ( ip->_transition == Trans_IN ||
1123 ip->_transition == Trans_OUT )
1125 if ( solidsBef.size() == 1 )
1126 return ( solidsBef[0] == prevID ) ? 0 : solidsBef[0];
1128 return solidsBef[ solidsBef[0] == prevID ];
1131 if ( solidsBef.size() == 1 )
1132 return solidsBef[0];
1134 for ( size_t i = 0; i < solids.size(); ++i )
1136 vector< TGeomID >::const_iterator it =
1137 std::find( solidsBef.begin(), solidsBef.end(), solids[i] );
1138 if ( it != solidsBef.end() )
1143 //================================================================================
1147 void B_IntersectPoint::Add( const vector< TGeomID >& fIDs,
1148 const SMDS_MeshNode* n) const
1150 if ( _faceIDs.empty() )
1153 for ( size_t i = 0; i < fIDs.size(); ++i )
1155 vector< TGeomID >::iterator it =
1156 std::find( _faceIDs.begin(), _faceIDs.end(), fIDs[i] );
1157 if ( it == _faceIDs.end() )
1158 _faceIDs.push_back( fIDs[i] );
1163 //================================================================================
1165 * Returns index of a common face if any, else zero
1167 int B_IntersectPoint::HasCommonFace( const B_IntersectPoint * other, int avoidFace ) const
1170 for ( size_t i = 0; i < other->_faceIDs.size(); ++i )
1171 if ( avoidFace != other->_faceIDs[i] &&
1172 IsOnFace ( other->_faceIDs[i] ))
1173 return other->_faceIDs[i];
1176 //================================================================================
1178 * Returns \c true if \a faceID in in this->_faceIDs
1180 bool B_IntersectPoint::IsOnFace( int faceID ) const // returns true if faceID is found
1182 vector< TGeomID >::const_iterator it =
1183 std::find( _faceIDs.begin(), _faceIDs.end(), faceID );
1184 return ( it != _faceIDs.end() );
1186 //================================================================================
1188 * OneOfSolids initialization
1190 void OneOfSolids::Init( const TopoDS_Shape& solid,
1191 TopAbs_ShapeEnum subType,
1192 const SMESHDS_Mesh* mesh )
1194 SetID( mesh->ShapeToIndex( solid ));
1196 if ( subType == TopAbs_FACE )
1197 SetHasInternalFaces( false );
1199 for ( TopExp_Explorer sub( solid, subType ); sub.More(); sub.Next() )
1201 _subIDs.Add( mesh->ShapeToIndex( sub.Current() ));
1202 if ( subType == TopAbs_FACE )
1204 _faces.Add( sub.Current() );
1205 if ( sub.Current().Orientation() == TopAbs_INTERNAL )
1206 SetHasInternalFaces( true );
1208 TGeomID faceID = mesh->ShapeToIndex( sub.Current() );
1209 if ( sub.Current().Orientation() == TopAbs_INTERNAL ||
1210 sub.Current().Orientation() == mesh->IndexToShape( faceID ).Orientation() )
1211 _outFaceIDs.Add( faceID );
1215 //================================================================================
1217 * Return an iterator on GridLine's in a given direction
1219 LineIndexer Grid::GetLineIndexer(size_t iDir) const
1221 const size_t indices[] = { 1,2,0, 0,2,1, 0,1,2 };
1222 const string s [] = { "X", "Y", "Z" };
1223 LineIndexer li( _coords[0].size(), _coords[1].size(), _coords[2].size(),
1224 indices[iDir*3], indices[iDir*3+1], indices[iDir*3+2],
1225 s[indices[iDir*3]], s[indices[iDir*3+1]], s[indices[iDir*3+2]]);
1228 //=============================================================================
1230 * Creates GridLine's of the grid
1232 void Grid::SetCoordinates(const vector<double>& xCoords,
1233 const vector<double>& yCoords,
1234 const vector<double>& zCoords,
1235 const double* axesDirs,
1236 const Bnd_Box& shapeBox)
1238 _coords[0] = xCoords;
1239 _coords[1] = yCoords;
1240 _coords[2] = zCoords;
1242 _axes[0].SetCoord( axesDirs[0],
1245 _axes[1].SetCoord( axesDirs[3],
1248 _axes[2].SetCoord( axesDirs[6],
1251 _axes[0].Normalize();
1252 _axes[1].Normalize();
1253 _axes[2].Normalize();
1255 _invB.SetCols( _axes[0], _axes[1], _axes[2] );
1258 // compute tolerance
1259 _minCellSize = Precision::Infinite();
1260 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1262 for ( size_t i = 1; i < _coords[ iDir ].size(); ++i )
1264 double cellLen = _coords[ iDir ][ i ] - _coords[ iDir ][ i-1 ];
1265 if ( cellLen < _minCellSize )
1266 _minCellSize = cellLen;
1269 if ( _minCellSize < Precision::Confusion() )
1270 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1271 SMESH_Comment("Too small cell size: ") << _minCellSize );
1272 _tol = _minCellSize / 1000.;
1274 // attune grid extremities to shape bounding box
1276 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
1277 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
1278 double* cP[6] = { &_coords[0].front(), &_coords[1].front(), &_coords[2].front(),
1279 &_coords[0].back(), &_coords[1].back(), &_coords[2].back() };
1280 for ( int i = 0; i < 6; ++i )
1281 if ( fabs( sP[i] - *cP[i] ) < _tol )
1282 *cP[i] = sP[i];// + _tol/1000. * ( i < 3 ? +1 : -1 );
1284 for ( int iDir = 0; iDir < 3; ++iDir )
1286 if ( _coords[iDir][0] - sP[iDir] > _tol )
1288 _minCellSize = Min( _minCellSize, _coords[iDir][0] - sP[iDir] );
1289 _coords[iDir].insert( _coords[iDir].begin(), sP[iDir] + _tol/1000.);
1291 if ( sP[iDir+3] - _coords[iDir].back() > _tol )
1293 _minCellSize = Min( _minCellSize, sP[iDir+3] - _coords[iDir].back() );
1294 _coords[iDir].push_back( sP[iDir+3] - _tol/1000.);
1297 _tol = _minCellSize / 1000.;
1299 _origin = ( _coords[0][0] * _axes[0] +
1300 _coords[1][0] * _axes[1] +
1301 _coords[2][0] * _axes[2] );
1304 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1306 LineIndexer li = GetLineIndexer( iDir );
1307 _lines[iDir].resize( li.NbLines() );
1308 double len = _coords[ iDir ].back() - _coords[iDir].front();
1309 for ( ; li.More(); ++li )
1311 GridLine& gl = _lines[iDir][ li.LineIndex() ];
1312 gl._line.SetLocation( _coords[0][li.I()] * _axes[0] +
1313 _coords[1][li.J()] * _axes[1] +
1314 _coords[2][li.K()] * _axes[2] );
1315 gl._line.SetDirection( _axes[ iDir ]);
1320 //================================================================================
1322 * Return local ID of shape
1324 TGeomID Grid::ShapeID( const TopoDS_Shape& s ) const
1326 return _helper->GetMeshDS()->ShapeToIndex( s );
1328 //================================================================================
1330 * Return a shape by its local ID
1332 const TopoDS_Shape& Grid::Shape( TGeomID id ) const
1334 return _helper->GetMeshDS()->IndexToShape( id );
1336 //================================================================================
1338 * Initialize _geometry
1340 void Grid::InitGeometry( const TopoDS_Shape& theShapeToMesh )
1342 SMESH_Mesh* mesh = _helper->GetMesh();
1344 _geometry._mainShape = theShapeToMesh;
1345 _geometry._extIntFaceID = mesh->GetMeshDS()->MaxShapeIndex() * 100;
1346 _geometry._soleSolid.SetID( 0 );
1347 _geometry._soleSolid.SetHasInternalFaces( false );
1349 InitClassifier( theShapeToMesh, TopAbs_VERTEX, _geometry._vertexClassifier );
1350 InitClassifier( theShapeToMesh, TopAbs_EDGE , _geometry._edgeClassifier );
1352 TopExp_Explorer solidExp( theShapeToMesh, TopAbs_SOLID );
1354 bool isSeveralSolids = false;
1355 if ( _toConsiderInternalFaces ) // check nb SOLIDs
1358 isSeveralSolids = solidExp.More();
1359 _toConsiderInternalFaces = isSeveralSolids;
1362 if ( !isSeveralSolids ) // look for an internal FACE
1364 TopExp_Explorer fExp( theShapeToMesh, TopAbs_FACE );
1365 for ( ; fExp.More() && !_toConsiderInternalFaces; fExp.Next() )
1366 _toConsiderInternalFaces = ( fExp.Current().Orientation() == TopAbs_INTERNAL );
1368 _geometry._soleSolid.SetHasInternalFaces( _toConsiderInternalFaces );
1369 _geometry._soleSolid.SetID( ShapeID( solidExp.Current() ));
1371 else // fill Geometry::_solidByID
1373 for ( ; solidExp.More(); solidExp.Next() )
1375 OneOfSolids & solid = _geometry._solidByID[ ShapeID( solidExp.Current() )];
1376 solid.Init( solidExp.Current(), TopAbs_FACE, mesh->GetMeshDS() );
1377 solid.Init( solidExp.Current(), TopAbs_EDGE, mesh->GetMeshDS() );
1378 solid.Init( solidExp.Current(), TopAbs_VERTEX, mesh->GetMeshDS() );
1384 _geometry._soleSolid.SetID( ShapeID( solidExp.Current() ));
1387 if ( !_toCreateFaces )
1389 int nbSolidsGlobal = _helper->Count( mesh->GetShapeToMesh(), TopAbs_SOLID, false );
1390 int nbSolidsLocal = _helper->Count( theShapeToMesh, TopAbs_SOLID, false );
1391 _toCreateFaces = ( nbSolidsLocal < nbSolidsGlobal );
1394 TopTools_IndexedMapOfShape faces;
1395 if ( _toCreateFaces || isSeveralSolids )
1396 TopExp::MapShapes( theShapeToMesh, TopAbs_FACE, faces );
1398 // find boundary FACEs on boundary of mesh->ShapeToMesh()
1399 if ( _toCreateFaces )
1400 for ( int i = 1; i <= faces.Size(); ++i )
1401 if ( faces(i).Orientation() != TopAbs_INTERNAL &&
1402 _helper->NbAncestors( faces(i), *mesh, TopAbs_SOLID ) == 1 )
1404 _geometry._boundaryFaces.Add( ShapeID( faces(i) ));
1407 if ( isSeveralSolids )
1408 for ( int i = 1; i <= faces.Size(); ++i )
1410 SetSolidFather( faces(i), theShapeToMesh );
1411 for ( TopExp_Explorer eExp( faces(i), TopAbs_EDGE ); eExp.More(); eExp.Next() )
1413 const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
1414 SetSolidFather( edge, theShapeToMesh );
1415 SetSolidFather( _helper->IthVertex( 0, edge ), theShapeToMesh );
1416 SetSolidFather( _helper->IthVertex( 1, edge ), theShapeToMesh );
1421 //================================================================================
1423 * Store ID of SOLID as father of its child shape ID
1425 void Grid::SetSolidFather( const TopoDS_Shape& s, const TopoDS_Shape& theShapeToMesh )
1427 if ( _geometry._solidIDsByShapeID.empty() )
1428 _geometry._solidIDsByShapeID.resize( _helper->GetMeshDS()->MaxShapeIndex() + 1 );
1430 vector< TGeomID > & solidIDs = _geometry._solidIDsByShapeID[ ShapeID( s )];
1431 if ( !solidIDs.empty() )
1433 solidIDs.reserve(2);
1434 PShapeIteratorPtr solidIt = _helper->GetAncestors( s,
1435 *_helper->GetMesh(),
1438 while ( const TopoDS_Shape* solid = solidIt->next() )
1439 solidIDs.push_back( ShapeID( *solid ));
1441 //================================================================================
1443 * Return IDs of solids given sub-shape belongs to
1445 const vector< TGeomID > & Grid::GetSolidIDs( TGeomID subShapeID ) const
1447 return _geometry._solidIDsByShapeID[ subShapeID ];
1449 //================================================================================
1451 * Check if a sub-shape belongs to several SOLIDs
1453 bool Grid::IsShared( TGeomID shapeID ) const
1455 return !_geometry.IsOneSolid() && ( _geometry._solidIDsByShapeID[ shapeID ].size() > 1 );
1457 //================================================================================
1459 * Check if any of FACEs belongs to several SOLIDs
1461 bool Grid::IsAnyShared( const std::vector< TGeomID >& faceIDs ) const
1463 for ( size_t i = 0; i < faceIDs.size(); ++i )
1464 if ( IsShared( faceIDs[ i ]))
1468 //================================================================================
1470 * Return Solid by ID
1472 Solid* Grid::GetSolid( TGeomID solidID )
1474 if ( !solidID || _geometry.IsOneSolid() || _geometry._solidByID.empty() )
1475 return & _geometry._soleSolid;
1477 return & _geometry._solidByID[ solidID ];
1479 //================================================================================
1481 * Return OneOfSolids by ID
1483 Solid* Grid::GetOneOfSolids( TGeomID solidID )
1485 map< TGeomID, OneOfSolids >::iterator is2s = _geometry._solidByID.find( solidID );
1486 if ( is2s != _geometry._solidByID.end() )
1487 return & is2s->second;
1489 return & _geometry._soleSolid;
1491 //================================================================================
1493 * Check if transition on given FACE is correct for a given SOLID
1495 bool Grid::IsCorrectTransition( TGeomID faceID, const Solid* solid )
1497 if ( _geometry.IsOneSolid() )
1500 const vector< TGeomID >& solidIDs = _geometry._solidIDsByShapeID[ faceID ];
1501 return solidIDs[0] == solid->ID();
1504 //================================================================================
1506 * Assign to geometry a node at FACE intersection
1508 void Grid::SetOnShape( const SMDS_MeshNode* n, const F_IntersectPoint& ip, bool unset )
1511 SMESHDS_Mesh* mesh = _helper->GetMeshDS();
1512 if ( ip._faceIDs.size() == 1 )
1514 mesh->SetNodeOnFace( n, ip._faceIDs[0], ip._u, ip._v );
1516 else if ( _geometry._vertexClassifier.IsSatisfy( n, &s ))
1518 if ( unset ) mesh->UnSetNodeOnShape( n );
1519 mesh->SetNodeOnVertex( n, TopoDS::Vertex( s ));
1521 else if ( _geometry._edgeClassifier.IsSatisfy( n, &s ))
1523 if ( unset ) mesh->UnSetNodeOnShape( n );
1524 mesh->SetNodeOnEdge( n, TopoDS::Edge( s ));
1526 else if ( ip._faceIDs.size() > 0 )
1528 mesh->SetNodeOnFace( n, ip._faceIDs[0], ip._u, ip._v );
1530 else if ( !unset && _geometry.IsOneSolid() )
1532 mesh->SetNodeInVolume( n, _geometry._soleSolid.ID() );
1535 //================================================================================
1537 * Initialize a classifier
1539 void Grid::InitClassifier( const TopoDS_Shape& mainShape,
1540 TopAbs_ShapeEnum shapeType,
1541 Controls::ElementsOnShape& classifier )
1543 TopTools_IndexedMapOfShape shapes;
1544 TopExp::MapShapes( mainShape, shapeType, shapes );
1546 TopoDS_Compound compound; BRep_Builder builder;
1547 builder.MakeCompound( compound );
1548 for ( int i = 1; i <= shapes.Size(); ++i )
1549 builder.Add( compound, shapes(i) );
1551 classifier.SetMesh( _helper->GetMeshDS() );
1552 //classifier.SetTolerance( _tol ); // _tol is not initialised
1553 classifier.SetShape( compound, SMDSAbs_Node );
1556 //================================================================================
1558 * Return EDGEs with FACEs to implement into the mesh
1560 void Grid::GetEdgesToImplement( map< TGeomID, vector< TGeomID > > & edge2faceIDsMap,
1561 const TopoDS_Shape& shape,
1562 const vector< TopoDS_Shape >& faces )
1564 // check if there are strange EDGEs
1565 TopTools_IndexedMapOfShape faceMap;
1566 TopExp::MapShapes( _helper->GetMesh()->GetShapeToMesh(), TopAbs_FACE, faceMap );
1567 int nbFacesGlobal = faceMap.Size();
1568 faceMap.Clear( false );
1569 TopExp::MapShapes( shape, TopAbs_FACE, faceMap );
1570 int nbFacesLocal = faceMap.Size();
1571 bool hasStrangeEdges = ( nbFacesGlobal > nbFacesLocal );
1572 if ( !_toAddEdges && !hasStrangeEdges )
1573 return; // no FACEs in contact with those meshed by other algo
1575 for ( size_t i = 0; i < faces.size(); ++i )
1577 _helper->SetSubShape( faces[i] );
1578 for ( TopExp_Explorer eExp( faces[i], TopAbs_EDGE ); eExp.More(); eExp.Next() )
1580 const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
1581 if ( hasStrangeEdges )
1583 bool hasStrangeFace = false;
1584 PShapeIteratorPtr faceIt = _helper->GetAncestors( edge, *_helper->GetMesh(), TopAbs_FACE);
1585 while ( const TopoDS_Shape* face = faceIt->next() )
1586 if (( hasStrangeFace = !faceMap.Contains( *face )))
1588 if ( !hasStrangeFace && !_toAddEdges )
1590 _geometry._strangeEdges.Add( ShapeID( edge ));
1591 _geometry._strangeEdges.Add( ShapeID( _helper->IthVertex( 0, edge )));
1592 _geometry._strangeEdges.Add( ShapeID( _helper->IthVertex( 1, edge )));
1594 if ( !SMESH_Algo::isDegenerated( edge ) &&
1595 !_helper->IsRealSeam( edge ))
1597 edge2faceIDsMap[ ShapeID( edge )].push_back( ShapeID( faces[i] ));
1604 //================================================================================
1606 * Computes coordinates of a point in the grid CS
1608 void Grid::ComputeUVW(const gp_XYZ& P, double UVW[3])
1610 gp_XYZ p = P * _invB;
1611 p.Coord( UVW[0], UVW[1], UVW[2] );
1613 //================================================================================
1617 void Grid::ComputeNodes(SMESH_MesherHelper& helper)
1619 // state of each node of the grid relative to the geometry
1620 const size_t nbGridNodes = _coords[0].size() * _coords[1].size() * _coords[2].size();
1621 const TGeomID undefID = 1e+9;
1622 vector< TGeomID > shapeIDVec( nbGridNodes, undefID );
1623 _nodes.resize( nbGridNodes, 0 );
1624 _gridIntP.resize( nbGridNodes, NULL );
1626 SMESHDS_Mesh* mesh = helper.GetMeshDS();
1628 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1630 LineIndexer li = GetLineIndexer( iDir );
1632 // find out a shift of node index while walking along a GridLine in this direction
1633 li.SetIndexOnLine( 0 );
1634 size_t nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1635 li.SetIndexOnLine( 1 );
1636 const size_t nShift = NodeIndex( li.I(), li.J(), li.K() ) - nIndex0;
1638 const vector<double> & coords = _coords[ iDir ];
1639 for ( ; li.More(); ++li ) // loop on lines in iDir
1641 li.SetIndexOnLine( 0 );
1642 nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
1644 GridLine& line = _lines[ iDir ][ li.LineIndex() ];
1645 const gp_XYZ lineLoc = line._line.Location().XYZ();
1646 const gp_XYZ lineDir = line._line.Direction().XYZ();
1648 line.RemoveExcessIntPoints( _tol );
1649 multiset< F_IntersectPoint >& intPnts = line._intPoints;
1650 multiset< F_IntersectPoint >::iterator ip = intPnts.begin();
1652 // Create mesh nodes at intersections with geometry
1653 // and set OUT state of nodes between intersections
1655 TGeomID solidID = 0;
1656 const double* nodeCoord = & coords[0];
1657 const double* coord0 = nodeCoord;
1658 const double* coordEnd = coord0 + coords.size();
1659 double nodeParam = 0;
1660 for ( ; ip != intPnts.end(); ++ip )
1662 solidID = line.GetSolidIDBefore( ip, solidID, _geometry );
1664 // set OUT state or just skip IN nodes before ip
1665 if ( nodeParam < ip->_paramOnLine - _tol )
1667 while ( nodeParam < ip->_paramOnLine - _tol )
1669 TGeomID & nodeShapeID = shapeIDVec[ nIndex0 + nShift * ( nodeCoord-coord0 ) ];
1670 nodeShapeID = Min( solidID, nodeShapeID );
1671 if ( ++nodeCoord < coordEnd )
1672 nodeParam = *nodeCoord - *coord0;
1676 if ( nodeCoord == coordEnd ) break;
1678 // create a mesh node on a GridLine at ip if it does not coincide with a grid node
1679 if ( nodeParam > ip->_paramOnLine + _tol )
1681 gp_XYZ xyz = lineLoc + ip->_paramOnLine * lineDir;
1682 ip->_node = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1683 ip->_indexOnLine = nodeCoord-coord0-1;
1684 SetOnShape( ip->_node, *ip );
1686 // create a mesh node at ip coincident with a grid node
1689 int nodeIndex = nIndex0 + nShift * ( nodeCoord-coord0 );
1690 if ( !_nodes[ nodeIndex ] )
1692 gp_XYZ xyz = lineLoc + nodeParam * lineDir;
1693 _nodes [ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1694 //_gridIntP[ nodeIndex ] = & * ip;
1695 //SetOnShape( _nodes[ nodeIndex ], *ip );
1697 if ( _gridIntP[ nodeIndex ] )
1698 _gridIntP[ nodeIndex ]->Add( ip->_faceIDs );
1700 _gridIntP[ nodeIndex ] = & * ip;
1701 // ip->_node = _nodes[ nodeIndex ]; -- to differ from ip on links
1702 ip->_indexOnLine = nodeCoord-coord0;
1703 if ( ++nodeCoord < coordEnd )
1704 nodeParam = *nodeCoord - *coord0;
1707 // set OUT state to nodes after the last ip
1708 for ( ; nodeCoord < coordEnd; ++nodeCoord )
1709 shapeIDVec[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = 0;
1713 // Create mesh nodes at !OUT nodes of the grid
1715 for ( size_t z = 0; z < _coords[2].size(); ++z )
1716 for ( size_t y = 0; y < _coords[1].size(); ++y )
1717 for ( size_t x = 0; x < _coords[0].size(); ++x )
1719 size_t nodeIndex = NodeIndex( x, y, z );
1720 if ( !_nodes[ nodeIndex ] &&
1721 0 < shapeIDVec[ nodeIndex ] && shapeIDVec[ nodeIndex ] < undefID )
1723 gp_XYZ xyz = ( _coords[0][x] * _axes[0] +
1724 _coords[1][y] * _axes[1] +
1725 _coords[2][z] * _axes[2] );
1726 _nodes[ nodeIndex ] = mesh->AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1727 mesh->SetNodeInVolume( _nodes[ nodeIndex ], shapeIDVec[ nodeIndex ]);
1729 else if ( _nodes[ nodeIndex ] && _gridIntP[ nodeIndex ] /*&&
1730 !_nodes[ nodeIndex]->GetShapeID()*/ )
1732 SetOnShape( _nodes[ nodeIndex ], *_gridIntP[ nodeIndex ]);
1737 // check validity of transitions
1738 const char* trName[] = { "TANGENT", "IN", "OUT", "APEX" };
1739 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1741 LineIndexer li = GetLineIndexer( iDir );
1742 for ( ; li.More(); ++li )
1744 multiset< F_IntersectPoint >& intPnts = _lines[ iDir ][ li.LineIndex() ]._intPoints;
1745 if ( intPnts.empty() ) continue;
1746 if ( intPnts.size() == 1 )
1748 if ( intPnts.begin()->_transition != Trans_TANGENT &&
1749 intPnts.begin()->_transition != Trans_APEX )
1750 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1751 SMESH_Comment("Wrong SOLE transition of GridLine (")
1752 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1753 << ") along " << li._nameConst
1754 << ": " << trName[ intPnts.begin()->_transition] );
1758 if ( intPnts.begin()->_transition == Trans_OUT )
1759 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1760 SMESH_Comment("Wrong START transition of GridLine (")
1761 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1762 << ") along " << li._nameConst
1763 << ": " << trName[ intPnts.begin()->_transition ]);
1764 if ( intPnts.rbegin()->_transition == Trans_IN )
1765 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1766 SMESH_Comment("Wrong END transition of GridLine (")
1767 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1768 << ") along " << li._nameConst
1769 << ": " << trName[ intPnts.rbegin()->_transition ]);
1776 //=============================================================================
1778 * Intersects TopoDS_Face with all GridLine's
1780 void FaceGridIntersector::Intersect()
1782 FaceLineIntersector intersector;
1783 intersector._surfaceInt = GetCurveFaceIntersector();
1784 intersector._tol = _grid->_tol;
1785 intersector._transOut = _face.Orientation() == TopAbs_REVERSED ? Trans_IN : Trans_OUT;
1786 intersector._transIn = _face.Orientation() == TopAbs_REVERSED ? Trans_OUT : Trans_IN;
1788 typedef void (FaceLineIntersector::* PIntFun )(const GridLine& gridLine);
1789 PIntFun interFunction;
1791 bool isDirect = true;
1792 BRepAdaptor_Surface surf( _face );
1793 switch ( surf.GetType() ) {
1795 intersector._plane = surf.Plane();
1796 interFunction = &FaceLineIntersector::IntersectWithPlane;
1797 isDirect = intersector._plane.Direct();
1799 case GeomAbs_Cylinder:
1800 intersector._cylinder = surf.Cylinder();
1801 interFunction = &FaceLineIntersector::IntersectWithCylinder;
1802 isDirect = intersector._cylinder.Direct();
1805 intersector._cone = surf.Cone();
1806 interFunction = &FaceLineIntersector::IntersectWithCone;
1807 //isDirect = intersector._cone.Direct();
1809 case GeomAbs_Sphere:
1810 intersector._sphere = surf.Sphere();
1811 interFunction = &FaceLineIntersector::IntersectWithSphere;
1812 isDirect = intersector._sphere.Direct();
1815 intersector._torus = surf.Torus();
1816 interFunction = &FaceLineIntersector::IntersectWithTorus;
1817 //isDirect = intersector._torus.Direct();
1820 interFunction = &FaceLineIntersector::IntersectWithSurface;
1823 std::swap( intersector._transOut, intersector._transIn );
1825 _intersections.clear();
1826 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1828 if ( surf.GetType() == GeomAbs_Plane )
1830 // check if all lines in this direction are parallel to a plane
1831 if ( intersector._plane.Axis().IsNormal( _grid->_lines[iDir][0]._line.Position(),
1832 Precision::Angular()))
1834 // find out a transition, that is the same for all lines of a direction
1835 gp_Dir plnNorm = intersector._plane.Axis().Direction();
1836 gp_Dir lineDir = _grid->_lines[iDir][0]._line.Direction();
1837 intersector._transition =
1838 ( plnNorm * lineDir < 0 ) ? intersector._transIn : intersector._transOut;
1840 if ( surf.GetType() == GeomAbs_Cylinder )
1842 // check if all lines in this direction are parallel to a cylinder
1843 if ( intersector._cylinder.Axis().IsParallel( _grid->_lines[iDir][0]._line.Position(),
1844 Precision::Angular()))
1848 // intersect the grid lines with the face
1849 for ( size_t iL = 0; iL < _grid->_lines[iDir].size(); ++iL )
1851 GridLine& gridLine = _grid->_lines[iDir][iL];
1852 if ( _bndBox.IsOut( gridLine._line )) continue;
1854 intersector._intPoints.clear();
1855 (intersector.*interFunction)( gridLine ); // <- intersection with gridLine
1856 for ( size_t i = 0; i < intersector._intPoints.size(); ++i )
1857 _intersections.push_back( make_pair( &gridLine, intersector._intPoints[i] ));
1861 if ( _face.Orientation() == TopAbs_INTERNAL )
1863 for ( size_t i = 0; i < _intersections.size(); ++i )
1864 if ( _intersections[i].second._transition == Trans_IN ||
1865 _intersections[i].second._transition == Trans_OUT )
1867 _intersections[i].second._transition = Trans_INTERNAL;
1872 //================================================================================
1874 * Return true if (_u,_v) is on the face
1876 bool FaceLineIntersector::UVIsOnFace() const
1878 TopAbs_State state = _surfaceInt->ClassifyUVPoint(gp_Pnt2d( _u,_v ));
1879 return ( state == TopAbs_IN || state == TopAbs_ON );
1881 //================================================================================
1883 * Store an intersection if it is IN or ON the face
1885 void FaceLineIntersector::addIntPoint(const bool toClassify)
1887 if ( !toClassify || UVIsOnFace() )
1890 p._paramOnLine = _w;
1893 p._transition = _transition;
1894 _intPoints.push_back( p );
1897 //================================================================================
1899 * Intersect a line with a plane
1901 void FaceLineIntersector::IntersectWithPlane(const GridLine& gridLine)
1903 IntAna_IntConicQuad linPlane( gridLine._line, _plane, Precision::Angular());
1904 _w = linPlane.ParamOnConic(1);
1905 if ( isParamOnLineOK( gridLine._length ))
1907 ElSLib::Parameters(_plane, linPlane.Point(1) ,_u,_v);
1911 //================================================================================
1913 * Intersect a line with a cylinder
1915 void FaceLineIntersector::IntersectWithCylinder(const GridLine& gridLine)
1917 IntAna_IntConicQuad linCylinder( gridLine._line, _cylinder );
1918 if ( linCylinder.IsDone() && linCylinder.NbPoints() > 0 )
1920 _w = linCylinder.ParamOnConic(1);
1921 if ( linCylinder.NbPoints() == 1 )
1922 _transition = Trans_TANGENT;
1924 _transition = _w < linCylinder.ParamOnConic(2) ? _transIn : _transOut;
1925 if ( isParamOnLineOK( gridLine._length ))
1927 ElSLib::Parameters(_cylinder, linCylinder.Point(1) ,_u,_v);
1930 if ( linCylinder.NbPoints() > 1 )
1932 _w = linCylinder.ParamOnConic(2);
1933 if ( isParamOnLineOK( gridLine._length ))
1935 ElSLib::Parameters(_cylinder, linCylinder.Point(2) ,_u,_v);
1936 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
1942 //================================================================================
1944 * Intersect a line with a cone
1946 void FaceLineIntersector::IntersectWithCone (const GridLine& gridLine)
1948 IntAna_IntConicQuad linCone(gridLine._line,_cone);
1949 if ( !linCone.IsDone() ) return;
1951 gp_Vec du, dv, norm;
1952 for ( int i = 1; i <= linCone.NbPoints(); ++i )
1954 _w = linCone.ParamOnConic( i );
1955 if ( !isParamOnLineOK( gridLine._length )) continue;
1956 ElSLib::Parameters(_cone, linCone.Point(i) ,_u,_v);
1959 ElSLib::D1( _u, _v, _cone, P, du, dv );
1961 double normSize2 = norm.SquareMagnitude();
1962 if ( normSize2 > Precision::Angular() * Precision::Angular() )
1964 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
1965 cos /= sqrt( normSize2 );
1966 if ( cos < -Precision::Angular() )
1967 _transition = _transIn;
1968 else if ( cos > Precision::Angular() )
1969 _transition = _transOut;
1971 _transition = Trans_TANGENT;
1975 _transition = Trans_APEX;
1977 addIntPoint( /*toClassify=*/false);
1981 //================================================================================
1983 * Intersect a line with a sphere
1985 void FaceLineIntersector::IntersectWithSphere (const GridLine& gridLine)
1987 IntAna_IntConicQuad linSphere(gridLine._line,_sphere);
1988 if ( linSphere.IsDone() && linSphere.NbPoints() > 0 )
1990 _w = linSphere.ParamOnConic(1);
1991 if ( linSphere.NbPoints() == 1 )
1992 _transition = Trans_TANGENT;
1994 _transition = _w < linSphere.ParamOnConic(2) ? _transIn : _transOut;
1995 if ( isParamOnLineOK( gridLine._length ))
1997 ElSLib::Parameters(_sphere, linSphere.Point(1) ,_u,_v);
2000 if ( linSphere.NbPoints() > 1 )
2002 _w = linSphere.ParamOnConic(2);
2003 if ( isParamOnLineOK( gridLine._length ))
2005 ElSLib::Parameters(_sphere, linSphere.Point(2) ,_u,_v);
2006 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
2012 //================================================================================
2014 * Intersect a line with a torus
2016 void FaceLineIntersector::IntersectWithTorus (const GridLine& gridLine)
2018 IntAna_IntLinTorus linTorus(gridLine._line,_torus);
2019 if ( !linTorus.IsDone()) return;
2021 gp_Vec du, dv, norm;
2022 for ( int i = 1; i <= linTorus.NbPoints(); ++i )
2024 _w = linTorus.ParamOnLine( i );
2025 if ( !isParamOnLineOK( gridLine._length )) continue;
2026 linTorus.ParamOnTorus( i, _u,_v );
2029 ElSLib::D1( _u, _v, _torus, P, du, dv );
2031 double normSize = norm.Magnitude();
2032 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
2034 if ( cos < -Precision::Angular() )
2035 _transition = _transIn;
2036 else if ( cos > Precision::Angular() )
2037 _transition = _transOut;
2039 _transition = Trans_TANGENT;
2040 addIntPoint( /*toClassify=*/false);
2044 //================================================================================
2046 * Intersect a line with a non-analytical surface
2048 void FaceLineIntersector::IntersectWithSurface (const GridLine& gridLine)
2050 _surfaceInt->Perform( gridLine._line, 0.0, gridLine._length );
2051 if ( !_surfaceInt->IsDone() ) return;
2052 for ( int i = 1; i <= _surfaceInt->NbPnt(); ++i )
2054 _transition = Transition( _surfaceInt->Transition( i ) );
2055 _w = _surfaceInt->WParameter( i );
2056 addIntPoint(/*toClassify=*/false);
2059 //================================================================================
2061 * check if its face can be safely intersected in a thread
2063 bool FaceGridIntersector::IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const
2068 TopLoc_Location loc;
2069 Handle(Geom_Surface) surf = BRep_Tool::Surface( _face, loc );
2070 Handle(Geom_RectangularTrimmedSurface) ts =
2071 Handle(Geom_RectangularTrimmedSurface)::DownCast( surf );
2072 while( !ts.IsNull() ) {
2073 surf = ts->BasisSurface();
2074 ts = Handle(Geom_RectangularTrimmedSurface)::DownCast(surf);
2076 if ( surf->IsKind( STANDARD_TYPE(Geom_BSplineSurface )) ||
2077 surf->IsKind( STANDARD_TYPE(Geom_BezierSurface )))
2078 if ( !noSafeTShapes.insert( _face.TShape().get() ).second )
2082 TopExp_Explorer exp( _face, TopAbs_EDGE );
2083 for ( ; exp.More(); exp.Next() )
2085 bool edgeIsSafe = true;
2086 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
2089 Handle(Geom_Curve) c = BRep_Tool::Curve( e, loc, f, l);
2092 Handle(Geom_TrimmedCurve) tc = Handle(Geom_TrimmedCurve)::DownCast(c);
2093 while( !tc.IsNull() ) {
2094 c = tc->BasisCurve();
2095 tc = Handle(Geom_TrimmedCurve)::DownCast(c);
2097 if ( c->IsKind( STANDARD_TYPE(Geom_BSplineCurve )) ||
2098 c->IsKind( STANDARD_TYPE(Geom_BezierCurve )))
2105 Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( e, surf, loc, f, l);
2108 Handle(Geom2d_TrimmedCurve) tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
2109 while( !tc.IsNull() ) {
2110 c2 = tc->BasisCurve();
2111 tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
2113 if ( c2->IsKind( STANDARD_TYPE(Geom2d_BSplineCurve )) ||
2114 c2->IsKind( STANDARD_TYPE(Geom2d_BezierCurve )))
2118 if ( !edgeIsSafe && !noSafeTShapes.insert( e.TShape().get() ).second )
2123 //================================================================================
2125 * \brief Creates topology of the hexahedron
2127 Hexahedron::Hexahedron(Grid* grid)
2128 : _grid( grid ), _nbFaceIntNodes(0), _hasTooSmall( false )
2130 _polygons.reserve(100); // to avoid reallocation;
2132 //set nodes shift within grid->_nodes from the node 000
2133 size_t dx = _grid->NodeIndexDX();
2134 size_t dy = _grid->NodeIndexDY();
2135 size_t dz = _grid->NodeIndexDZ();
2137 size_t i100 = i000 + dx;
2138 size_t i010 = i000 + dy;
2139 size_t i110 = i010 + dx;
2140 size_t i001 = i000 + dz;
2141 size_t i101 = i100 + dz;
2142 size_t i011 = i010 + dz;
2143 size_t i111 = i110 + dz;
2144 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V000 )] = i000;
2145 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V100 )] = i100;
2146 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V010 )] = i010;
2147 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V110 )] = i110;
2148 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V001 )] = i001;
2149 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V101 )] = i101;
2150 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V011 )] = i011;
2151 grid->_nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V111 )] = i111;
2153 vector< int > idVec;
2154 // set nodes to links
2155 for ( int linkID = SMESH_Block::ID_Ex00; linkID <= SMESH_Block::ID_E11z; ++linkID )
2157 SMESH_Block::GetEdgeVertexIDs( linkID, idVec );
2158 _Link& link = _hexLinks[ SMESH_Block::ShapeIndex( linkID )];
2159 link._nodes[0] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[0] )];
2160 link._nodes[1] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[1] )];
2163 // set links to faces
2164 int interlace[4] = { 0, 3, 1, 2 }; // to walk by links around a face: { u0, 1v, u1, 0v }
2165 for ( int faceID = SMESH_Block::ID_Fxy0; faceID <= SMESH_Block::ID_F1yz; ++faceID )
2167 _Face& quad = _hexQuads[ SMESH_Block::ShapeIndex( faceID )];
2168 quad._name = (SMESH_Block::TShapeID) faceID;
2170 SMESH_Block::GetFaceEdgesIDs( faceID, idVec );
2171 bool revFace = ( faceID == SMESH_Block::ID_Fxy0 ||
2172 faceID == SMESH_Block::ID_Fx1z ||
2173 faceID == SMESH_Block::ID_F0yz );
2174 quad._links.resize(4);
2175 vector<_OrientedLink>::iterator frwLinkIt = quad._links.begin();
2176 vector<_OrientedLink>::reverse_iterator revLinkIt = quad._links.rbegin();
2177 for ( int i = 0; i < 4; ++i )
2179 bool revLink = revFace;
2180 if ( i > 1 ) // reverse links u1 and v0
2182 _OrientedLink& link = revFace ? *revLinkIt++ : *frwLinkIt++;
2183 link = _OrientedLink( & _hexLinks[ SMESH_Block::ShapeIndex( idVec[interlace[i]] )],
2188 //================================================================================
2190 * \brief Copy constructor
2192 Hexahedron::Hexahedron( const Hexahedron& other, size_t i, size_t j, size_t k, int cellID )
2193 :_grid( other._grid ), _nbFaceIntNodes(0), _i( i ), _j( j ), _k( k ), _hasTooSmall( false )
2195 _polygons.reserve(100); // to avoid reallocation;
2198 for ( int i = 0; i < 12; ++i )
2200 const _Link& srcLink = other._hexLinks[ i ];
2201 _Link& tgtLink = this->_hexLinks[ i ];
2202 tgtLink._nodes[0] = _hexNodes + ( srcLink._nodes[0] - other._hexNodes );
2203 tgtLink._nodes[1] = _hexNodes + ( srcLink._nodes[1] - other._hexNodes );
2206 for ( int i = 0; i < 6; ++i )
2208 const _Face& srcQuad = other._hexQuads[ i ];
2209 _Face& tgtQuad = this->_hexQuads[ i ];
2210 tgtQuad._name = srcQuad._name;
2211 tgtQuad._links.resize(4);
2212 for ( int j = 0; j < 4; ++j )
2214 const _OrientedLink& srcLink = srcQuad._links[ j ];
2215 _OrientedLink& tgtLink = tgtQuad._links[ j ];
2216 tgtLink._reverse = srcLink._reverse;
2217 tgtLink._link = _hexLinks + ( srcLink._link - other._hexLinks );
2223 (void)cellID; // unused in release mode
2227 //================================================================================
2229 * \brief Return IDs of SOLIDs interfering with this Hexahedron
2231 size_t Hexahedron::getSolids( TGeomID ids[] )
2233 if ( _grid->_geometry.IsOneSolid() )
2235 ids[0] = _grid->GetSolid()->ID();
2238 // count intersection points belonging to each SOLID
2240 id2NbPoints.reserve( 3 );
2242 _origNodeInd = _grid->NodeIndex( _i,_j,_k );
2243 for ( int iN = 0; iN < 8; ++iN )
2245 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
2246 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
2248 if ( _hexNodes[iN]._intPoint ) // intersection with a FACE
2250 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2252 const vector< TGeomID > & solidIDs =
2253 _grid->GetSolidIDs( _hexNodes[iN]._intPoint->_faceIDs[iF] );
2254 for ( size_t i = 0; i < solidIDs.size(); ++i )
2255 insertAndIncrement( solidIDs[i], id2NbPoints );
2258 else if ( _hexNodes[iN]._node ) // node inside a SOLID
2260 insertAndIncrement( _hexNodes[iN]._node->GetShapeID(), id2NbPoints );
2264 for ( int iL = 0; iL < 12; ++iL )
2266 const _Link& link = _hexLinks[ iL ];
2267 for ( size_t iP = 0; iP < link._fIntPoints.size(); ++iP )
2269 for ( size_t iF = 0; iF < link._fIntPoints[iP]->_faceIDs.size(); ++iF )
2271 const vector< TGeomID > & solidIDs =
2272 _grid->GetSolidIDs( link._fIntPoints[iP]->_faceIDs[iF] );
2273 for ( size_t i = 0; i < solidIDs.size(); ++i )
2274 insertAndIncrement( solidIDs[i], id2NbPoints );
2279 for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
2281 const vector< TGeomID > & solidIDs = _grid->GetSolidIDs( _eIntPoints[iP]->_shapeID );
2282 for ( size_t i = 0; i < solidIDs.size(); ++i )
2283 insertAndIncrement( solidIDs[i], id2NbPoints );
2286 size_t nbSolids = 0;
2287 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2288 if ( id2nb->second >= 3 )
2289 ids[ nbSolids++ ] = id2nb->first;
2294 //================================================================================
2296 * \brief Count cuts by INTERNAL FACEs and set _Node::_isInternalFlags
2298 bool Hexahedron::isCutByInternalFace( IsInternalFlag & maxFlag )
2301 id2NbPoints.reserve( 3 );
2303 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2304 for ( size_t iF = 0; iF < _intNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2306 if ( _grid->IsInternal( _intNodes[iN]._intPoint->_faceIDs[iF]))
2307 insertAndIncrement( _intNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2309 for ( size_t iN = 0; iN < 8; ++iN )
2310 if ( _hexNodes[iN]._intPoint )
2311 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2313 if ( _grid->IsInternal( _hexNodes[iN]._intPoint->_faceIDs[iF]))
2314 insertAndIncrement( _hexNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2317 maxFlag = IS_NOT_INTERNAL;
2318 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2320 TGeomID intFace = id2nb->first;
2321 IsInternalFlag intFlag = ( id2nb->second >= 3 ? IS_CUT_BY_INTERNAL_FACE : IS_INTERNAL );
2322 if ( intFlag > maxFlag )
2325 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2326 if ( _intNodes[iN].IsOnFace( intFace ))
2327 _intNodes[iN].SetInternal( intFlag );
2329 for ( size_t iN = 0; iN < 8; ++iN )
2330 if ( _hexNodes[iN].IsOnFace( intFace ))
2331 _hexNodes[iN].SetInternal( intFlag );
2337 //================================================================================
2339 * \brief Return any FACE interfering with this Hexahedron
2341 TGeomID Hexahedron::getAnyFace() const
2344 id2NbPoints.reserve( 3 );
2346 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2347 for ( size_t iF = 0; iF < _intNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2348 insertAndIncrement( _intNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2350 for ( size_t iN = 0; iN < 8; ++iN )
2351 if ( _hexNodes[iN]._intPoint )
2352 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
2353 insertAndIncrement( _hexNodes[iN]._intPoint->_faceIDs[iF], id2NbPoints );
2355 for ( unsigned int minNb = 3; minNb > 0; --minNb )
2356 for ( TID2Nb::iterator id2nb = id2NbPoints.begin(); id2nb != id2NbPoints.end(); ++id2nb )
2357 if ( id2nb->second >= minNb )
2358 return id2nb->first;
2363 //================================================================================
2365 * \brief Initializes IJK by Hexahedron index
2367 void Hexahedron::setIJK( size_t iCell )
2369 size_t iNbCell = _grid->_coords[0].size() - 1;
2370 size_t jNbCell = _grid->_coords[1].size() - 1;
2371 _i = iCell % iNbCell;
2372 _j = ( iCell % ( iNbCell * jNbCell )) / iNbCell;
2373 _k = iCell / iNbCell / jNbCell;
2376 //================================================================================
2378 * \brief Initializes its data by given grid cell (countered from zero)
2380 void Hexahedron::init( size_t iCell )
2386 //================================================================================
2388 * \brief Initializes its data by given grid cell nodes and intersections
2390 void Hexahedron::init( size_t i, size_t j, size_t k, const Solid* solid )
2392 _i = i; _j = j; _k = k;
2394 bool isCompute = solid;
2396 solid = _grid->GetSolid();
2398 // set nodes of grid to nodes of the hexahedron and
2399 // count nodes at hexahedron corners located IN and ON geometry
2400 _nbCornerNodes = _nbBndNodes = 0;
2401 _origNodeInd = _grid->NodeIndex( i,j,k );
2402 for ( int iN = 0; iN < 8; ++iN )
2404 _hexNodes[iN]._isInternalFlags = 0;
2406 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
2407 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
2409 if ( _hexNodes[iN]._node && !solid->Contains( _hexNodes[iN]._node->GetShapeID() ))
2410 _hexNodes[iN]._node = 0;
2411 if ( _hexNodes[iN]._intPoint && !solid->ContainsAny( _hexNodes[iN]._intPoint->_faceIDs ))
2412 _hexNodes[iN]._intPoint = 0;
2414 _nbCornerNodes += bool( _hexNodes[iN]._node );
2415 _nbBndNodes += bool( _hexNodes[iN]._intPoint );
2417 _sideLength[0] = _grid->_coords[0][i+1] - _grid->_coords[0][i];
2418 _sideLength[1] = _grid->_coords[1][j+1] - _grid->_coords[1][j];
2419 _sideLength[2] = _grid->_coords[2][k+1] - _grid->_coords[2][k];
2427 if ( _nbFaceIntNodes + _eIntPoints.size() > 0 &&
2428 _nbFaceIntNodes + _eIntPoints.size() + _nbCornerNodes > 3)
2430 _intNodes.reserve( 3 * _nbBndNodes + _nbFaceIntNodes + _eIntPoints.size() );
2432 // this method can be called in parallel, so use own helper
2433 SMESH_MesherHelper helper( *_grid->_helper->GetMesh() );
2435 // Create sub-links (_Link::_splits) by splitting links with _Link::_fIntPoints
2436 // ---------------------------------------------------------------
2438 for ( int iLink = 0; iLink < 12; ++iLink )
2440 _Link& link = _hexLinks[ iLink ];
2441 link._fIntNodes.clear();
2442 link._fIntNodes.reserve( link._fIntPoints.size() );
2443 for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
2444 if ( solid->ContainsAny( link._fIntPoints[i]->_faceIDs ))
2446 _intNodes.push_back( _Node( 0, link._fIntPoints[i] ));
2447 link._fIntNodes.push_back( & _intNodes.back() );
2450 link._splits.clear();
2451 split._nodes[ 0 ] = link._nodes[0];
2452 bool isOut = ( ! link._nodes[0]->Node() );
2453 bool checkTransition;
2454 for ( size_t i = 0; i < link._fIntNodes.size(); ++i )
2456 const bool isGridNode = ( ! link._fIntNodes[i]->Node() );
2457 if ( !isGridNode ) // intersection non-coincident with a grid node
2459 if ( split._nodes[ 0 ]->Node() && !isOut )
2461 split._nodes[ 1 ] = link._fIntNodes[i];
2462 link._splits.push_back( split );
2464 split._nodes[ 0 ] = link._fIntNodes[i];
2465 checkTransition = true;
2467 else // FACE intersection coincident with a grid node (at link ends)
2469 checkTransition = ( i == 0 && link._nodes[0]->Node() );
2471 if ( checkTransition )
2473 const vector< TGeomID >& faceIDs = link._fIntNodes[i]->_intPoint->_faceIDs;
2474 if ( _grid->IsInternal( faceIDs.back() ))
2476 else if ( faceIDs.size() > 1 || _eIntPoints.size() > 0 )
2477 isOut = isOutPoint( link, i, helper, solid );
2480 bool okTransi = _grid->IsCorrectTransition( faceIDs[0], solid );
2481 switch ( link._fIntNodes[i]->FaceIntPnt()->_transition ) {
2482 case Trans_OUT: isOut = okTransi; break;
2483 case Trans_IN : isOut = !okTransi; break;
2485 isOut = isOutPoint( link, i, helper, solid );
2490 if ( link._nodes[ 1 ]->Node() && split._nodes[ 0 ]->Node() && !isOut )
2492 split._nodes[ 1 ] = link._nodes[1];
2493 link._splits.push_back( split );
2497 // Create _Node's at intersections with EDGEs.
2498 // --------------------------------------------
2499 // 1) add this->_eIntPoints to _Face::_eIntNodes
2500 // 2) fill _intNodes and _vIntNodes
2502 const double tol2 = _grid->_tol * _grid->_tol;
2503 int facets[3], nbFacets, subEntity;
2505 for ( int iF = 0; iF < 6; ++iF )
2506 _hexQuads[ iF ]._eIntNodes.clear();
2508 for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
2510 if ( !solid->ContainsAny( _eIntPoints[iP]->_faceIDs ))
2512 nbFacets = getEntity( _eIntPoints[iP], facets, subEntity );
2513 _Node* equalNode = 0;
2514 switch( nbFacets ) {
2515 case 1: // in a _Face
2517 _Face& quad = _hexQuads[ facets[0] - SMESH_Block::ID_FirstF ];
2518 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2520 equalNode->Add( _eIntPoints[ iP ] );
2523 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2524 quad._eIntNodes.push_back( & _intNodes.back() );
2528 case 2: // on a _Link
2530 _Link& link = _hexLinks[ subEntity - SMESH_Block::ID_FirstE ];
2531 if ( link._splits.size() > 0 )
2533 equalNode = findEqualNode( link._fIntNodes, _eIntPoints[ iP ], tol2 );
2535 equalNode->Add( _eIntPoints[ iP ] );
2536 else if ( link._splits.size() == 1 &&
2537 link._splits[0]._nodes[0] &&
2538 link._splits[0]._nodes[1] )
2539 link._splits.clear(); // hex edge is divided by _eIntPoints[iP]
2544 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2545 bool newNodeUsed = false;
2546 for ( int iF = 0; iF < 2; ++iF )
2548 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
2549 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2551 equalNode->Add( _eIntPoints[ iP ] );
2554 quad._eIntNodes.push_back( & _intNodes.back() );
2559 _intNodes.pop_back();
2563 case 3: // at a corner
2565 _Node& node = _hexNodes[ subEntity - SMESH_Block::ID_FirstV ];
2568 if ( node._intPoint )
2569 node._intPoint->Add( _eIntPoints[ iP ]->_faceIDs, _eIntPoints[ iP ]->_node );
2573 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2574 for ( int iF = 0; iF < 3; ++iF )
2576 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
2577 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
2579 equalNode->Add( _eIntPoints[ iP ] );
2582 quad._eIntNodes.push_back( & _intNodes.back() );
2588 } // switch( nbFacets )
2590 if ( nbFacets == 0 ||
2591 _grid->ShapeType( _eIntPoints[ iP ]->_shapeID ) == TopAbs_VERTEX )
2593 equalNode = findEqualNode( _vIntNodes, _eIntPoints[ iP ], tol2 );
2595 equalNode->Add( _eIntPoints[ iP ] );
2597 else if ( nbFacets == 0 ) {
2598 if ( _intNodes.empty() || _intNodes.back().EdgeIntPnt() != _eIntPoints[ iP ])
2599 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
2600 _vIntNodes.push_back( & _intNodes.back() );
2603 } // loop on _eIntPoints
2606 else if (( 3 < _nbCornerNodes && _nbCornerNodes < 8 ) || // _nbFaceIntNodes == 0
2607 ( !_grid->_geometry.IsOneSolid() ))
2610 // create sub-links (_splits) of whole links
2611 for ( int iLink = 0; iLink < 12; ++iLink )
2613 _Link& link = _hexLinks[ iLink ];
2614 link._splits.clear();
2615 if ( link._nodes[ 0 ]->Node() && link._nodes[ 1 ]->Node() )
2617 split._nodes[ 0 ] = link._nodes[0];
2618 split._nodes[ 1 ] = link._nodes[1];
2619 link._splits.push_back( split );
2625 } // init( _i, _j, _k )
2627 //================================================================================
2629 * \brief Compute mesh volumes resulted from intersection of the Hexahedron
2631 void Hexahedron::computeElements( const Solid* solid, int solidIndex )
2635 solid = _grid->GetSolid();
2636 if ( !_grid->_geometry.IsOneSolid() )
2638 TGeomID solidIDs[20];
2639 size_t nbSolids = getSolids( solidIDs );
2642 for ( size_t i = 0; i < nbSolids; ++i )
2644 solid = _grid->GetSolid( solidIDs[i] );
2645 computeElements( solid, i );
2646 if ( !_volumeDefs._nodes.empty() && i < nbSolids - 1 )
2647 _volumeDefs.SetNext( new _volumeDef( _volumeDefs ));
2651 solid = _grid->GetSolid( solidIDs[0] );
2655 init( _i, _j, _k, solid ); // get nodes and intersections from grid nodes and split links
2657 int nbIntersections = _nbFaceIntNodes + _eIntPoints.size();
2658 if ( _nbCornerNodes + nbIntersections < 4 )
2661 if ( _nbBndNodes == _nbCornerNodes && nbIntersections == 0 && isInHole() )
2662 return; // cell is in a hole
2664 IsInternalFlag intFlag = IS_NOT_INTERNAL;
2665 if ( solid->HasInternalFaces() && this->isCutByInternalFace( intFlag ))
2667 for ( _SplitIterator it( _hexLinks ); it.More(); it.Next() )
2669 if ( compute( solid, intFlag ))
2670 _volumeDefs.SetNext( new _volumeDef( _volumeDefs ));
2675 if ( solidIndex >= 0 )
2676 intFlag = IS_CUT_BY_INTERNAL_FACE;
2678 compute( solid, intFlag );
2682 //================================================================================
2684 * \brief Compute mesh volumes resulted from intersection of the Hexahedron
2686 bool Hexahedron::compute( const Solid* solid, const IsInternalFlag intFlag )
2689 _polygons.reserve( 20 );
2691 for ( int iN = 0; iN < 8; ++iN )
2692 _hexNodes[iN]._usedInFace = 0;
2694 if ( intFlag & IS_CUT_BY_INTERNAL_FACE && !_grid->_toAddEdges ) // Issue #19913
2695 preventVolumesOverlapping();
2697 // Create polygons from quadrangles
2698 // --------------------------------
2700 vector< _OrientedLink > splits;
2701 vector<_Node*> chainNodes;
2702 _Face* coplanarPolyg;
2704 const bool hasEdgeIntersections = !_eIntPoints.empty();
2705 const bool toCheckSideDivision = isImplementEdges() || intFlag & IS_CUT_BY_INTERNAL_FACE;
2707 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
2709 _Face& quad = _hexQuads[ iF ] ;
2711 _polygons.resize( _polygons.size() + 1 );
2712 _Face* polygon = &_polygons.back();
2713 polygon->_polyLinks.reserve( 20 );
2714 polygon->_name = quad._name;
2717 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
2718 for ( int iS = 0; iS < quad._links[ iE ].NbResultLinks(); ++iS )
2719 splits.push_back( quad._links[ iE ].ResultLink( iS ));
2721 // add splits of links to a polygon and add _polyLinks to make
2722 // polygon's boundary closed
2724 int nbSplits = splits.size();
2725 if (( nbSplits == 1 ) &&
2726 ( quad._eIntNodes.empty() ||
2727 splits[0].FirstNode()->IsLinked( splits[0].LastNode()->_intPoint )))
2728 //( quad._eIntNodes.empty() || _nbCornerNodes + nbIntersections > 6 ))
2731 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2732 if ( quad._eIntNodes[ iP ]->IsUsedInFace( polygon ))
2733 quad._eIntNodes[ iP ]->_usedInFace = 0;
2735 size_t nbUsedEdgeNodes = 0;
2736 _Face* prevPolyg = 0; // polygon previously created from this quad
2738 while ( nbSplits > 0 )
2741 while ( !splits[ iS ] )
2744 if ( !polygon->_links.empty() )
2746 _polygons.resize( _polygons.size() + 1 );
2747 polygon = &_polygons.back();
2748 polygon->_polyLinks.reserve( 20 );
2749 polygon->_name = quad._name;
2751 polygon->_links.push_back( splits[ iS ] );
2752 splits[ iS++ ]._link = 0;
2755 _Node* nFirst = polygon->_links.back().FirstNode();
2756 _Node *n1,*n2 = polygon->_links.back().LastNode();
2757 for ( ; nFirst != n2 && iS < splits.size(); ++iS )
2759 _OrientedLink& split = splits[ iS ];
2760 if ( !split ) continue;
2762 n1 = split.FirstNode();
2765 (( n1->_intPoint->_faceIDs.size() > 1 && toCheckSideDivision ) ||
2766 ( n1->_isInternalFlags )))
2768 // n1 is at intersection with EDGE
2769 if ( findChainOnEdge( splits, polygon->_links.back(), split, iS, quad, chainNodes ))
2771 for ( size_t i = 1; i < chainNodes.size(); ++i )
2772 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
2773 if ( chainNodes.back() != n1 ) // not a partial cut by INTERNAL FACE
2775 prevPolyg = polygon;
2776 n2 = chainNodes.back();
2781 else if ( n1 != n2 )
2783 // try to connect to intersections with EDGEs
2784 if ( quad._eIntNodes.size() > nbUsedEdgeNodes &&
2785 findChain( n2, n1, quad, chainNodes ))
2787 for ( size_t i = 1; i < chainNodes.size(); ++i )
2789 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i] );
2790 nbUsedEdgeNodes += ( chainNodes[i]->IsUsedInFace( polygon ));
2792 if ( chainNodes.back() != n1 )
2794 n2 = chainNodes.back();
2799 // try to connect to a split ending on the same FACE
2802 _OrientedLink foundSplit;
2803 for ( size_t i = iS; i < splits.size() && !foundSplit; ++i )
2804 if (( foundSplit = splits[ i ]) &&
2805 ( n2->IsLinked( foundSplit.FirstNode()->_intPoint )))
2811 foundSplit._link = 0;
2815 if ( n2 != foundSplit.FirstNode() )
2817 polygon->AddPolyLink( n2, foundSplit.FirstNode() );
2818 n2 = foundSplit.FirstNode();
2824 if ( n2->IsLinked( nFirst->_intPoint ))
2826 polygon->AddPolyLink( n2, n1, prevPolyg );
2829 } // if ( n1 != n2 )
2831 polygon->_links.push_back( split );
2834 n2 = polygon->_links.back().LastNode();
2838 if ( nFirst != n2 ) // close a polygon
2840 if ( !findChain( n2, nFirst, quad, chainNodes ))
2842 if ( !closePolygon( polygon, chainNodes ))
2843 if ( !isImplementEdges() )
2844 chainNodes.push_back( nFirst );
2846 for ( size_t i = 1; i < chainNodes.size(); ++i )
2848 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
2849 nbUsedEdgeNodes += bool( chainNodes[i]->IsUsedInFace( polygon ));
2853 if ( polygon->_links.size() < 3 && nbSplits > 0 )
2855 polygon->_polyLinks.clear();
2856 polygon->_links.clear();
2858 } // while ( nbSplits > 0 )
2860 if ( polygon->_links.size() < 3 )
2862 _polygons.pop_back();
2864 } // loop on 6 hexahedron sides
2866 // Create polygons closing holes in a polyhedron
2867 // ----------------------------------------------
2869 // clear _usedInFace
2870 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
2871 _intNodes[ iN ]._usedInFace = 0;
2873 // add polygons to their links and mark used nodes
2874 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
2876 _Face& polygon = _polygons[ iP ];
2877 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
2879 polygon._links[ iL ].AddFace( &polygon );
2880 polygon._links[ iL ].FirstNode()->_usedInFace = &polygon;
2884 vector< _OrientedLink* > freeLinks;
2885 freeLinks.reserve(20);
2886 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
2888 _Face& polygon = _polygons[ iP ];
2889 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
2890 if ( polygon._links[ iL ].NbFaces() < 2 )
2891 freeLinks.push_back( & polygon._links[ iL ]);
2893 int nbFreeLinks = freeLinks.size();
2894 if ( nbFreeLinks == 1 ) return false;
2896 // put not used intersection nodes to _vIntNodes
2897 int nbVertexNodes = 0; // nb not used vertex nodes
2899 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
2900 nbVertexNodes += ( !_vIntNodes[ iN ]->IsUsedInFace() );
2902 const double tol = 1e-3 * Min( Min( _sideLength[0], _sideLength[1] ), _sideLength[0] );
2903 for ( size_t iN = _nbFaceIntNodes; iN < _intNodes.size(); ++iN )
2905 if ( _intNodes[ iN ].IsUsedInFace() ) continue;
2906 if ( dynamic_cast< const F_IntersectPoint* >( _intNodes[ iN ]._intPoint )) continue;
2908 findEqualNode( _vIntNodes, _intNodes[ iN ].EdgeIntPnt(), tol*tol );
2911 _vIntNodes.push_back( &_intNodes[ iN ]);
2917 set<TGeomID> usedFaceIDs;
2918 vector< TGeomID > faces;
2919 TGeomID curFace = 0;
2920 const size_t nbQuadPolygons = _polygons.size();
2921 E_IntersectPoint ipTmp;
2923 // create polygons by making closed chains of free links
2924 size_t iPolygon = _polygons.size();
2925 while ( nbFreeLinks > 0 )
2927 if ( iPolygon == _polygons.size() )
2929 _polygons.resize( _polygons.size() + 1 );
2930 _polygons[ iPolygon ]._polyLinks.reserve( 20 );
2931 _polygons[ iPolygon ]._links.reserve( 20 );
2933 _Face& polygon = _polygons[ iPolygon ];
2935 _OrientedLink* curLink = 0;
2937 if (( !hasEdgeIntersections ) ||
2938 ( nbFreeLinks < 4 && nbVertexNodes == 0 ))
2940 // get a remaining link to start from
2941 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2942 if (( curLink = freeLinks[ iL ] ))
2943 freeLinks[ iL ] = 0;
2944 polygon._links.push_back( *curLink );
2948 // find all links connected to curLink
2949 curNode = curLink->FirstNode();
2951 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2952 if ( freeLinks[ iL ] && freeLinks[ iL ]->LastNode() == curNode )
2954 curLink = freeLinks[ iL ];
2955 freeLinks[ iL ] = 0;
2957 polygon._links.push_back( *curLink );
2959 } while ( curLink );
2961 else // there are intersections with EDGEs
2963 // get a remaining link to start from, one lying on minimal nb of FACEs
2965 typedef pair< TGeomID, int > TFaceOfLink;
2966 TFaceOfLink faceOfLink( -1, -1 );
2967 TFaceOfLink facesOfLink[3] = { faceOfLink, faceOfLink, faceOfLink };
2968 for ( size_t iL = 0; iL < freeLinks.size(); ++iL )
2969 if ( freeLinks[ iL ] )
2971 faces = freeLinks[ iL ]->GetNotUsedFace( usedFaceIDs );
2972 if ( faces.size() == 1 )
2974 faceOfLink = TFaceOfLink( faces[0], iL );
2975 if ( !freeLinks[ iL ]->HasEdgeNodes() )
2977 facesOfLink[0] = faceOfLink;
2979 else if ( facesOfLink[0].first < 0 )
2981 faceOfLink = TFaceOfLink(( faces.empty() ? -1 : faces[0]), iL );
2982 facesOfLink[ 1 + faces.empty() ] = faceOfLink;
2985 for ( int i = 0; faceOfLink.first < 0 && i < 3; ++i )
2986 faceOfLink = facesOfLink[i];
2988 if ( faceOfLink.first < 0 ) // all faces used
2990 for ( size_t iL = 0; iL < freeLinks.size() && faceOfLink.first < 1; ++iL )
2991 if (( curLink = freeLinks[ iL ]))
2994 curLink->FirstNode()->IsLinked( curLink->LastNode()->_intPoint );
2995 faceOfLink.second = iL;
2997 usedFaceIDs.clear();
2999 curFace = faceOfLink.first;
3000 curLink = freeLinks[ faceOfLink.second ];
3001 freeLinks[ faceOfLink.second ] = 0;
3003 usedFaceIDs.insert( curFace );
3004 polygon._links.push_back( *curLink );
3007 // find all links lying on a curFace
3010 // go forward from curLink
3011 curNode = curLink->LastNode();
3013 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3014 if ( freeLinks[ iL ] &&
3015 freeLinks[ iL ]->FirstNode() == curNode &&
3016 freeLinks[ iL ]->LastNode()->IsOnFace( curFace ))
3018 curLink = freeLinks[ iL ];
3019 freeLinks[ iL ] = 0;
3020 polygon._links.push_back( *curLink );
3023 } while ( curLink );
3025 std::reverse( polygon._links.begin(), polygon._links.end() );
3027 curLink = & polygon._links.back();
3030 // go backward from curLink
3031 curNode = curLink->FirstNode();
3033 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
3034 if ( freeLinks[ iL ] &&
3035 freeLinks[ iL ]->LastNode() == curNode &&
3036 freeLinks[ iL ]->FirstNode()->IsOnFace( curFace ))
3038 curLink = freeLinks[ iL ];
3039 freeLinks[ iL ] = 0;
3040 polygon._links.push_back( *curLink );
3043 } while ( curLink );
3045 curNode = polygon._links.back().FirstNode();
3047 if ( polygon._links[0].LastNode() != curNode )
3049 if ( nbVertexNodes > 0 )
3051 // add links with _vIntNodes if not already used
3053 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
3054 if ( !_vIntNodes[ iN ]->IsUsedInFace() &&
3055 _vIntNodes[ iN ]->IsOnFace( curFace ))
3057 _vIntNodes[ iN ]->_usedInFace = &polygon;
3058 chainNodes.push_back( _vIntNodes[ iN ] );
3060 if ( chainNodes.size() > 1 &&
3061 curFace != _grid->PseudoIntExtFaceID() ) /////// TODO
3063 sortVertexNodes( chainNodes, curNode, curFace );
3065 for ( size_t i = 0; i < chainNodes.size(); ++i )
3067 polygon.AddPolyLink( chainNodes[ i ], curNode );
3068 curNode = chainNodes[ i ];
3069 freeLinks.push_back( &polygon._links.back() );
3072 nbVertexNodes -= chainNodes.size();
3074 // if ( polygon._links.size() > 1 )
3076 polygon.AddPolyLink( polygon._links[0].LastNode(), curNode );
3077 freeLinks.push_back( &polygon._links.back() );
3081 } // if there are intersections with EDGEs
3083 if ( polygon._links.size() < 2 ||
3084 polygon._links[0].LastNode() != polygon._links.back().FirstNode() )
3085 return false; // closed polygon not found -> invalid polyhedron
3087 if ( polygon._links.size() == 2 )
3089 if ( freeLinks.back() == &polygon._links.back() )
3091 freeLinks.pop_back();
3094 if ( polygon._links.front().NbFaces() > 0 )
3095 polygon._links.back().AddFace( polygon._links.front()._link->_faces[0] );
3096 if ( polygon._links.back().NbFaces() > 0 )
3097 polygon._links.front().AddFace( polygon._links.back()._link->_faces[0] );
3099 if ( iPolygon == _polygons.size()-1 )
3100 _polygons.pop_back();
3102 else // polygon._links.size() >= 2
3104 // add polygon to its links
3105 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3107 polygon._links[ iL ].AddFace( &polygon );
3108 polygon._links[ iL ].Reverse();
3110 if ( /*hasEdgeIntersections &&*/ iPolygon == _polygons.size() - 1 )
3112 // check that a polygon does not lie on a hexa side
3114 for ( size_t iL = 0; iL < polygon._links.size() && !coplanarPolyg; ++iL )
3116 if ( polygon._links[ iL ].NbFaces() < 2 )
3117 continue; // it's a just added free link
3118 // look for a polygon made on a hexa side and sharing
3119 // two or more haxa links
3121 coplanarPolyg = polygon._links[ iL ]._link->_faces[0];
3122 for ( iL2 = iL + 1; iL2 < polygon._links.size(); ++iL2 )
3123 if ( polygon._links[ iL2 ]._link->_faces[0] == coplanarPolyg &&
3124 !coplanarPolyg->IsPolyLink( polygon._links[ iL ]) &&
3125 !coplanarPolyg->IsPolyLink( polygon._links[ iL2 ]) &&
3126 coplanarPolyg < & _polygons[ nbQuadPolygons ])
3128 if ( iL2 == polygon._links.size() )
3131 if ( coplanarPolyg ) // coplanar polygon found
3133 freeLinks.resize( freeLinks.size() - polygon._polyLinks.size() );
3134 nbFreeLinks -= polygon._polyLinks.size();
3136 // an E_IntersectPoint used to mark nodes of coplanarPolyg
3137 // as lying on curFace while they are not at intersection with geometry
3138 ipTmp._faceIDs.resize(1);
3139 ipTmp._faceIDs[0] = curFace;
3141 // fill freeLinks with links not shared by coplanarPolyg and polygon
3142 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3143 if ( polygon._links[ iL ]._link->_faces[1] &&
3144 polygon._links[ iL ]._link->_faces[0] != coplanarPolyg )
3146 _Face* p = polygon._links[ iL ]._link->_faces[0];
3147 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
3148 if ( p->_links[ iL2 ]._link == polygon._links[ iL ]._link )
3150 freeLinks.push_back( & p->_links[ iL2 ] );
3152 freeLinks.back()->RemoveFace( &polygon );
3156 for ( size_t iL = 0; iL < coplanarPolyg->_links.size(); ++iL )
3157 if ( coplanarPolyg->_links[ iL ]._link->_faces[1] &&
3158 coplanarPolyg->_links[ iL ]._link->_faces[1] != &polygon )
3160 _Face* p = coplanarPolyg->_links[ iL ]._link->_faces[0];
3161 if ( p == coplanarPolyg )
3162 p = coplanarPolyg->_links[ iL ]._link->_faces[1];
3163 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
3164 if ( p->_links[ iL2 ]._link == coplanarPolyg->_links[ iL ]._link )
3166 // set links of coplanarPolyg in place of used freeLinks
3167 // to re-create coplanarPolyg next
3169 for ( ; iL3 < freeLinks.size() && freeLinks[ iL3 ]; ++iL3 );
3170 if ( iL3 < freeLinks.size() )
3171 freeLinks[ iL3 ] = ( & p->_links[ iL2 ] );
3173 freeLinks.push_back( & p->_links[ iL2 ] );
3175 freeLinks[ iL3 ]->RemoveFace( coplanarPolyg );
3176 // mark nodes of coplanarPolyg as lying on curFace
3177 for ( int iN = 0; iN < 2; ++iN )
3179 _Node* n = freeLinks[ iL3 ]->_link->_nodes[ iN ];
3180 if ( n->_intPoint ) n->_intPoint->Add( ipTmp._faceIDs );
3181 else n->_intPoint = &ipTmp;
3186 // set coplanarPolyg to be re-created next
3187 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3188 if ( coplanarPolyg == & _polygons[ iP ] )
3191 _polygons[ iPolygon ]._links.clear();
3192 _polygons[ iPolygon ]._polyLinks.clear();
3195 _polygons.pop_back();
3196 usedFaceIDs.erase( curFace );
3198 } // if ( coplanarPolyg )
3199 } // if ( hasEdgeIntersections ) - search for coplanarPolyg
3201 iPolygon = _polygons.size();
3203 } // end of case ( polygon._links.size() > 2 )
3204 } // while ( nbFreeLinks > 0 )
3206 // check volume size
3207 _hasTooSmall = ! checkPolyhedronSize( intFlag & IS_CUT_BY_INTERNAL_FACE );
3209 for ( size_t i = 0; i < 8; ++i )
3210 if ( _hexNodes[ i ]._intPoint == &ipTmp )
3211 _hexNodes[ i ]._intPoint = 0;
3214 return false; // too small volume
3217 // Try to find out names of no-name polygons (issue # 19887)
3218 if ( _grid->IsToRemoveExcessEntities() && _polygons.back()._name == SMESH_Block::ID_NONE )
3221 0.5 * ( _grid->_coords[0][_i] + _grid->_coords[0][_i+1] ) * _grid->_axes[0] +
3222 0.5 * ( _grid->_coords[1][_j] + _grid->_coords[1][_j+1] ) * _grid->_axes[1] +
3223 0.5 * ( _grid->_coords[2][_k] + _grid->_coords[2][_k+1] ) * _grid->_axes[2];
3224 for ( size_t i = _polygons.size() - 1; _polygons[i]._name == SMESH_Block::ID_NONE; --i )
3226 _Face& face = _polygons[ i ];
3229 for ( size_t iL = 0; iL < face._links.size(); ++iL )
3231 _Node* n = face._links[ iL ].FirstNode();
3232 gp_XYZ p = SMESH_NodeXYZ( n->Node() );
3233 _grid->ComputeUVW( p, uvw.ChangeCoord().ChangeData() );
3236 gp_Pnt pMin = bb.CornerMin();
3237 if ( bb.IsXThin( _grid->_tol ))
3238 face._name = pMin.X() < uvwCenter.X() ? SMESH_Block::ID_F0yz : SMESH_Block::ID_F1yz;
3239 else if ( bb.IsYThin( _grid->_tol ))
3240 face._name = pMin.Y() < uvwCenter.Y() ? SMESH_Block::ID_Fx0z : SMESH_Block::ID_Fx1z;
3241 else if ( bb.IsZThin( _grid->_tol ))
3242 face._name = pMin.Z() < uvwCenter.Z() ? SMESH_Block::ID_Fxy0 : SMESH_Block::ID_Fxy1;
3246 _volumeDefs._nodes.clear();
3247 _volumeDefs._quantities.clear();
3248 _volumeDefs._names.clear();
3250 // create a classic cell if possible
3253 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
3254 nbPolygons += (_polygons[ iF ]._links.size() > 0 );
3256 //const int nbNodes = _nbCornerNodes + nbIntersections;
3258 for ( size_t i = 0; i < 8; ++i )
3259 nbNodes += _hexNodes[ i ].IsUsedInFace();
3260 for ( size_t i = 0; i < _intNodes.size(); ++i )
3261 nbNodes += _intNodes[ i ].IsUsedInFace();
3263 bool isClassicElem = false;
3264 if ( nbNodes == 8 && nbPolygons == 6 ) isClassicElem = addHexa();
3265 else if ( nbNodes == 4 && nbPolygons == 4 ) isClassicElem = addTetra();
3266 else if ( nbNodes == 6 && nbPolygons == 5 ) isClassicElem = addPenta();
3267 else if ( nbNodes == 5 && nbPolygons == 5 ) isClassicElem = addPyra ();
3268 if ( !isClassicElem )
3270 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
3272 const size_t nbLinks = _polygons[ iF ]._links.size();
3273 if ( nbLinks == 0 ) continue;
3274 _volumeDefs._quantities.push_back( nbLinks );
3275 _volumeDefs._names.push_back( _polygons[ iF ]._name );
3276 for ( size_t iL = 0; iL < nbLinks; ++iL )
3277 _volumeDefs._nodes.push_back( _polygons[ iF ]._links[ iL ].FirstNode() );
3280 _volumeDefs._solidID = solid->ID();
3282 return !_volumeDefs._nodes.empty();
3284 //================================================================================
3286 * \brief Create elements in the mesh
3288 int Hexahedron::MakeElements(SMESH_MesherHelper& helper,
3289 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
3291 SMESHDS_Mesh* mesh = helper.GetMeshDS();
3293 CellsAroundLink c( _grid, 0 );
3294 const size_t nbGridCells = c._nbCells[0] * c._nbCells[1] * c._nbCells[2];
3295 vector< Hexahedron* > allHexa( nbGridCells, 0 );
3298 // set intersection nodes from GridLine's to links of allHexa
3299 int i,j,k, cellIndex, iLink;
3300 for ( int iDir = 0; iDir < 3; ++iDir )
3302 // loop on GridLine's parallel to iDir
3303 LineIndexer lineInd = _grid->GetLineIndexer( iDir );
3304 CellsAroundLink fourCells( _grid, iDir );
3305 for ( ; lineInd.More(); ++lineInd )
3307 GridLine& line = _grid->_lines[ iDir ][ lineInd.LineIndex() ];
3308 multiset< F_IntersectPoint >::const_iterator ip = line._intPoints.begin();
3309 for ( ; ip != line._intPoints.end(); ++ip )
3311 // if ( !ip->_node ) continue; // intersection at a grid node
3312 lineInd.SetIndexOnLine( ip->_indexOnLine );
3313 fourCells.Init( lineInd.I(), lineInd.J(), lineInd.K() );
3314 for ( int iL = 0; iL < 4; ++iL ) // loop on 4 cells sharing a link
3316 if ( !fourCells.GetCell( iL, i,j,k, cellIndex, iLink ))
3318 Hexahedron *& hex = allHexa[ cellIndex ];
3321 hex = new Hexahedron( *this, i, j, k, cellIndex );
3324 hex->_hexLinks[iLink]._fIntPoints.push_back( &(*ip) );
3325 hex->_nbFaceIntNodes += bool( ip->_node );
3331 // implement geom edges into the mesh
3332 addEdges( helper, allHexa, edge2faceIDsMap );
3334 // add not split hexahedra to the mesh
3336 TGeomID solidIDs[20];
3337 vector< Hexahedron* > intHexa; intHexa.reserve( nbIntHex );
3338 vector< const SMDS_MeshElement* > boundaryVolumes; boundaryVolumes.reserve( nbIntHex * 1.1 );
3339 for ( size_t i = 0; i < allHexa.size(); ++i )
3341 // initialize this by not cut allHexa[ i ]
3342 Hexahedron * & hex = allHexa[ i ];
3343 if ( hex ) // split hexahedron
3345 intHexa.push_back( hex );
3346 if ( hex->_nbFaceIntNodes > 0 ||
3347 hex->_eIntPoints.size() > 0 ||
3348 hex->getSolids( solidIDs ) > 1 )
3349 continue; // treat intersected hex later in parallel
3350 this->init( hex->_i, hex->_j, hex->_k );
3354 this->init( i ); // == init(i,j,k)
3356 if (( _nbCornerNodes == 8 ) &&
3357 ( _nbBndNodes < _nbCornerNodes || !isInHole() ))
3359 // order of _hexNodes is defined by enum SMESH_Block::TShapeID
3360 SMDS_MeshElement* el =
3361 mesh->AddVolume( _hexNodes[0].Node(), _hexNodes[2].Node(),
3362 _hexNodes[3].Node(), _hexNodes[1].Node(),
3363 _hexNodes[4].Node(), _hexNodes[6].Node(),
3364 _hexNodes[7].Node(), _hexNodes[5].Node() );
3365 TGeomID solidID = 0;
3366 if ( _nbBndNodes < _nbCornerNodes )
3368 for ( int iN = 0; iN < 8 && !solidID; ++iN )
3369 if ( !_hexNodes[iN]._intPoint ) // no intersection
3370 solidID = _hexNodes[iN].Node()->GetShapeID();
3374 getSolids( solidIDs );
3375 solidID = solidIDs[0];
3377 mesh->SetMeshElementOnShape( el, solidID );
3381 if ( _grid->_toCreateFaces && _nbBndNodes >= 3 )
3383 boundaryVolumes.push_back( el );
3384 el->setIsMarked( true );
3387 else if ( _nbCornerNodes > 3 && !hex )
3389 // all intersection of hex with geometry are at grid nodes
3390 hex = new Hexahedron( *this, _i, _j, _k, i );
3391 intHexa.push_back( hex );
3395 // compute definitions of volumes resulted from hexadron intersection
3397 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, intHexa.size() ),
3398 ParallelHexahedron( intHexa ),
3399 tbb::simple_partitioner()); // computeElements() is called here
3401 for ( size_t i = 0; i < intHexa.size(); ++i )
3402 if ( Hexahedron * hex = intHexa[ i ] )
3403 hex->computeElements();
3406 // simplify polyhedrons
3407 if ( _grid->IsToRemoveExcessEntities() )
3409 for ( size_t i = 0; i < intHexa.size(); ++i )
3410 if ( Hexahedron * hex = intHexa[ i ] )
3411 hex->removeExcessSideDivision( allHexa );
3413 for ( size_t i = 0; i < intHexa.size(); ++i )
3414 if ( Hexahedron * hex = intHexa[ i ] )
3415 hex->removeExcessNodes( allHexa );
3419 for ( size_t i = 0; i < intHexa.size(); ++i )
3420 if ( Hexahedron * hex = intHexa[ i ] )
3421 nbAdded += hex->addVolumes( helper );
3423 // fill boundaryVolumes with volumes neighboring too small skipped volumes
3424 if ( _grid->_toCreateFaces )
3426 for ( size_t i = 0; i < intHexa.size(); ++i )
3427 if ( Hexahedron * hex = intHexa[ i ] )
3428 hex->getBoundaryElems( boundaryVolumes );
3431 // create boundary mesh faces
3432 addFaces( helper, boundaryVolumes );
3434 // create mesh edges
3435 addSegments( helper, edge2faceIDsMap );
3437 for ( size_t i = 0; i < allHexa.size(); ++i )
3439 delete allHexa[ i ];
3444 //================================================================================
3446 * \brief Implements geom edges into the mesh
3448 void Hexahedron::addEdges(SMESH_MesherHelper& helper,
3449 vector< Hexahedron* >& hexes,
3450 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
3452 if ( edge2faceIDsMap.empty() ) return;
3454 // Prepare planes for intersecting with EDGEs
3457 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ ) // iDirZ gives normal direction to planes
3459 GridPlanes& planes = pln[ iDirZ ];
3460 int iDirX = ( iDirZ + 1 ) % 3;
3461 int iDirY = ( iDirZ + 2 ) % 3;
3462 planes._zNorm = ( _grid->_axes[ iDirX ] ^ _grid->_axes[ iDirY ] ).Normalized();
3463 planes._zProjs.resize ( _grid->_coords[ iDirZ ].size() );
3464 planes._zProjs [0] = 0;
3465 const double zFactor = _grid->_axes[ iDirZ ] * planes._zNorm;
3466 const vector< double > & u = _grid->_coords[ iDirZ ];
3467 for ( size_t i = 1; i < planes._zProjs.size(); ++i )
3469 planes._zProjs [i] = zFactor * ( u[i] - u[0] );
3473 const double deflection = _grid->_minCellSize / 20.;
3474 const double tol = _grid->_tol;
3475 E_IntersectPoint ip;
3477 TColStd_MapOfInteger intEdgeIDs; // IDs of not shared INTERNAL EDGES
3479 // Intersect EDGEs with the planes
3480 map< TGeomID, vector< TGeomID > >::const_iterator e2fIt = edge2faceIDsMap.begin();
3481 for ( ; e2fIt != edge2faceIDsMap.end(); ++e2fIt )
3483 const TGeomID edgeID = e2fIt->first;
3484 const TopoDS_Edge & E = TopoDS::Edge( _grid->Shape( edgeID ));
3485 BRepAdaptor_Curve curve( E );
3486 TopoDS_Vertex v1 = helper.IthVertex( 0, E, false );
3487 TopoDS_Vertex v2 = helper.IthVertex( 1, E, false );
3489 ip._faceIDs = e2fIt->second;
3490 ip._shapeID = edgeID;
3492 bool isInternal = ( ip._faceIDs.size() == 1 && _grid->IsInternal( edgeID ));
3495 intEdgeIDs.Add( edgeID );
3496 intEdgeIDs.Add( _grid->ShapeID( v1 ));
3497 intEdgeIDs.Add( _grid->ShapeID( v2 ));
3500 // discretize the EDGE
3501 GCPnts_UniformDeflection discret( curve, deflection, true );
3502 if ( !discret.IsDone() || discret.NbPoints() < 2 )
3505 // perform intersection
3506 E_IntersectPoint* eip, *vip = 0;
3507 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ )
3509 GridPlanes& planes = pln[ iDirZ ];
3510 int iDirX = ( iDirZ + 1 ) % 3;
3511 int iDirY = ( iDirZ + 2 ) % 3;
3512 double xLen = _grid->_coords[ iDirX ].back() - _grid->_coords[ iDirX ][0];
3513 double yLen = _grid->_coords[ iDirY ].back() - _grid->_coords[ iDirY ][0];
3514 double zLen = _grid->_coords[ iDirZ ].back() - _grid->_coords[ iDirZ ][0];
3515 int dIJK[3], d000[3] = { 0,0,0 };
3516 double o[3] = { _grid->_coords[0][0],
3517 _grid->_coords[1][0],
3518 _grid->_coords[2][0] };
3520 // locate the 1st point of a segment within the grid
3521 gp_XYZ p1 = discret.Value( 1 ).XYZ();
3522 double u1 = discret.Parameter( 1 );
3523 double zProj1 = planes._zNorm * ( p1 - _grid->_origin );
3525 _grid->ComputeUVW( p1, ip._uvw );
3526 int iX1 = int(( ip._uvw[iDirX] - o[iDirX]) / xLen * (_grid->_coords[ iDirX ].size() - 1));
3527 int iY1 = int(( ip._uvw[iDirY] - o[iDirY]) / yLen * (_grid->_coords[ iDirY ].size() - 1));
3528 int iZ1 = int(( ip._uvw[iDirZ] - o[iDirZ]) / zLen * (_grid->_coords[ iDirZ ].size() - 1));
3529 locateValue( iX1, ip._uvw[iDirX], _grid->_coords[ iDirX ], dIJK[ iDirX ], tol );
3530 locateValue( iY1, ip._uvw[iDirY], _grid->_coords[ iDirY ], dIJK[ iDirY ], tol );
3531 locateValue( iZ1, ip._uvw[iDirZ], _grid->_coords[ iDirZ ], dIJK[ iDirZ ], tol );
3533 int ijk[3]; // grid index where a segment intersects a plane
3538 // add the 1st vertex point to a hexahedron
3542 ip._shapeID = _grid->ShapeID( v1 );
3543 vip = _grid->Add( ip );
3545 vip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3546 if ( !addIntersection( vip, hexes, ijk, d000 ))
3547 _grid->Remove( vip );
3548 ip._shapeID = edgeID;
3550 for ( int iP = 2; iP <= discret.NbPoints(); ++iP )
3552 // locate the 2nd point of a segment within the grid
3553 gp_XYZ p2 = discret.Value( iP ).XYZ();
3554 double u2 = discret.Parameter( iP );
3555 double zProj2 = planes._zNorm * ( p2 - _grid->_origin );
3557 if ( Abs( zProj2 - zProj1 ) > std::numeric_limits<double>::min() )
3559 locateValue( iZ2, zProj2, planes._zProjs, dIJK[ iDirZ ], tol );
3561 // treat intersections with planes between 2 end points of a segment
3562 int dZ = ( iZ1 <= iZ2 ) ? +1 : -1;
3563 int iZ = iZ1 + ( iZ1 < iZ2 );
3564 for ( int i = 0, nb = Abs( iZ1 - iZ2 ); i < nb; ++i, iZ += dZ )
3566 ip._point = findIntPoint( u1, zProj1, u2, zProj2,
3567 planes._zProjs[ iZ ],
3568 curve, planes._zNorm, _grid->_origin );
3569 _grid->ComputeUVW( ip._point.XYZ(), ip._uvw );
3570 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
3571 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
3574 // add ip to hex "above" the plane
3575 eip = _grid->Add( ip );
3577 eip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3579 bool added = addIntersection( eip, hexes, ijk, dIJK);
3581 // add ip to hex "below" the plane
3582 ijk[ iDirZ ] = iZ-1;
3583 if ( !addIntersection( eip, hexes, ijk, dIJK ) &&
3585 _grid->Remove( eip );
3593 // add the 2nd vertex point to a hexahedron
3597 ip._shapeID = _grid->ShapeID( v2 );
3598 _grid->ComputeUVW( p1, ip._uvw );
3599 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
3600 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
3602 bool sameV = ( v1.IsSame( v2 ));
3604 vip = _grid->Add( ip );
3605 if ( isInternal && !sameV )
3606 vip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3607 if ( !addIntersection( vip, hexes, ijk, d000 ) && !sameV )
3608 _grid->Remove( vip );
3609 ip._shapeID = edgeID;
3611 } // loop on 3 grid directions
3615 if ( intEdgeIDs.Size() > 0 )
3616 cutByExtendedInternal( hexes, intEdgeIDs );
3621 //================================================================================
3623 * \brief Fully cut hexes that are partially cut by INTERNAL FACE.
3624 * Cut them by extended INTERNAL FACE.
3626 void Hexahedron::cutByExtendedInternal( std::vector< Hexahedron* >& hexes,
3627 const TColStd_MapOfInteger& intEdgeIDs )
3629 IntAna_IntConicQuad intersection;
3630 SMESHDS_Mesh* meshDS = _grid->_helper->GetMeshDS();
3631 const double tol2 = _grid->_tol * _grid->_tol;
3633 for ( size_t iH = 0; iH < hexes.size(); ++iH )
3635 Hexahedron* hex = hexes[ iH ];
3636 if ( !hex || hex->_eIntPoints.size() < 2 )
3638 if ( !intEdgeIDs.Contains( hex->_eIntPoints.back()->_shapeID ))
3641 // get 3 points on INTERNAL FACE to construct a cutting plane
3642 gp_Pnt p1 = hex->_eIntPoints[0]->_point;
3643 gp_Pnt p2 = hex->_eIntPoints[1]->_point;
3644 gp_Pnt p3 = hex->mostDistantInternalPnt( iH, p1, p2 );
3646 gp_Vec norm = gp_Vec( p1, p2 ) ^ gp_Vec( p1, p3 );
3649 pln = gp_Pln( p1, norm );
3656 TGeomID intFaceID = hex->_eIntPoints.back()->_faceIDs.front(); // FACE being "extended"
3657 TGeomID solidID = _grid->GetSolid( intFaceID )->ID();
3659 // cut links by the plane
3660 //bool isCut = false;
3661 for ( int iLink = 0; iLink < 12; ++iLink )
3663 _Link& link = hex->_hexLinks[ iLink ];
3664 if ( !link._fIntPoints.empty() )
3666 // if ( link._fIntPoints[0]->_faceIDs.back() == _grid->PseudoIntExtFaceID() )
3668 continue; // already cut link
3670 if ( !link._nodes[0]->Node() ||
3671 !link._nodes[1]->Node() )
3672 continue; // outside link
3674 if ( link._nodes[0]->IsOnFace( intFaceID ))
3676 if ( link._nodes[0]->_intPoint->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
3677 if ( p1.SquareDistance( link._nodes[0]->Point() ) < tol2 ||
3678 p2.SquareDistance( link._nodes[0]->Point() ) < tol2 )
3679 link._nodes[0]->_intPoint->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3680 continue; // link is cut by FACE being "extended"
3682 if ( link._nodes[1]->IsOnFace( intFaceID ))
3684 if ( link._nodes[1]->_intPoint->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
3685 if ( p1.SquareDistance( link._nodes[1]->Point() ) < tol2 ||
3686 p2.SquareDistance( link._nodes[1]->Point() ) < tol2 )
3687 link._nodes[1]->_intPoint->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3688 continue; // link is cut by FACE being "extended"
3690 gp_Pnt p4 = link._nodes[0]->Point();
3691 gp_Pnt p5 = link._nodes[1]->Point();
3692 gp_Lin line( p4, gp_Vec( p4, p5 ));
3694 intersection.Perform( line, pln );
3695 if ( !intersection.IsDone() ||
3696 intersection.IsInQuadric() ||
3697 intersection.IsParallel() ||
3698 intersection.NbPoints() < 1 )
3701 double u = intersection.ParamOnConic(1);
3702 if ( u + _grid->_tol < 0 )
3704 int iDir = iLink / 4;
3705 int index = (&hex->_i)[iDir];
3706 double linkLen = _grid->_coords[iDir][index+1] - _grid->_coords[iDir][index];
3707 if ( u - _grid->_tol > linkLen )
3710 if ( u < _grid->_tol ||
3711 u > linkLen - _grid->_tol ) // intersection at grid node
3713 int i = ! ( u < _grid->_tol ); // [0,1]
3714 int iN = link._nodes[ i ] - hex->_hexNodes; // [0-7]
3716 const F_IntersectPoint * & ip = _grid->_gridIntP[ hex->_origNodeInd +
3717 _grid->_nodeShift[iN] ];
3720 ip = _grid->_extIntPool.getNew();
3721 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3722 //ip->_transition = Trans_INTERNAL;
3724 else if ( ip->_faceIDs.back() != _grid->PseudoIntExtFaceID() )
3726 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3728 hex->_nbFaceIntNodes++;
3733 const gp_Pnt& p = intersection.Point( 1 );
3734 F_IntersectPoint* ip = _grid->_extIntPool.getNew();
3735 ip->_node = meshDS->AddNode( p.X(), p.Y(), p.Z() );
3736 ip->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3737 ip->_transition = Trans_INTERNAL;
3738 meshDS->SetNodeInVolume( ip->_node, solidID );
3740 CellsAroundLink fourCells( _grid, iDir );
3741 fourCells.Init( hex->_i, hex->_j, hex->_k, iLink );
3742 int i,j,k, cellIndex;
3743 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing the link
3745 if ( !fourCells.GetCell( iC, i,j,k, cellIndex, iLink ))
3747 Hexahedron * h = hexes[ cellIndex ];
3749 h = hexes[ cellIndex ] = new Hexahedron( *this, i, j, k, cellIndex );
3750 h->_hexLinks[iLink]._fIntPoints.push_back( ip );
3751 h->_nbFaceIntNodes++;
3758 // for ( size_t i = 0; i < hex->_eIntPoints.size(); ++i )
3760 // if ( _grid->IsInternal( hex->_eIntPoints[i]->_shapeID ) &&
3761 // ! hex->_eIntPoints[i]->IsOnFace( _grid->PseudoIntExtFaceID() ))
3762 // hex->_eIntPoints[i]->_faceIDs.push_back( _grid->PseudoIntExtFaceID() );
3766 } // loop on all hexes
3770 //================================================================================
3772 * \brief Return intersection point on INTERNAL FACE most distant from given ones
3774 gp_Pnt Hexahedron::mostDistantInternalPnt( int hexIndex, const gp_Pnt& p1, const gp_Pnt& p2 )
3776 gp_Pnt resultPnt = p1;
3778 double maxDist2 = 0;
3779 for ( int iLink = 0; iLink < 12; ++iLink ) // check links
3781 _Link& link = _hexLinks[ iLink ];
3782 for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
3783 if ( _grid->PseudoIntExtFaceID() != link._fIntPoints[i]->_faceIDs[0] &&
3784 _grid->IsInternal( link._fIntPoints[i]->_faceIDs[0] ) &&
3785 link._fIntPoints[i]->_node )
3787 gp_Pnt p = SMESH_NodeXYZ( link._fIntPoints[i]->_node );
3788 double d = p1.SquareDistance( p );
3796 d = p2.SquareDistance( p );
3806 _origNodeInd = _grid->NodeIndex( _i,_j,_k );
3808 for ( size_t iN = 0; iN < 8; ++iN ) // check corners
3810 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _grid->_nodeShift[iN] ];
3811 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _grid->_nodeShift[iN] ];
3812 if ( _hexNodes[iN]._intPoint )
3813 for ( size_t iF = 0; iF < _hexNodes[iN]._intPoint->_faceIDs.size(); ++iF )
3815 if ( _grid->IsInternal( _hexNodes[iN]._intPoint->_faceIDs[iF]))
3817 gp_Pnt p = SMESH_NodeXYZ( _hexNodes[iN]._node );
3818 double d = p1.SquareDistance( p );
3826 d = p2.SquareDistance( p );
3836 if ( maxDist2 < _grid->_tol * _grid->_tol )
3842 //================================================================================
3844 * \brief Finds intersection of a curve with a plane
3845 * \param [in] u1 - parameter of one curve point
3846 * \param [in] proj1 - projection of the curve point to the plane normal
3847 * \param [in] u2 - parameter of another curve point
3848 * \param [in] proj2 - projection of the other curve point to the plane normal
3849 * \param [in] proj - projection of a point where the curve intersects the plane
3850 * \param [in] curve - the curve
3851 * \param [in] axis - the plane normal
3852 * \param [in] origin - the plane origin
3853 * \return gp_Pnt - the found intersection point
3855 gp_Pnt Hexahedron::findIntPoint( double u1, double proj1,
3856 double u2, double proj2,
3858 BRepAdaptor_Curve& curve,
3860 const gp_XYZ& origin)
3862 double r = (( proj - proj1 ) / ( proj2 - proj1 ));
3863 double u = u1 * ( 1 - r ) + u2 * r;
3864 gp_Pnt p = curve.Value( u );
3865 double newProj = axis * ( p.XYZ() - origin );
3866 if ( Abs( proj - newProj ) > _grid->_tol / 10. )
3869 return findIntPoint( u2, proj2, u, newProj, proj, curve, axis, origin );
3871 return findIntPoint( u1, proj2, u, newProj, proj, curve, axis, origin );
3876 //================================================================================
3878 * \brief Returns indices of a hexahedron sub-entities holding a point
3879 * \param [in] ip - intersection point
3880 * \param [out] facets - 0-3 facets holding a point
3881 * \param [out] sub - index of a vertex or an edge holding a point
3882 * \return int - number of facets holding a point
3884 int Hexahedron::getEntity( const E_IntersectPoint* ip, int* facets, int& sub )
3886 enum { X = 1, Y = 2, Z = 4 }; // == 001, 010, 100
3888 int vertex = 0, edgeMask = 0;
3890 if ( Abs( _grid->_coords[0][ _i ] - ip->_uvw[0] ) < _grid->_tol ) {
3891 facets[ nbFacets++ ] = SMESH_Block::ID_F0yz;
3894 else if ( Abs( _grid->_coords[0][ _i+1 ] - ip->_uvw[0] ) < _grid->_tol ) {
3895 facets[ nbFacets++ ] = SMESH_Block::ID_F1yz;
3899 if ( Abs( _grid->_coords[1][ _j ] - ip->_uvw[1] ) < _grid->_tol ) {
3900 facets[ nbFacets++ ] = SMESH_Block::ID_Fx0z;
3903 else if ( Abs( _grid->_coords[1][ _j+1 ] - ip->_uvw[1] ) < _grid->_tol ) {
3904 facets[ nbFacets++ ] = SMESH_Block::ID_Fx1z;
3908 if ( Abs( _grid->_coords[2][ _k ] - ip->_uvw[2] ) < _grid->_tol ) {
3909 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy0;
3912 else if ( Abs( _grid->_coords[2][ _k+1 ] - ip->_uvw[2] ) < _grid->_tol ) {
3913 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy1;
3920 case 0: sub = 0; break;
3921 case 1: sub = facets[0]; break;
3923 const int edge [3][8] = {
3924 { SMESH_Block::ID_E00z, SMESH_Block::ID_E10z,
3925 SMESH_Block::ID_E01z, SMESH_Block::ID_E11z },
3926 { SMESH_Block::ID_E0y0, SMESH_Block::ID_E1y0, 0, 0,
3927 SMESH_Block::ID_E0y1, SMESH_Block::ID_E1y1 },
3928 { SMESH_Block::ID_Ex00, 0, SMESH_Block::ID_Ex10, 0,
3929 SMESH_Block::ID_Ex01, 0, SMESH_Block::ID_Ex11 }
3931 switch ( edgeMask ) {
3932 case X | Y: sub = edge[ 0 ][ vertex ]; break;
3933 case X | Z: sub = edge[ 1 ][ vertex ]; break;
3934 default: sub = edge[ 2 ][ vertex ];
3940 sub = vertex + SMESH_Block::ID_FirstV;
3945 //================================================================================
3947 * \brief Adds intersection with an EDGE
3949 bool Hexahedron::addIntersection( const E_IntersectPoint* ip,
3950 vector< Hexahedron* >& hexes,
3951 int ijk[], int dIJK[] )
3955 size_t hexIndex[4] = {
3956 _grid->CellIndex( ijk[0], ijk[1], ijk[2] ),
3957 dIJK[0] ? _grid->CellIndex( ijk[0]+dIJK[0], ijk[1], ijk[2] ) : -1,
3958 dIJK[1] ? _grid->CellIndex( ijk[0], ijk[1]+dIJK[1], ijk[2] ) : -1,
3959 dIJK[2] ? _grid->CellIndex( ijk[0], ijk[1], ijk[2]+dIJK[2] ) : -1
3961 for ( int i = 0; i < 4; ++i )
3963 if ( hexIndex[i] < hexes.size() && hexes[ hexIndex[i] ] )
3965 Hexahedron* h = hexes[ hexIndex[i] ];
3966 h->_eIntPoints.reserve(2);
3967 h->_eIntPoints.push_back( ip );
3970 // check if ip is really inside the hex
3971 if ( h->isOutParam( ip->_uvw ))
3972 throw SALOME_Exception("ip outside a hex");
3978 //================================================================================
3980 * \brief Finds nodes at a path from one node to another via intersections with EDGEs
3982 bool Hexahedron::findChain( _Node* n1,
3985 vector<_Node*>& chn )
3988 chn.push_back( n1 );
3989 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
3990 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
3991 n1->IsLinked( quad._eIntNodes[ iP ]->_intPoint ) &&
3992 n2->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
3994 chn.push_back( quad._eIntNodes[ iP ]);
3995 chn.push_back( n2 );
3996 quad._eIntNodes[ iP ]->_usedInFace = &quad;
4003 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4004 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
4005 chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
4007 chn.push_back( quad._eIntNodes[ iP ]);
4008 found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
4011 } while ( found && ! chn.back()->IsLinked( n2->_intPoint ) );
4013 if ( chn.back() != n2 && chn.back()->IsLinked( n2->_intPoint ))
4014 chn.push_back( n2 );
4016 return chn.size() > 1;
4018 //================================================================================
4020 * \brief Try to heal a polygon whose ends are not connected
4022 bool Hexahedron::closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const
4024 int i = -1, nbLinks = polygon->_links.size();
4027 vector< _OrientedLink > newLinks;
4028 // find a node lying on the same FACE as the last one
4029 _Node* node = polygon->_links.back().LastNode();
4030 int avoidFace = node->IsLinked( polygon->_links.back().FirstNode()->_intPoint );
4031 for ( i = nbLinks - 2; i >= 0; --i )
4032 if ( node->IsLinked( polygon->_links[i].FirstNode()->_intPoint, avoidFace ))
4036 for ( ; i < nbLinks; ++i )
4037 newLinks.push_back( polygon->_links[i] );
4041 // find a node lying on the same FACE as the first one
4042 node = polygon->_links[0].FirstNode();
4043 avoidFace = node->IsLinked( polygon->_links[0].LastNode()->_intPoint );
4044 for ( i = 1; i < nbLinks; ++i )
4045 if ( node->IsLinked( polygon->_links[i].LastNode()->_intPoint, avoidFace ))
4048 for ( nbLinks = i + 1, i = 0; i < nbLinks; ++i )
4049 newLinks.push_back( polygon->_links[i] );
4051 if ( newLinks.size() > 1 )
4053 polygon->_links.swap( newLinks );
4055 chainNodes.push_back( polygon->_links.back().LastNode() );
4056 chainNodes.push_back( polygon->_links[0].FirstNode() );
4061 //================================================================================
4063 * \brief Finds nodes on the same EDGE as the first node of avoidSplit.
4065 * This function is for
4066 * 1) a case where an EDGE lies on a quad which lies on a FACE
4067 * so that a part of quad in ON and another part is IN
4068 * 2) INTERNAL FACE passes through the 1st node of avoidSplit
4070 bool Hexahedron::findChainOnEdge( const vector< _OrientedLink >& splits,
4071 const _OrientedLink& prevSplit,
4072 const _OrientedLink& avoidSplit,
4075 vector<_Node*>& chn )
4077 _Node* pn1 = prevSplit.FirstNode();
4078 _Node* pn2 = prevSplit.LastNode();
4079 int avoidFace = pn1->IsLinked( pn2->_intPoint ); // FACE under the quad
4080 if ( avoidFace < 1 && pn1->_intPoint )
4083 _Node* n = 0, *stopNode = avoidSplit.LastNode();
4086 if ( !quad._eIntNodes.empty() ) // connect pn2 with EDGE intersections
4088 chn.push_back( pn2 );
4093 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
4094 if (( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad )) &&
4095 ( chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint, avoidFace )) &&
4096 ( !avoidFace || quad._eIntNodes[ iP ]->IsOnFace( avoidFace )))
4098 chn.push_back( quad._eIntNodes[ iP ]);
4099 found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
4107 for ( i = splits.size()-1; i >= 0; --i ) // connect new pn2 (at _eIntNodes) with a split
4112 n = splits[i].LastNode();
4113 if ( n == stopNode )
4116 ( n->IsLinked( pn2->_intPoint, avoidFace )) &&
4117 ( !avoidFace || n->IsOnFace( avoidFace )))
4120 n = splits[i].FirstNode();
4121 if ( n == stopNode )
4123 if (( n->IsLinked( pn2->_intPoint, avoidFace )) &&
4124 ( !avoidFace || n->IsOnFace( avoidFace )))
4128 if ( n && n != stopNode )
4131 chn.push_back( pn2 );
4136 else if ( !chn.empty() && chn.back()->_isInternalFlags )
4138 // INTERNAL FACE partially cuts the quad
4139 for ( int i = chn.size() - 2; i >= 0; --i )
4140 chn.push_back( chn[ i ]);
4145 //================================================================================
4147 * \brief Checks transition at the ginen intersection node of a link
4149 bool Hexahedron::isOutPoint( _Link& link, int iP,
4150 SMESH_MesherHelper& helper, const Solid* solid ) const
4154 if ( link._fIntNodes[iP]->faces().size() == 1 &&
4155 _grid->IsInternal( link._fIntNodes[iP]->face(0) ))
4158 const bool moreIntPoints = ( iP+1 < (int) link._fIntNodes.size() );
4161 _Node* n1 = link._fIntNodes[ iP ];
4163 n1 = link._nodes[0];
4164 _Node* n2 = moreIntPoints ? link._fIntNodes[ iP+1 ] : 0;
4165 if ( !n2 || !n2->Node() )
4166 n2 = link._nodes[1];
4170 // get all FACEs under n1 and n2
4171 set< TGeomID > faceIDs;
4172 if ( moreIntPoints ) faceIDs.insert( link._fIntNodes[iP+1]->faces().begin(),
4173 link._fIntNodes[iP+1]->faces().end() );
4174 if ( n2->_intPoint ) faceIDs.insert( n2->_intPoint->_faceIDs.begin(),
4175 n2->_intPoint->_faceIDs.end() );
4176 if ( faceIDs.empty() )
4177 return false; // n2 is inside
4178 if ( n1->_intPoint ) faceIDs.insert( n1->_intPoint->_faceIDs.begin(),
4179 n1->_intPoint->_faceIDs.end() );
4180 faceIDs.insert( link._fIntNodes[iP]->faces().begin(),
4181 link._fIntNodes[iP]->faces().end() );
4183 // get a point between 2 nodes
4184 gp_Pnt p1 = n1->Point();
4185 gp_Pnt p2 = n2->Point();
4186 gp_Pnt pOnLink = 0.8 * p1.XYZ() + 0.2 * p2.XYZ();
4188 TopLoc_Location loc;
4190 set< TGeomID >::iterator faceID = faceIDs.begin();
4191 for ( ; faceID != faceIDs.end(); ++faceID )
4193 // project pOnLink on a FACE
4194 if ( *faceID < 1 || !solid->Contains( *faceID )) continue;
4195 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( *faceID ));
4196 GeomAPI_ProjectPointOnSurf& proj = helper.GetProjector( face, loc, 0.1*_grid->_tol );
4197 gp_Pnt testPnt = pOnLink.Transformed( loc.Transformation().Inverted() );
4198 proj.Perform( testPnt );
4199 if ( proj.IsDone() && proj.NbPoints() > 0 )
4202 proj.LowerDistanceParameters( u,v );
4204 if ( proj.LowerDistance() <= 0.1 * _grid->_tol )
4210 // find isOut by normals
4212 if ( GeomLib::NormEstim( BRep_Tool::Surface( face, loc ),
4217 if ( solid->Orientation( face ) == TopAbs_REVERSED )
4219 gp_Vec v( proj.NearestPoint(), testPnt );
4220 isOut = ( v * normal > 0 );
4225 // classify a projection
4226 if ( !n1->IsOnFace( *faceID ) || !n2->IsOnFace( *faceID ))
4228 BRepTopAdaptor_FClass2d cls( face, Precision::Confusion() );
4229 TopAbs_State state = cls.Perform( gp_Pnt2d( u,v ));
4230 if ( state == TopAbs_OUT )
4242 //================================================================================
4244 * \brief Sort nodes on a FACE
4246 void Hexahedron::sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID faceID)
4248 if ( nodes.size() > 20 ) return;
4250 // get shapes under nodes
4251 TGeomID nShapeIds[20], *nShapeIdsEnd = &nShapeIds[0] + nodes.size();
4252 for ( size_t i = 0; i < nodes.size(); ++i )
4253 if ( !( nShapeIds[i] = nodes[i]->ShapeID() ))
4256 // get shapes of the FACE
4257 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( faceID ));
4258 list< TopoDS_Edge > edges;
4259 list< int > nbEdges;
4260 int nbW = SMESH_Block::GetOrderedEdges (face, edges, nbEdges);
4262 // select a WIRE - remove EDGEs of irrelevant WIREs from edges
4263 list< TopoDS_Edge >::iterator e = edges.begin(), eEnd = e;
4264 list< int >::iterator nE = nbEdges.begin();
4265 for ( ; nbW > 0; ++nE, --nbW )
4267 std::advance( eEnd, *nE );
4268 for ( ; e != eEnd; ++e )
4269 for ( int i = 0; i < 2; ++i )
4272 _grid->ShapeID( *e ) :
4273 _grid->ShapeID( SMESH_MesherHelper::IthVertex( 0, *e ));
4275 ( std::find( &nShapeIds[0], nShapeIdsEnd, id ) != nShapeIdsEnd ))
4277 edges.erase( eEnd, edges.end() ); // remove rest wires
4278 e = eEnd = edges.end();
4285 edges.erase( edges.begin(), eEnd ); // remove a current irrelevant wire
4288 // rotate edges to have the first one at least partially out of the hexa
4289 list< TopoDS_Edge >::iterator e = edges.begin(), eMidOut = edges.end();
4290 for ( ; e != edges.end(); ++e )
4292 if ( !_grid->ShapeID( *e ))
4297 for ( int i = 0; i < 2 && !isOut; ++i )
4301 TopoDS_Vertex v = SMESH_MesherHelper::IthVertex( 0, *e );
4302 p = BRep_Tool::Pnt( v );
4304 else if ( eMidOut == edges.end() )
4306 TopLoc_Location loc;
4307 Handle(Geom_Curve) c = BRep_Tool::Curve( *e, loc, f, l);
4308 if ( c.IsNull() ) break;
4309 p = c->Value( 0.5 * ( f + l )).Transformed( loc );
4316 _grid->ComputeUVW( p.XYZ(), uvw );
4317 if ( isOutParam( uvw ))
4328 if ( e != edges.end() )
4329 edges.splice( edges.end(), edges, edges.begin(), e );
4330 else if ( eMidOut != edges.end() )
4331 edges.splice( edges.end(), edges, edges.begin(), eMidOut );
4333 // sort nodes according to the order of edges
4334 _Node* orderNodes [20];
4335 //TGeomID orderShapeIDs[20];
4337 TGeomID id, *pID = 0;
4338 for ( e = edges.begin(); e != edges.end(); ++e )
4340 if (( id = _grid->ShapeID( SMESH_MesherHelper::IthVertex( 0, *e ))) &&
4341 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
4343 //orderShapeIDs[ nbN ] = id;
4344 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
4347 if (( id = _grid->ShapeID( *e )) &&
4348 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
4350 //orderShapeIDs[ nbN ] = id;
4351 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
4355 if ( nbN != nodes.size() )
4358 bool reverse = ( orderNodes[0 ]->Point().SquareDistance( curNode->Point() ) >
4359 orderNodes[nbN-1]->Point().SquareDistance( curNode->Point() ));
4361 for ( size_t i = 0; i < nodes.size(); ++i )
4362 nodes[ i ] = orderNodes[ reverse ? nbN-1-i : i ];
4365 //================================================================================
4367 * \brief Adds computed elements to the mesh
4369 int Hexahedron::addVolumes( SMESH_MesherHelper& helper )
4371 F_IntersectPoint noIntPnt;
4372 const bool toCheckNodePos = _grid->IsToCheckNodePos();
4375 // add elements resulted from hexahedron intersection
4376 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
4378 vector< const SMDS_MeshNode* > nodes( volDef->_nodes.size() );
4379 for ( size_t iN = 0; iN < nodes.size(); ++iN )
4381 if ( !( nodes[iN] = volDef->_nodes[iN].Node() ))
4383 if ( const E_IntersectPoint* eip = volDef->_nodes[iN].EdgeIntPnt() )
4385 nodes[iN] = volDef->_nodes[iN]._intPoint->_node =
4386 helper.AddNode( eip->_point.X(),
4389 if ( _grid->ShapeType( eip->_shapeID ) == TopAbs_VERTEX )
4390 helper.GetMeshDS()->SetNodeOnVertex( nodes[iN], eip->_shapeID );
4392 helper.GetMeshDS()->SetNodeOnEdge( nodes[iN], eip->_shapeID );
4395 throw SALOME_Exception("Bug: no node at intersection point");
4397 else if ( volDef->_nodes[iN]._intPoint &&
4398 volDef->_nodes[iN]._intPoint->_node == volDef->_nodes[iN]._node )
4400 // Update position of node at EDGE intersection;
4401 // see comment to _Node::Add( E_IntersectPoint )
4402 SMESHDS_Mesh* mesh = helper.GetMeshDS();
4403 TGeomID shapeID = volDef->_nodes[iN].EdgeIntPnt()->_shapeID;
4404 mesh->UnSetNodeOnShape( nodes[iN] );
4405 if ( _grid->ShapeType( shapeID ) == TopAbs_VERTEX )
4406 mesh->SetNodeOnVertex( nodes[iN], shapeID );
4408 mesh->SetNodeOnEdge( nodes[iN], shapeID );
4410 else if ( toCheckNodePos &&
4411 !nodes[iN]->isMarked() &&
4412 _grid->ShapeType( nodes[iN]->GetShapeID() ) == TopAbs_FACE )
4414 _grid->SetOnShape( nodes[iN], noIntPnt, /*unset=*/true );
4415 nodes[iN]->setIsMarked( true );
4419 const SMDS_MeshElement* v = 0;
4420 if ( !volDef->_quantities.empty() )
4422 v = helper.AddPolyhedralVolume( nodes, volDef->_quantities );
4426 switch ( nodes.size() )
4428 case 8: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],
4429 nodes[4],nodes[5],nodes[6],nodes[7] );
4431 case 4: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3] );
4433 case 6: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4],nodes[5] );
4435 case 5: v = helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4] );
4439 if (( volDef->_volume = v ))
4441 helper.GetMeshDS()->SetMeshElementOnShape( v, volDef->_solidID );
4448 //================================================================================
4450 * \brief Return true if the element is in a hole
4452 bool Hexahedron::isInHole() const
4454 if ( !_vIntNodes.empty() )
4457 const size_t ijk[3] = { _i, _j, _k };
4458 F_IntersectPoint curIntPnt;
4460 // consider a cell to be in a hole if all links in any direction
4461 // comes OUT of geometry
4462 for ( int iDir = 0; iDir < 3; ++iDir )
4464 const vector<double>& coords = _grid->_coords[ iDir ];
4465 LineIndexer li = _grid->GetLineIndexer( iDir );
4466 li.SetIJK( _i,_j,_k );
4467 size_t lineIndex[4] = { li.LineIndex (),
4471 bool allLinksOut = true, hasLinks = false;
4472 for ( int iL = 0; iL < 4 && allLinksOut; ++iL ) // loop on 4 links parallel to iDir
4474 const _Link& link = _hexLinks[ iL + 4*iDir ];
4475 // check transition of the first node of a link
4476 const F_IntersectPoint* firstIntPnt = 0;
4477 if ( link._nodes[0]->Node() ) // 1st node is a hexa corner
4479 curIntPnt._paramOnLine = coords[ ijk[ iDir ]] - coords[0] + _grid->_tol;
4480 const GridLine& line = _grid->_lines[ iDir ][ lineIndex[ iL ]];
4481 if ( !line._intPoints.empty() )
4483 multiset< F_IntersectPoint >::const_iterator ip =
4484 line._intPoints.upper_bound( curIntPnt );
4486 firstIntPnt = &(*ip);
4489 else if ( !link._fIntPoints.empty() )
4491 firstIntPnt = link._fIntPoints[0];
4497 allLinksOut = ( firstIntPnt->_transition == Trans_OUT &&
4498 !_grid->IsShared( firstIntPnt->_faceIDs[0] ));
4501 if ( hasLinks && allLinksOut )
4507 //================================================================================
4509 * \brief Check if a polyherdon has an edge lying on EDGE shared by strange FACE
4510 * that will be meshed by other algo
4512 bool Hexahedron::hasStrangeEdge() const
4514 if ( _eIntPoints.size() < 2 )
4517 TopTools_MapOfShape edges;
4518 for ( size_t i = 0; i < _eIntPoints.size(); ++i )
4520 if ( !_grid->IsStrangeEdge( _eIntPoints[i]->_shapeID ))
4522 const TopoDS_Shape& s = _grid->Shape( _eIntPoints[i]->_shapeID );
4523 if ( s.ShapeType() == TopAbs_EDGE )
4525 if ( ! edges.Add( s ))
4526 return true; // an EDGE encounters twice
4530 PShapeIteratorPtr edgeIt = _grid->_helper->GetAncestors( s,
4531 *_grid->_helper->GetMesh(),
4533 while ( const TopoDS_Shape* edge = edgeIt->next() )
4534 if ( ! edges.Add( *edge ))
4535 return true; // an EDGE encounters twice
4541 //================================================================================
4543 * \brief Return true if a polyhedron passes _sizeThreshold criterion
4545 bool Hexahedron::checkPolyhedronSize( bool cutByInternalFace ) const
4547 if ( cutByInternalFace && !_grid->_toUseThresholdForInternalFaces )
4549 // check if any polygon fully lies on shared/internal FACEs
4550 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
4552 const _Face& polygon = _polygons[iP];
4553 if ( polygon._links.empty() )
4555 bool allNodesInternal = true;
4556 for ( size_t iL = 0; iL < polygon._links.size() && allNodesInternal; ++iL )
4558 _Node* n = polygon._links[ iL ].FirstNode();
4559 allNodesInternal = (( n->IsCutByInternal() ) ||
4560 ( n->_intPoint && _grid->IsAnyShared( n->_intPoint->_faceIDs )));
4562 if ( allNodesInternal )
4566 if ( this->hasStrangeEdge() )
4570 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
4572 const _Face& polygon = _polygons[iP];
4573 if ( polygon._links.empty() )
4575 gp_XYZ area (0,0,0);
4576 gp_XYZ p1 = polygon._links[ 0 ].FirstNode()->Point().XYZ();
4577 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
4579 gp_XYZ p2 = polygon._links[ iL ].LastNode()->Point().XYZ();
4583 volume += p1 * area;
4587 double initVolume = _sideLength[0] * _sideLength[1] * _sideLength[2];
4589 return volume > initVolume / _grid->_sizeThreshold;
4591 //================================================================================
4593 * \brief Tries to create a hexahedron
4595 bool Hexahedron::addHexa()
4597 int nbQuad = 0, iQuad = -1;
4598 for ( size_t i = 0; i < _polygons.size(); ++i )
4600 if ( _polygons[i]._links.empty() )
4602 if ( _polygons[i]._links.size() != 4 )
4613 for ( int iL = 0; iL < 4; ++iL )
4616 nodes[iL] = _polygons[iQuad]._links[iL].FirstNode();
4619 // find a top node above the base node
4620 _Link* link = _polygons[iQuad]._links[iL]._link;
4621 if ( !link->_faces[0] || !link->_faces[1] )
4622 return debugDumpLink( link );
4623 // a quadrangle sharing <link> with _polygons[iQuad]
4624 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[iQuad] )];
4625 for ( int i = 0; i < 4; ++i )
4626 if ( quad->_links[i]._link == link )
4628 // 1st node of a link opposite to <link> in <quad>
4629 nodes[iL+4] = quad->_links[(i+2)%4].FirstNode();
4635 _volumeDefs.Set( &nodes[0], 8 );
4639 //================================================================================
4641 * \brief Tries to create a tetrahedron
4643 bool Hexahedron::addTetra()
4646 for ( size_t i = 0; i < _polygons.size() && iTria < 0; ++i )
4647 if ( _polygons[i]._links.size() == 3 )
4653 nodes[0] = _polygons[iTria]._links[0].FirstNode();
4654 nodes[1] = _polygons[iTria]._links[1].FirstNode();
4655 nodes[2] = _polygons[iTria]._links[2].FirstNode();
4657 _Link* link = _polygons[iTria]._links[0]._link;
4658 if ( !link->_faces[0] || !link->_faces[1] )
4659 return debugDumpLink( link );
4661 // a triangle sharing <link> with _polygons[0]
4662 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[iTria] )];
4663 for ( int i = 0; i < 3; ++i )
4664 if ( tria->_links[i]._link == link )
4666 nodes[3] = tria->_links[(i+1)%3].LastNode();
4667 _volumeDefs.Set( &nodes[0], 4 );
4673 //================================================================================
4675 * \brief Tries to create a pentahedron
4677 bool Hexahedron::addPenta()
4679 // find a base triangular face
4681 for ( int iF = 0; iF < 5 && iTri < 0; ++iF )
4682 if ( _polygons[ iF ]._links.size() == 3 )
4684 if ( iTri < 0 ) return false;
4689 for ( int iL = 0; iL < 3; ++iL )
4692 nodes[iL] = _polygons[ iTri ]._links[iL].FirstNode();
4695 // find a top node above the base node
4696 _Link* link = _polygons[ iTri ]._links[iL]._link;
4697 if ( !link->_faces[0] || !link->_faces[1] )
4698 return debugDumpLink( link );
4699 // a quadrangle sharing <link> with a base triangle
4700 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[ iTri ] )];
4701 if ( quad->_links.size() != 4 ) return false;
4702 for ( int i = 0; i < 4; ++i )
4703 if ( quad->_links[i]._link == link )
4705 // 1st node of a link opposite to <link> in <quad>
4706 nodes[iL+3] = quad->_links[(i+2)%4].FirstNode();
4712 _volumeDefs.Set( &nodes[0], 6 );
4714 return ( nbN == 6 );
4716 //================================================================================
4718 * \brief Tries to create a pyramid
4720 bool Hexahedron::addPyra()
4722 // find a base quadrangle
4724 for ( int iF = 0; iF < 5 && iQuad < 0; ++iF )
4725 if ( _polygons[ iF ]._links.size() == 4 )
4727 if ( iQuad < 0 ) return false;
4731 nodes[0] = _polygons[iQuad]._links[0].FirstNode();
4732 nodes[1] = _polygons[iQuad]._links[1].FirstNode();
4733 nodes[2] = _polygons[iQuad]._links[2].FirstNode();
4734 nodes[3] = _polygons[iQuad]._links[3].FirstNode();
4736 _Link* link = _polygons[iQuad]._links[0]._link;
4737 if ( !link->_faces[0] || !link->_faces[1] )
4738 return debugDumpLink( link );
4740 // a triangle sharing <link> with a base quadrangle
4741 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[ iQuad ] )];
4742 if ( tria->_links.size() != 3 ) return false;
4743 for ( int i = 0; i < 3; ++i )
4744 if ( tria->_links[i]._link == link )
4746 nodes[4] = tria->_links[(i+1)%3].LastNode();
4747 _volumeDefs.Set( &nodes[0], 5 );
4753 //================================================================================
4755 * \brief Dump a link and return \c false
4757 bool Hexahedron::debugDumpLink( Hexahedron::_Link* link )
4760 gp_Pnt p1 = link->_nodes[0]->Point(), p2 = link->_nodes[1]->Point();
4761 cout << "BUG: not shared link. IKJ = ( "<< _i << " " << _j << " " << _k << " )" << endl
4762 << "n1 (" << p1.X() << ", "<< p1.Y() << ", "<< p1.Z() << " )" << endl
4763 << "n2 (" << p2.X() << ", "<< p2.Y() << ", "<< p2.Z() << " )" << endl;
4765 (void)link; // unused in release mode
4769 //================================================================================
4771 * \brief Classify a point by grid parameters
4773 bool Hexahedron::isOutParam(const double uvw[3]) const
4775 return (( _grid->_coords[0][ _i ] - _grid->_tol > uvw[0] ) ||
4776 ( _grid->_coords[0][ _i+1 ] + _grid->_tol < uvw[0] ) ||
4777 ( _grid->_coords[1][ _j ] - _grid->_tol > uvw[1] ) ||
4778 ( _grid->_coords[1][ _j+1 ] + _grid->_tol < uvw[1] ) ||
4779 ( _grid->_coords[2][ _k ] - _grid->_tol > uvw[2] ) ||
4780 ( _grid->_coords[2][ _k+1 ] + _grid->_tol < uvw[2] ));
4782 //================================================================================
4784 * \brief Divide a polygon into triangles and modify accordingly an adjacent polyhedron
4786 void splitPolygon( const SMDS_MeshElement* polygon,
4787 SMDS_VolumeTool & volume,
4788 const int facetIndex,
4789 const TGeomID faceID,
4790 const TGeomID solidID,
4791 SMESH_MeshEditor::ElemFeatures& face,
4792 SMESH_MeshEditor& editor,
4793 const bool reinitVolume)
4795 SMESH_MeshAlgos::Triangulate divider(/*optimize=*/false);
4796 int nbTrias = divider.GetTriangles( polygon, face.myNodes );
4797 face.myNodes.resize( nbTrias * 3 );
4799 SMESH_MeshEditor::ElemFeatures newVolumeDef;
4800 newVolumeDef.Init( volume.Element() );
4801 newVolumeDef.SetID( volume.Element()->GetID() );
4803 newVolumeDef.myPolyhedQuantities.reserve( volume.NbFaces() + nbTrias );
4804 newVolumeDef.myNodes.reserve( volume.NbNodes() + nbTrias * 3 );
4806 SMESHDS_Mesh* meshDS = editor.GetMeshDS();
4807 SMDS_MeshElement* newTriangle;
4808 for ( int iF = 0, nF = volume.NbFaces(); iF < nF; iF++ )
4810 if ( iF == facetIndex )
4812 newVolumeDef.myPolyhedQuantities.push_back( 3 );
4813 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(),
4814 face.myNodes.begin(),
4815 face.myNodes.begin() + 3 );
4816 meshDS->RemoveFreeElement( polygon, 0, false );
4817 newTriangle = meshDS->AddFace( face.myNodes[0], face.myNodes[1], face.myNodes[2] );
4818 meshDS->SetMeshElementOnShape( newTriangle, faceID );
4822 const SMDS_MeshNode** nn = volume.GetFaceNodes( iF );
4823 const size_t nbFaceNodes = volume.NbFaceNodes ( iF );
4824 newVolumeDef.myPolyhedQuantities.push_back( nbFaceNodes );
4825 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(), nn, nn + nbFaceNodes );
4829 for ( size_t iN = 3; iN < face.myNodes.size(); iN += 3 )
4831 newVolumeDef.myPolyhedQuantities.push_back( 3 );
4832 newVolumeDef.myNodes.insert( newVolumeDef.myNodes.end(),
4833 face.myNodes.begin() + iN,
4834 face.myNodes.begin() + iN + 3 );
4835 newTriangle = meshDS->AddFace( face.myNodes[iN], face.myNodes[iN+1], face.myNodes[iN+2] );
4836 meshDS->SetMeshElementOnShape( newTriangle, faceID );
4839 meshDS->RemoveFreeElement( volume.Element(), 0, false );
4840 SMDS_MeshElement* newVolume = editor.AddElement( newVolumeDef.myNodes, newVolumeDef );
4841 meshDS->SetMeshElementOnShape( newVolume, solidID );
4846 volume.Set( newVolume );
4850 //================================================================================
4852 * \brief Create mesh faces at free facets
4854 void Hexahedron::addFaces( SMESH_MesherHelper& helper,
4855 const vector< const SMDS_MeshElement* > & boundaryVolumes )
4857 if ( !_grid->_toCreateFaces )
4860 SMDS_VolumeTool vTool;
4861 vector<int> bndFacets;
4862 SMESH_MeshEditor editor( helper.GetMesh() );
4863 SMESH_MeshEditor::ElemFeatures face( SMDSAbs_Face );
4864 SMESHDS_Mesh* meshDS = helper.GetMeshDS();
4866 // check if there are internal or shared FACEs
4867 bool hasInternal = ( !_grid->_geometry.IsOneSolid() ||
4868 _grid->_geometry._soleSolid.HasInternalFaces() );
4870 for ( size_t iV = 0; iV < boundaryVolumes.size(); ++iV )
4872 if ( !vTool.Set( boundaryVolumes[ iV ]))
4875 TGeomID solidID = vTool.Element()->GetShapeID();
4876 Solid * solid = _grid->GetOneOfSolids( solidID );
4878 // find boundary facets
4881 for ( int iF = 0, n = vTool.NbFaces(); iF < n; iF++ )
4883 bool isBoundary = vTool.IsFreeFace( iF );
4886 bndFacets.push_back( iF );
4888 else if ( hasInternal )
4890 // check if all nodes are on internal/shared FACEs
4892 const SMDS_MeshNode** nn = vTool.GetFaceNodes( iF );
4893 const size_t nbFaceNodes = vTool.NbFaceNodes ( iF );
4894 for ( size_t iN = 0; iN < nbFaceNodes && isBoundary; ++iN )
4895 isBoundary = ( nn[ iN ]->GetShapeID() != solidID );
4897 bndFacets.push_back( -( iF+1 )); // !!! minus ==> to check the FACE
4900 if ( bndFacets.empty() )
4905 if ( !vTool.IsPoly() )
4906 vTool.SetExternalNormal();
4907 for ( size_t i = 0; i < bndFacets.size(); ++i ) // loop on boundary facets
4909 const bool isBoundary = ( bndFacets[i] >= 0 );
4910 const int iFacet = isBoundary ? bndFacets[i] : -bndFacets[i]-1;
4911 const SMDS_MeshNode** nn = vTool.GetFaceNodes( iFacet );
4912 const size_t nbFaceNodes = vTool.NbFaceNodes ( iFacet );
4913 face.myNodes.assign( nn, nn + nbFaceNodes );
4916 const SMDS_MeshElement* existFace = 0, *newFace = 0;
4918 if (( existFace = meshDS->FindElement( face.myNodes, SMDSAbs_Face )))
4920 if ( existFace->isMarked() )
4921 continue; // created by this method
4922 faceID = existFace->GetShapeID();
4926 // look for a supporting FACE
4927 for ( size_t iN = 0; iN < nbFaceNodes && !faceID; ++iN ) // look for a node on FACE
4929 if ( nn[ iN ]->GetPosition()->GetDim() == 2 )
4930 faceID = nn[ iN ]->GetShapeID();
4932 for ( size_t iN = 0; iN < nbFaceNodes && !faceID; ++iN )
4934 // look for a father FACE of EDGEs and VERTEXes
4935 const TopoDS_Shape& s1 = _grid->Shape( nn[ iN ]->GetShapeID() );
4936 const TopoDS_Shape& s2 = _grid->Shape( nn[ iN+1 ]->GetShapeID() );
4937 if ( s1 != s2 && s1.ShapeType() == TopAbs_EDGE && s2.ShapeType() == TopAbs_EDGE )
4939 TopoDS_Shape f = helper.GetCommonAncestor( s1, s2, *helper.GetMesh(), TopAbs_FACE );
4941 faceID = _grid->ShapeID( f );
4945 bool toCheckFace = faceID && (( !isBoundary ) ||
4946 ( hasInternal && _grid->_toUseThresholdForInternalFaces ));
4947 if ( toCheckFace ) // check if all nodes are on the found FACE
4949 SMESH_subMesh* faceSM = helper.GetMesh()->GetSubMeshContaining( faceID );
4950 for ( size_t iN = 0; iN < nbFaceNodes && faceID; ++iN )
4952 TGeomID subID = nn[ iN ]->GetShapeID();
4953 if ( subID != faceID && !faceSM->DependsOn( subID ))
4956 if ( !faceID && !isBoundary )
4960 // orient a new face according to supporting FACE orientation in shape_to_mesh
4961 if ( !solid->IsOutsideOriented( faceID ))
4964 editor.Reorient( existFace );
4966 std::reverse( face.myNodes.begin(), face.myNodes.end() );
4969 if ( ! ( newFace = existFace ))
4971 face.SetPoly( nbFaceNodes > 4 );
4972 newFace = editor.AddElement( face.myNodes, face );
4975 newFace->setIsMarked( true ); // to distinguish from face created in getBoundaryElems()
4978 if ( faceID && _grid->IsBoundaryFace( faceID )) // face is not shared
4980 // set newFace to the found FACE provided that it fully lies on the FACE
4981 for ( size_t iN = 0; iN < nbFaceNodes && faceID; ++iN )
4982 if ( nn[iN]->GetShapeID() == solidID )
4985 meshDS->UnSetMeshElementOnShape( existFace, _grid->Shape( faceID ));
4990 // split a polygon that will be used by other 3D algorithm
4991 if ( faceID && nbFaceNodes > 4 &&
4992 !_grid->IsInternal( faceID ) &&
4993 !_grid->IsShared( faceID ) &&
4994 !_grid->IsBoundaryFace( faceID ))
4996 splitPolygon( newFace, vTool, iFacet, faceID, solidID,
4997 face, editor, i+1 < bndFacets.size() );
5002 meshDS->SetMeshElementOnShape( newFace, faceID );
5004 meshDS->SetMeshElementOnShape( newFace, solidID );
5006 } // loop on bndFacets
5007 } // loop on boundaryVolumes
5010 // Orient coherently mesh faces on INTERNAL FACEs
5014 TopExp_Explorer faceExp( _grid->_geometry._mainShape, TopAbs_FACE );
5015 for ( ; faceExp.More(); faceExp.Next() )
5017 if ( faceExp.Current().Orientation() != TopAbs_INTERNAL )
5020 SMESHDS_SubMesh* sm = meshDS->MeshElements( faceExp.Current() );
5021 if ( !sm ) continue;
5023 TIDSortedElemSet facesToOrient;
5024 for ( SMDS_ElemIteratorPtr fIt = sm->GetElements(); fIt->more(); )
5025 facesToOrient.insert( facesToOrient.end(), fIt->next() );
5026 if ( facesToOrient.size() < 2 )
5029 gp_Dir direction(1,0,0);
5030 const SMDS_MeshElement* anyFace = *facesToOrient.begin();
5031 editor.Reorient2D( facesToOrient, direction, anyFace );
5037 //================================================================================
5039 * \brief Create mesh segments.
5041 void Hexahedron::addSegments( SMESH_MesherHelper& helper,
5042 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap )
5044 SMESHDS_Mesh* mesh = helper.GetMeshDS();
5046 std::vector<const SMDS_MeshNode*> nodes;
5047 std::vector<const SMDS_MeshElement *> elems;
5048 map< TGeomID, vector< TGeomID > >::const_iterator e2ff = edge2faceIDsMap.begin();
5049 for ( ; e2ff != edge2faceIDsMap.end(); ++e2ff )
5051 const TopoDS_Edge& edge = TopoDS::Edge( _grid->Shape( e2ff->first ));
5052 const TopoDS_Face& face = TopoDS::Face( _grid->Shape( e2ff->second[0] ));
5053 StdMeshers_FaceSide side( face, edge, helper.GetMesh(), /*isFwd=*/true, /*skipMed=*/true );
5054 nodes = side.GetOrderedNodes();
5057 if ( nodes.size() == 2 )
5058 // check that there is an element connecting two nodes
5059 if ( !mesh->GetElementsByNodes( nodes, elems ))
5062 for ( size_t i = 1; i < nodes.size(); i++ )
5064 SMDS_MeshElement* segment = mesh->AddEdge( nodes[i-1], nodes[i] );
5065 mesh->SetMeshElementOnShape( segment, e2ff->first );
5071 //================================================================================
5073 * \brief Return created volumes and volumes that can have free facet because of
5074 * skipped small volume. Also create mesh faces on free facets
5075 * of adjacent not-cut volumes if the result volume is too small.
5077 void Hexahedron::getBoundaryElems( vector< const SMDS_MeshElement* > & boundaryElems )
5079 if ( _hasTooSmall /*|| _volumeDefs.IsEmpty()*/ )
5081 // create faces around a missing small volume
5083 SMESH_MeshEditor editor( _grid->_helper->GetMesh() );
5084 SMESH_MeshEditor::ElemFeatures polygon( SMDSAbs_Face );
5085 SMESHDS_Mesh* meshDS = _grid->_helper->GetMeshDS();
5086 std::vector<const SMDS_MeshElement *> adjVolumes(2);
5087 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
5089 const size_t nbLinks = _polygons[ iF ]._links.size();
5090 if ( nbLinks != 4 ) continue;
5091 polygon.myNodes.resize( nbLinks );
5092 polygon.myNodes.back() = 0;
5093 for ( size_t iL = 0, iN = nbLinks - 1; iL < nbLinks; ++iL, --iN )
5094 if ( ! ( polygon.myNodes[iN] = _polygons[ iF ]._links[ iL ].FirstNode()->Node() ))
5096 if ( !polygon.myNodes.back() )
5099 meshDS->GetElementsByNodes( polygon.myNodes, adjVolumes, SMDSAbs_Volume );
5100 if ( adjVolumes.size() != 1 )
5102 if ( !adjVolumes[0]->isMarked() )
5104 boundaryElems.push_back( adjVolumes[0] );
5105 adjVolumes[0]->setIsMarked( true );
5108 bool sameShape = true;
5109 TGeomID shapeID = polygon.myNodes[0]->GetShapeID();
5110 for ( size_t i = 1; i < polygon.myNodes.size() && sameShape; ++i )
5111 sameShape = ( shapeID == polygon.myNodes[i]->GetShapeID() );
5113 if ( !sameShape || !_grid->IsSolid( shapeID ))
5114 continue; // some of shapes must be FACE
5118 faceID = getAnyFace();
5121 if ( _grid->IsInternal( faceID ) ||
5122 _grid->IsShared( faceID ) //||
5123 //_grid->IsBoundaryFace( faceID ) -- commented for #19887
5125 break; // create only if a new face will be used by other 3D algo
5128 Solid * solid = _grid->GetOneOfSolids( adjVolumes[0]->GetShapeID() );
5129 if ( !solid->IsOutsideOriented( faceID ))
5130 std::reverse( polygon.myNodes.begin(), polygon.myNodes.end() );
5132 //polygon.SetPoly( polygon.myNodes.size() > 4 );
5133 const SMDS_MeshElement* newFace = editor.AddElement( polygon.myNodes, polygon );
5134 meshDS->SetMeshElementOnShape( newFace, faceID );
5138 // return created volumes
5139 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
5141 if ( volDef->_volume && !volDef->_volume->isMarked() )
5143 volDef->_volume->setIsMarked( true );
5144 boundaryElems.push_back( volDef->_volume );
5146 if ( _grid->IsToCheckNodePos() ) // un-mark nodes marked in addVolumes()
5147 for ( size_t iN = 0; iN < volDef->_nodes.size(); ++iN )
5148 volDef->_nodes[iN].Node()->setIsMarked( false );
5153 //================================================================================
5155 * \brief Remove edges and nodes dividing a hexa side in the case if an adjacent
5156 * volume also sharing the dividing edge is missing due to its small side.
5159 //================================================================================
5161 void Hexahedron::removeExcessSideDivision(const vector< Hexahedron* >& allHexa)
5163 if ( ! _volumeDefs.IsPolyhedron() )
5164 return; // not a polyhedron
5166 // look for a divided side adjacent to a small hexahedron
5168 int di[6] = { 0, 0, 0, 0,-1, 1 };
5169 int dj[6] = { 0, 0,-1, 1, 0, 0 };
5170 int dk[6] = {-1, 1, 0, 0, 0, 0 };
5172 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
5174 size_t neighborIndex = _grid->CellIndex( _i + di[iF],
5177 if ( neighborIndex >= allHexa.size() ||
5178 !allHexa[ neighborIndex ] ||
5179 !allHexa[ neighborIndex ]->_hasTooSmall )
5182 // check if a side is divided into several polygons
5183 for ( _volumeDef* volDef = &_volumeDefs; volDef; volDef = volDef->_next )
5185 int nbPolygons = 0, nbNodes = 0;
5186 for ( size_t i = 0; i < volDef->_names.size(); ++i )
5187 if ( volDef->_names[ i ] == _hexQuads[ iF ]._name )
5190 nbNodes += volDef->_quantities[ i ];
5192 if ( nbPolygons < 2 )
5195 // construct loops from polygons
5196 typedef _volumeDef::_linkDef TLinkDef;
5197 std::vector< TLinkDef* > loops;
5198 std::vector< TLinkDef > links( nbNodes );
5199 for ( size_t i = 0, iN = 0, iLoop = 0; iLoop < volDef->_quantities.size(); ++iLoop )
5201 size_t nbLinks = volDef->_quantities[ iLoop ];
5202 if ( volDef->_names[ iLoop ] != _hexQuads[ iF ]._name )
5207 loops.push_back( & links[i] );
5208 for ( size_t n = 0; n < nbLinks-1; ++n, ++i, ++iN )
5210 links[i].init( volDef->_nodes[iN], volDef->_nodes[iN+1], iLoop );
5211 links[i].setNext( &links[i+1] );
5213 links[i].init( volDef->_nodes[iN], volDef->_nodes[iN-nbLinks+1], iLoop );
5214 links[i].setNext( &links[i-nbLinks+1] );
5218 // look for equal links in different loops and join such loops
5219 bool loopsJoined = false;
5220 std::set< TLinkDef > linkSet;
5221 for ( size_t iLoop = 0; iLoop < loops.size(); ++iLoop )
5224 for ( TLinkDef* l = loops[ iLoop ]; l != beg; l = l->_next ) // walk around the iLoop
5226 std::pair< std::set< TLinkDef >::iterator, bool > it2new = linkSet.insert( *l );
5227 if ( !it2new.second ) // equal found, join loops
5229 const TLinkDef* equal = &(*it2new.first);
5230 if ( equal->_loopIndex == l->_loopIndex )
5235 for ( size_t i = iLoop - 1; i < loops.size(); --i )
5236 if ( loops[ i ] && loops[ i ]->_loopIndex == equal->_loopIndex )
5239 // exclude l and equal and join two loops
5240 if ( l->_prev != equal )
5241 l->_prev->setNext( equal->_next );
5242 if ( equal->_prev != l )
5243 equal->_prev->setNext( l->_next );
5245 if ( volDef->_quantities[ l->_loopIndex ] > 0 )
5246 volDef->_quantities[ l->_loopIndex ] *= -1;
5247 if ( volDef->_quantities[ equal->_loopIndex ] > 0 )
5248 volDef->_quantities[ equal->_loopIndex ] *= -1;
5250 if ( loops[ iLoop ] == l )
5251 loops[ iLoop ] = l->_prev->_next;
5253 beg = loops[ iLoop ];
5259 // set unchanged polygons
5260 std::vector< int > newQuantities;
5261 std::vector< _volumeDef::_nodeDef > newNodes;
5262 vector< SMESH_Block::TShapeID > newNames;
5263 newQuantities.reserve( volDef->_quantities.size() );
5264 newNodes.reserve ( volDef->_nodes.size() );
5265 newNames.reserve ( volDef->_names.size() );
5266 for ( size_t i = 0, iLoop = 0; iLoop < volDef->_quantities.size(); ++iLoop )
5268 if ( volDef->_quantities[ iLoop ] < 0 )
5270 i -= volDef->_quantities[ iLoop ];
5273 newQuantities.push_back( volDef->_quantities[ iLoop ]);
5274 newNodes.insert( newNodes.end(),
5275 volDef->_nodes.begin() + i,
5276 volDef->_nodes.begin() + i + newQuantities.back() );
5277 newNames.push_back( volDef->_names[ iLoop ]);
5278 i += volDef->_quantities[ iLoop ];
5282 for ( size_t iLoop = 0; iLoop < loops.size(); ++iLoop )
5284 if ( !loops[ iLoop ] )
5286 newQuantities.push_back( 0 );
5288 for ( TLinkDef* l = loops[ iLoop ]; l != beg; l = l->_next, ++newQuantities.back() )
5290 newNodes.push_back( l->_node1 );
5291 beg = loops[ iLoop ];
5293 newNames.push_back( _hexQuads[ iF ]._name );
5295 volDef->_quantities.swap( newQuantities );
5296 volDef->_nodes.swap( newNodes );
5297 volDef->_names.swap( newNames );
5299 } // loop on volDef's
5300 } // loop on hex sides
5303 } // removeExcessSideDivision()
5306 //================================================================================
5308 * \brief Remove nodes splitting Cartesian cell edges in the case if a node
5309 * is used in every cells only by two polygons sharing the edge
5312 //================================================================================
5314 void Hexahedron::removeExcessNodes(vector< Hexahedron* >& allHexa)
5316 if ( ! _volumeDefs.IsPolyhedron() )
5317 return; // not a polyhedron
5319 typedef vector< _volumeDef::_nodeDef >::iterator TNodeIt;
5320 vector< int > nodesInPoly[ 4 ]; // node index in _volumeDefs._nodes
5321 vector< int > volDefInd [ 4 ]; // index of a _volumeDefs
5322 Hexahedron* hexa [ 4 ];
5323 int i,j,k, cellIndex, iLink = 0, iCellLink;
5324 for ( int iDir = 0; iDir < 3; ++iDir )
5326 CellsAroundLink fourCells( _grid, iDir );
5327 for ( int iL = 0; iL < 4; ++iL, ++iLink ) // 4 links in a direction
5329 _Link& link = _hexLinks[ iLink ];
5330 fourCells.Init( _i, _j, _k, iLink );
5332 for ( size_t iP = 0; iP < link._fIntPoints.size(); ++iP ) // loop on nodes on the link
5334 bool nodeRemoved = true;
5335 _volumeDef::_nodeDef node; node._intPoint = link._fIntPoints[iP];
5337 for ( size_t i = 0, nb = _volumeDefs.size(); i < nb && nodeRemoved; ++i )
5338 if ( _volumeDef* vol = _volumeDefs.at( i ))
5340 ( std::find( vol->_nodes.begin(), vol->_nodes.end(), node ) == vol->_nodes.end() );
5342 continue; // node already removed
5344 // check if a node encounters zero or two times in 4 cells sharing iLink
5345 // if so, the node can be removed from the cells
5346 bool nodeIsOnEdge = true;
5347 int nbPolyhedraWithNode = 0;
5348 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing a link
5350 nodesInPoly[ iC ].clear();
5351 volDefInd [ iC ].clear();
5353 if ( !fourCells.GetCell( iC, i,j,k, cellIndex, iCellLink ))
5355 hexa[ iC ] = allHexa[ cellIndex ];
5358 for ( size_t i = 0, nb = hexa[ iC ]->_volumeDefs.size(); i < nb; ++i )
5359 if ( _volumeDef* vol = hexa[ iC ]->_volumeDefs.at( i ))
5361 for ( TNodeIt nIt = vol->_nodes.begin(); nIt != vol->_nodes.end(); ++nIt )
5363 nIt = std::find( nIt, vol->_nodes.end(), node );
5364 if ( nIt != vol->_nodes.end() )
5366 nodesInPoly[ iC ].push_back( std::distance( vol->_nodes.begin(), nIt ));
5367 volDefInd [ iC ].push_back( i );
5372 nbPolyhedraWithNode += ( !nodesInPoly[ iC ].empty() );
5374 if ( nodesInPoly[ iC ].size() != 0 &&
5375 nodesInPoly[ iC ].size() != 2 )
5377 nodeIsOnEdge = false;
5380 } // loop on 4 cells
5382 // remove nodes from polyhedra
5383 if ( nbPolyhedraWithNode > 0 && nodeIsOnEdge )
5385 for ( int iC = 0; iC < 4; ++iC ) // loop on 4 cells sharing the link
5387 if ( nodesInPoly[ iC ].empty() )
5389 for ( int i = volDefInd[ iC ].size() - 1; i >= 0; --i )
5391 _volumeDef* vol = hexa[ iC ]->_volumeDefs.at( volDefInd[ iC ][ i ]);
5392 int nIndex = nodesInPoly[ iC ][ i ];
5393 // decrement _quantities
5394 for ( size_t iQ = 0; iQ < vol->_quantities.size(); ++iQ )
5395 if ( nIndex < vol->_quantities[ iQ ])
5397 vol->_quantities[ iQ ]--;
5402 nIndex -= vol->_quantities[ iQ ];
5404 vol->_nodes.erase( vol->_nodes.begin() + nodesInPoly[ iC ][ i ]);
5407 vol->_nodes.size() == 6 * 4 &&
5408 vol->_quantities.size() == 6 ) // polyhedron becomes hexahedron?
5410 bool allQuads = true;
5411 for ( size_t iQ = 0; iQ < vol->_quantities.size() && allQuads; ++iQ )
5412 allQuads = ( vol->_quantities[ iQ ] == 4 );
5415 // set side nodes as this: bottom, top, top, ...
5416 int iTop = 0, iBot = 0; // side indices
5417 for ( int iS = 0; iS < 6; ++iS )
5419 if ( vol->_names[ iS ] == SMESH_Block::ID_Fxy0 )
5421 if ( vol->_names[ iS ] == SMESH_Block::ID_Fxy1 )
5428 std::copy( vol->_nodes.begin(),
5429 vol->_nodes.begin() + 4,
5430 vol->_nodes.begin() + 4 );
5433 std::copy( vol->_nodes.begin() + 4 * iBot,
5434 vol->_nodes.begin() + 4 * ( iBot + 1),
5435 vol->_nodes.begin() );
5438 std::copy( vol->_nodes.begin() + 4 * iTop,
5439 vol->_nodes.begin() + 4 * ( iTop + 1),
5440 vol->_nodes.begin() + 4 );
5442 std::copy( vol->_nodes.begin() + 4,
5443 vol->_nodes.begin() + 8,
5444 vol->_nodes.begin() + 8 );
5445 // set up top facet nodes by comparing their uvw with bottom nodes
5446 E_IntersectPoint ip[8];
5447 for ( int iN = 0; iN < 8; ++iN )
5449 SMESH_NodeXYZ p = vol->_nodes[ iN ].Node();
5450 _grid->ComputeUVW( p, ip[ iN ]._uvw );
5452 const double tol2 = _grid->_tol * _grid->_tol;
5453 for ( int iN = 0; iN < 4; ++iN )
5455 gp_Pnt2d pBot( ip[ iN ]._uvw[0], ip[ iN ]._uvw[1] );
5456 for ( int iT = 4; iT < 8; ++iT )
5458 gp_Pnt2d pTop( ip[ iT ]._uvw[0], ip[ iT ]._uvw[1] );
5459 if ( pBot.SquareDistance( pTop ) < tol2 )
5461 // vol->_nodes[ iN + 4 ]._node = ip[ iT ]._node;
5462 // vol->_nodes[ iN + 4 ]._intPoint = 0;
5463 vol->_nodes[ iN + 4 ] = vol->_nodes[ iT + 4 ];
5468 vol->_nodes.resize( 8 );
5469 vol->_quantities.clear();
5470 //vol->_names.clear();
5473 } // loop on _volumeDefs
5474 } // loop on 4 cell abound a link
5475 } // if ( nodeIsOnEdge )
5476 } // loop on intersection points of a link
5477 } // loop on 4 links of a direction
5478 } // loop on 3 directions
5482 } // removeExcessNodes()
5484 //================================================================================
5486 * \brief [Issue #19913] Modify _hexLinks._splits to prevent creating overlapping volumes
5488 //================================================================================
5490 void Hexahedron::preventVolumesOverlapping()
5492 // Cut off a quadrangle corner if two links sharing the corner
5493 // are shared by same two solids, in this case each of solids gets
5494 // a triangle for it-self.
5495 std::vector< TGeomID > soIDs[4];
5496 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
5498 _Face& quad = _hexQuads[ iF ] ;
5500 int iFOpposite = iF + ( iF % 2 ? -1 : 1 );
5501 _Face& quadOpp = _hexQuads[ iFOpposite ] ;
5503 int nbSides = 0, nbSidesOpp = 0;
5504 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
5506 nbSides += ( quad._links [ iE ].NbResultLinks() > 0 );
5507 nbSidesOpp += ( quadOpp._links[ iE ].NbResultLinks() > 0 );
5509 if ( nbSides < 4 || nbSidesOpp != 2 )
5512 for ( int iE = 0; iE < 4; ++iE )
5514 soIDs[ iE ].clear();
5515 _Node* n = quad._links[ iE ].FirstNode();
5516 if ( n->_intPoint && n->_intPoint->_faceIDs.size() )
5517 soIDs[ iE ] = _grid->GetSolidIDs( n->_intPoint->_faceIDs[0] );
5519 if ((( soIDs[0].size() >= 2 ) +
5520 ( soIDs[1].size() >= 2 ) +
5521 ( soIDs[2].size() >= 2 ) +
5522 ( soIDs[3].size() >= 2 ) ) < 3 )
5526 for ( int i = 0; i < 4; ++i )
5528 int i1 = _grid->_helper->WrapIndex( i + 1, 4 );
5529 int i2 = _grid->_helper->WrapIndex( i + 2, 4 );
5530 int i3 = _grid->_helper->WrapIndex( i + 3, 4 );
5531 if ( soIDs[i1].size() == 2 && soIDs[i ] != soIDs[i1] &&
5532 soIDs[i2].size() == 2 && soIDs[i1] == soIDs[i2] &&
5533 soIDs[i3].size() == 2 && soIDs[i2] == soIDs[i3] )
5535 quad._links[ i1 ]._link->_splits.clear();
5536 quad._links[ i2 ]._link->_splits.clear();
5545 } // preventVolumesOverlapping()
5547 //================================================================================
5549 * \brief Set to _hexLinks a next portion of splits located on one side of INTERNAL FACEs
5551 bool Hexahedron::_SplitIterator::Next()
5553 if ( _iterationNb > 0 )
5554 // count used splits
5555 for ( size_t i = 0; i < _splits.size(); ++i )
5557 if ( _splits[i]._iCheckIteration == _iterationNb )
5559 _splits[i]._isUsed = _splits[i]._checkedSplit->_faces[1];
5560 _nbUsed += _splits[i]._isUsed;
5568 bool toTestUsed = ( _nbChecked >= _splits.size() );
5571 // all splits are checked; find all not used splits
5572 for ( size_t i = 0; i < _splits.size(); ++i )
5573 if ( !_splits[i].IsCheckedOrUsed( toTestUsed ))
5574 _splits[i]._iCheckIteration = _iterationNb;
5576 _nbUsed = _splits.size(); // to stop iteration
5580 // get any not used/checked split to start from
5582 for ( size_t i = 0; i < _splits.size(); ++i )
5584 if ( !_splits[i].IsCheckedOrUsed( toTestUsed ))
5586 _freeNodes.push_back( _splits[i]._nodes[0] );
5587 _freeNodes.push_back( _splits[i]._nodes[1] );
5588 _splits[i]._iCheckIteration = _iterationNb;
5592 // find splits connected to the start one via _freeNodes
5593 for ( size_t iN = 0; iN < _freeNodes.size(); ++iN )
5595 for ( size_t iS = 0; iS < _splits.size(); ++iS )
5597 if ( _splits[iS].IsCheckedOrUsed( toTestUsed ))
5600 if ( _freeNodes[iN] == _splits[iS]._nodes[0] )
5602 else if ( _freeNodes[iN] == _splits[iS]._nodes[1] )
5606 if ( _freeNodes[iN]->_isInternalFlags > 0 )
5608 if ( _splits[iS]._nodes[ iN2 ]->_isInternalFlags == 0 )
5610 if ( !_splits[iS]._nodes[ iN2 ]->IsLinked( _freeNodes[iN]->_intPoint ))
5613 _splits[iS]._iCheckIteration = _iterationNb;
5614 _freeNodes.push_back( _splits[iS]._nodes[ iN2 ]);
5618 // set splits to hex links
5620 for ( int iL = 0; iL < 12; ++iL )
5621 _hexLinks[ iL ]._splits.clear();
5624 for ( size_t i = 0; i < _splits.size(); ++i )
5626 if ( _splits[i]._iCheckIteration == _iterationNb )
5628 split._nodes[0] = _splits[i]._nodes[0];
5629 split._nodes[1] = _splits[i]._nodes[1];
5630 _Link & hexLink = _hexLinks[ _splits[i]._linkID ];
5631 hexLink._splits.push_back( split );
5632 _splits[i]._checkedSplit = & hexLink._splits.back();
5639 //================================================================================
5641 * \brief computes exact bounding box with axes parallel to given ones
5643 //================================================================================
5645 void getExactBndBox( const vector< TopoDS_Shape >& faceVec,
5646 const double* axesDirs,
5650 TopoDS_Compound allFacesComp;
5651 b.MakeCompound( allFacesComp );
5652 for ( size_t iF = 0; iF < faceVec.size(); ++iF )
5653 b.Add( allFacesComp, faceVec[ iF ] );
5655 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
5656 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
5658 for ( int i = 0; i < 6; ++i )
5659 farDist = Max( farDist, 10 * sP[i] );
5661 gp_XYZ axis[3] = { gp_XYZ( axesDirs[0], axesDirs[1], axesDirs[2] ),
5662 gp_XYZ( axesDirs[3], axesDirs[4], axesDirs[5] ),
5663 gp_XYZ( axesDirs[6], axesDirs[7], axesDirs[8] ) };
5664 axis[0].Normalize();
5665 axis[1].Normalize();
5666 axis[2].Normalize();
5668 gp_Mat basis( axis[0], axis[1], axis[2] );
5669 gp_Mat bi = basis.Inverted();
5672 for ( int iDir = 0; iDir < 3; ++iDir )
5674 gp_XYZ axis0 = axis[ iDir ];
5675 gp_XYZ axis1 = axis[ ( iDir + 1 ) % 3 ];
5676 gp_XYZ axis2 = axis[ ( iDir + 2 ) % 3 ];
5677 for ( int isMax = 0; isMax < 2; ++isMax )
5679 double shift = isMax ? farDist : -farDist;
5680 gp_XYZ orig = shift * axis0;
5681 gp_XYZ norm = axis1 ^ axis2;
5682 gp_Pln pln( orig, norm );
5683 norm = pln.Axis().Direction().XYZ();
5684 BRepBuilderAPI_MakeFace plane( pln, -farDist, farDist, -farDist, farDist );
5686 gp_Pnt& pAxis = isMax ? pMax : pMin;
5687 gp_Pnt pPlane, pFaces;
5688 double dist = GEOMUtils::GetMinDistance( plane, allFacesComp, pPlane, pFaces );
5693 for ( int i = 0; i < 2; ++i ) {
5694 corner.SetCoord( 1, sP[ i*3 ]);
5695 for ( int j = 0; j < 2; ++j ) {
5696 corner.SetCoord( 2, sP[ i*3 + 1 ]);
5697 for ( int k = 0; k < 2; ++k )
5699 corner.SetCoord( 3, sP[ i*3 + 2 ]);
5705 corner = isMax ? bb.CornerMax() : bb.CornerMin();
5706 pAxis.SetCoord( iDir+1, corner.Coord( iDir+1 ));
5710 gp_XYZ pf = pFaces.XYZ() * bi;
5711 pAxis.SetCoord( iDir+1, pf.Coord( iDir+1 ) );
5717 shapeBox.Add( pMin );
5718 shapeBox.Add( pMax );
5725 //=============================================================================
5727 * \brief Generates 3D structured Cartesian mesh in the internal part of
5728 * solid shapes and polyhedral volumes near the shape boundary.
5729 * \param theMesh - mesh to fill in
5730 * \param theShape - a compound of all SOLIDs to mesh
5731 * \retval bool - true in case of success
5733 //=============================================================================
5735 bool StdMeshers_Cartesian_3D::Compute(SMESH_Mesh & theMesh,
5736 const TopoDS_Shape & theShape)
5738 // The algorithm generates the mesh in following steps:
5740 // 1) Intersection of grid lines with the geometry boundary.
5741 // This step allows to find out if a given node of the initial grid is
5742 // inside or outside the geometry.
5744 // 2) For each cell of the grid, check how many of it's nodes are outside
5745 // of the geometry boundary. Depending on a result of this check
5746 // - skip a cell, if all it's nodes are outside
5747 // - skip a cell, if it is too small according to the size threshold
5748 // - add a hexahedron in the mesh, if all nodes are inside
5749 // - add a polyhedron in the mesh, if some nodes are inside and some outside
5751 _computeCanceled = false;
5753 SMESH_MesherHelper helper( theMesh );
5754 SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
5759 grid._helper = &helper;
5760 grid._toAddEdges = _hyp->GetToAddEdges();
5761 grid._toCreateFaces = _hyp->GetToCreateFaces();
5762 grid._toConsiderInternalFaces = _hyp->GetToConsiderInternalFaces();
5763 grid._toUseThresholdForInternalFaces = _hyp->GetToUseThresholdForInternalFaces();
5764 grid._sizeThreshold = _hyp->GetSizeThreshold();
5765 grid.InitGeometry( theShape );
5767 vector< TopoDS_Shape > faceVec;
5769 TopTools_MapOfShape faceMap;
5770 TopExp_Explorer fExp;
5771 for ( fExp.Init( theShape, TopAbs_FACE ); fExp.More(); fExp.Next() )
5773 bool isNewFace = faceMap.Add( fExp.Current() );
5774 if ( !grid._toConsiderInternalFaces )
5775 if ( !isNewFace || fExp.Current().Orientation() == TopAbs_INTERNAL )
5776 // remove an internal face
5777 faceMap.Remove( fExp.Current() );
5779 faceVec.reserve( faceMap.Extent() );
5780 faceVec.assign( faceMap.cbegin(), faceMap.cend() );
5782 vector<FaceGridIntersector> facesItersectors( faceVec.size() );
5784 for ( size_t i = 0; i < faceVec.size(); ++i )
5786 facesItersectors[i]._face = TopoDS::Face( faceVec[i] );
5787 facesItersectors[i]._faceID = grid.ShapeID( faceVec[i] );
5788 facesItersectors[i]._grid = &grid;
5789 shapeBox.Add( facesItersectors[i].GetFaceBndBox() );
5791 getExactBndBox( faceVec, _hyp->GetAxisDirs(), shapeBox );
5794 vector<double> xCoords, yCoords, zCoords;
5795 _hyp->GetCoordinates( xCoords, yCoords, zCoords, shapeBox );
5797 grid.SetCoordinates( xCoords, yCoords, zCoords, _hyp->GetAxisDirs(), shapeBox );
5799 if ( _computeCanceled ) return false;
5802 { // copy partner faces and curves of not thread-safe types
5803 set< const Standard_Transient* > tshapes;
5804 BRepBuilderAPI_Copy copier;
5805 for ( size_t i = 0; i < facesItersectors.size(); ++i )
5807 if ( !facesItersectors[i].IsThreadSafe( tshapes ))
5809 copier.Perform( facesItersectors[i]._face );
5810 facesItersectors[i]._face = TopoDS::Face( copier );
5814 // Intersection of grid lines with the geometry boundary.
5815 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, facesItersectors.size() ),
5816 ParallelIntersector( facesItersectors ),
5817 tbb::simple_partitioner());
5819 for ( size_t i = 0; i < facesItersectors.size(); ++i )
5820 facesItersectors[i].Intersect();
5823 // put intersection points onto the GridLine's; this is done after intersection
5824 // to avoid contention of facesItersectors for writing into the same GridLine
5825 // in case of parallel work of facesItersectors
5826 for ( size_t i = 0; i < facesItersectors.size(); ++i )
5827 facesItersectors[i].StoreIntersections();
5829 if ( _computeCanceled ) return false;
5831 // create nodes on the geometry
5832 grid.ComputeNodes( helper );
5834 if ( _computeCanceled ) return false;
5836 // get EDGEs to take into account
5837 map< TGeomID, vector< TGeomID > > edge2faceIDsMap;
5838 grid.GetEdgesToImplement( edge2faceIDsMap, theShape, faceVec );
5840 // create volume elements
5841 Hexahedron hex( &grid );
5842 int nbAdded = hex.MakeElements( helper, edge2faceIDsMap );
5846 if ( !grid._toConsiderInternalFaces )
5848 // make all SOLIDs computed
5849 TopExp_Explorer solidExp( theShape, TopAbs_SOLID );
5850 if ( SMESHDS_SubMesh* sm1 = meshDS->MeshElements( solidExp.Current()) )
5852 SMDS_ElemIteratorPtr volIt = sm1->GetElements();
5853 for ( ; solidExp.More() && volIt->more(); solidExp.Next() )
5855 const SMDS_MeshElement* vol = volIt->next();
5856 sm1->RemoveElement( vol );
5857 meshDS->SetMeshElementOnShape( vol, solidExp.Current() );
5861 // make other sub-shapes computed
5862 setSubmeshesComputed( theMesh, theShape );
5865 // remove free nodes
5866 //if ( SMESHDS_SubMesh * smDS = meshDS->MeshElements( helper.GetSubShapeID() ))
5868 std::vector< const SMDS_MeshNode* > nodesToRemove;
5869 // get intersection nodes
5870 for ( int iDir = 0; iDir < 3; ++iDir )
5872 vector< GridLine >& lines = grid._lines[ iDir ];
5873 for ( size_t i = 0; i < lines.size(); ++i )
5875 multiset< F_IntersectPoint >::iterator ip = lines[i]._intPoints.begin();
5876 for ( ; ip != lines[i]._intPoints.end(); ++ip )
5877 if ( ip->_node && ip->_node->NbInverseElements() == 0 && !ip->_node->isMarked() )
5879 nodesToRemove.push_back( ip->_node );
5880 ip->_node->setIsMarked( true );
5885 for ( size_t i = 0; i < grid._nodes.size(); ++i )
5886 if ( grid._nodes[i] && grid._nodes[i]->NbInverseElements() == 0 &&
5887 !grid._nodes[i]->isMarked() )
5889 nodesToRemove.push_back( grid._nodes[i] );
5890 grid._nodes[i]->setIsMarked( true );
5894 for ( size_t i = 0; i < nodesToRemove.size(); ++i )
5895 meshDS->RemoveFreeNode( nodesToRemove[i], /*smD=*/0, /*fromGroups=*/false );
5901 // SMESH_ComputeError is not caught at SMESH_submesh level for an unknown reason
5902 catch ( SMESH_ComputeError& e)
5904 return error( SMESH_ComputeErrorPtr( new SMESH_ComputeError( e )));
5909 //=============================================================================
5913 //=============================================================================
5915 bool StdMeshers_Cartesian_3D::Evaluate(SMESH_Mesh & /*theMesh*/,
5916 const TopoDS_Shape & /*theShape*/,
5917 MapShapeNbElems& /*theResMap*/)
5920 // std::vector<int> aResVec(SMDSEntity_Last);
5921 // for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
5922 // if(IsQuadratic) {
5923 // aResVec[SMDSEntity_Quad_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
5924 // int nb1d_face0_int = ( nb2d_face0*4 - nb1d ) / 2;
5925 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
5928 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
5929 // aResVec[SMDSEntity_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
5931 // SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
5932 // aResMap.insert(std::make_pair(sm,aResVec));
5937 //=============================================================================
5941 * \brief Event listener setting/unsetting _alwaysComputed flag to
5942 * submeshes of inferior levels to prevent their computing
5944 struct _EventListener : public SMESH_subMeshEventListener
5948 _EventListener(const string& algoName):
5949 SMESH_subMeshEventListener(/*isDeletable=*/true,"StdMeshers_Cartesian_3D::_EventListener"),
5952 // --------------------------------------------------------------------------------
5953 // setting/unsetting _alwaysComputed flag to submeshes of inferior levels
5955 static void setAlwaysComputed( const bool isComputed,
5956 SMESH_subMesh* subMeshOfSolid)
5958 SMESH_subMeshIteratorPtr smIt =
5959 subMeshOfSolid->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
5960 while ( smIt->more() )
5962 SMESH_subMesh* sm = smIt->next();
5963 sm->SetIsAlwaysComputed( isComputed );
5965 subMeshOfSolid->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
5968 // --------------------------------------------------------------------------------
5969 // unsetting _alwaysComputed flag if "Cartesian_3D" was removed
5971 virtual void ProcessEvent(const int /*event*/,
5972 const int eventType,
5973 SMESH_subMesh* subMeshOfSolid,
5974 SMESH_subMeshEventListenerData* /*data*/,
5975 const SMESH_Hypothesis* /*hyp*/ = 0)
5977 if ( eventType == SMESH_subMesh::COMPUTE_EVENT )
5979 setAlwaysComputed( subMeshOfSolid->GetComputeState() == SMESH_subMesh::COMPUTE_OK,
5984 SMESH_Algo* algo3D = subMeshOfSolid->GetAlgo();
5985 if ( !algo3D || _algoName != algo3D->GetName() )
5986 setAlwaysComputed( false, subMeshOfSolid );
5990 // --------------------------------------------------------------------------------
5991 // set the event listener
5993 static void SetOn( SMESH_subMesh* subMeshOfSolid, const string& algoName )
5995 subMeshOfSolid->SetEventListener( new _EventListener( algoName ),
6000 }; // struct _EventListener
6004 //================================================================================
6006 * \brief Sets event listener to submeshes if necessary
6007 * \param subMesh - submesh where algo is set
6008 * This method is called when a submesh gets HYP_OK algo_state.
6009 * After being set, event listener is notified on each event of a submesh.
6011 //================================================================================
6013 void StdMeshers_Cartesian_3D::SetEventListener(SMESH_subMesh* subMesh)
6015 _EventListener::SetOn( subMesh, GetName() );
6018 //================================================================================
6020 * \brief Set _alwaysComputed flag to submeshes of inferior levels to avoid their computing
6022 //================================================================================
6024 void StdMeshers_Cartesian_3D::setSubmeshesComputed(SMESH_Mesh& theMesh,
6025 const TopoDS_Shape& theShape)
6027 for ( TopExp_Explorer soExp( theShape, TopAbs_SOLID ); soExp.More(); soExp.Next() )
6028 _EventListener::setAlwaysComputed( true, theMesh.GetSubMesh( soExp.Current() ));