1 // Copyright (C) 2007-2016 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"
27 #include "SMDS_MeshNode.hxx"
28 #include "SMESHDS_Mesh.hxx"
29 #include "SMESH_Block.hxx"
30 #include "SMESH_Comment.hxx"
31 #include "SMESH_Mesh.hxx"
32 #include "SMESH_MesherHelper.hxx"
33 #include "SMESH_subMesh.hxx"
34 #include "SMESH_subMeshEventListener.hxx"
35 #include "StdMeshers_CartesianParameters3D.hxx"
37 #include <utilities.h>
38 #include <Utils_ExceptHandlers.hxx>
39 #include <Basics_OCCTVersion.hxx>
41 #include <GEOMUtils.hxx>
43 #include <BRepAdaptor_Curve.hxx>
44 #include <BRepAdaptor_Surface.hxx>
45 #include <BRepBndLib.hxx>
46 #include <BRepBuilderAPI_Copy.hxx>
47 #include <BRepBuilderAPI_MakeFace.hxx>
48 #include <BRepTools.hxx>
49 #include <BRepTopAdaptor_FClass2d.hxx>
50 #include <BRep_Builder.hxx>
51 #include <BRep_Tool.hxx>
52 #include <Bnd_B3d.hxx>
53 #include <Bnd_Box.hxx>
55 #include <GCPnts_UniformDeflection.hxx>
56 #include <Geom2d_BSplineCurve.hxx>
57 #include <Geom2d_BezierCurve.hxx>
58 #include <Geom2d_TrimmedCurve.hxx>
59 #include <GeomAPI_ProjectPointOnSurf.hxx>
60 #include <GeomLib.hxx>
61 #include <Geom_BSplineCurve.hxx>
62 #include <Geom_BSplineSurface.hxx>
63 #include <Geom_BezierCurve.hxx>
64 #include <Geom_BezierSurface.hxx>
65 #include <Geom_RectangularTrimmedSurface.hxx>
66 #include <Geom_TrimmedCurve.hxx>
67 #include <IntAna_IntConicQuad.hxx>
68 #include <IntAna_IntLinTorus.hxx>
69 #include <IntAna_Quadric.hxx>
70 #include <IntCurveSurface_TransitionOnCurve.hxx>
71 #include <IntCurvesFace_Intersector.hxx>
72 #include <Poly_Triangulation.hxx>
73 #include <Precision.hxx>
75 #include <TopExp_Explorer.hxx>
76 #include <TopLoc_Location.hxx>
77 #include <TopTools_IndexedMapOfShape.hxx>
78 #include <TopTools_MapOfShape.hxx>
80 #include <TopoDS_Compound.hxx>
81 #include <TopoDS_Face.hxx>
82 #include <TopoDS_TShape.hxx>
83 #include <gp_Cone.hxx>
84 #include <gp_Cylinder.hxx>
87 #include <gp_Pnt2d.hxx>
88 #include <gp_Sphere.hxx>
89 #include <gp_Torus.hxx>
95 #include <tbb/parallel_for.h>
96 //#include <tbb/enumerable_thread_specific.h>
105 //=============================================================================
109 //=============================================================================
111 StdMeshers_Cartesian_3D::StdMeshers_Cartesian_3D(int hypId, int studyId, SMESH_Gen * gen)
112 :SMESH_3D_Algo(hypId, studyId, gen)
114 _name = "Cartesian_3D";
115 _shapeType = (1 << TopAbs_SOLID); // 1 bit /shape type
116 _compatibleHypothesis.push_back("CartesianParameters3D");
118 _onlyUnaryInput = false; // to mesh all SOLIDs at once
119 _requireDiscreteBoundary = false; // 2D mesh not needed
120 _supportSubmeshes = false; // do not use any existing mesh
123 //=============================================================================
125 * Check presence of a hypothesis
127 //=============================================================================
129 bool StdMeshers_Cartesian_3D::CheckHypothesis (SMESH_Mesh& aMesh,
130 const TopoDS_Shape& aShape,
131 Hypothesis_Status& aStatus)
133 aStatus = SMESH_Hypothesis::HYP_MISSING;
135 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape);
136 list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
137 if ( h == hyps.end())
142 for ( ; h != hyps.end(); ++h )
144 if (( _hyp = dynamic_cast<const StdMeshers_CartesianParameters3D*>( *h )))
146 aStatus = _hyp->IsDefined() ? HYP_OK : HYP_BAD_PARAMETER;
151 return aStatus == HYP_OK;
158 //=============================================================================
159 // Definitions of internal utils
160 // --------------------------------------------------------------------------
162 Trans_TANGENT = IntCurveSurface_Tangent,
163 Trans_IN = IntCurveSurface_In,
164 Trans_OUT = IntCurveSurface_Out,
167 // --------------------------------------------------------------------------
169 * \brief Common data of any intersection between a Grid and a shape
171 struct B_IntersectPoint
173 mutable const SMDS_MeshNode* _node;
174 mutable vector< TGeomID > _faceIDs;
176 B_IntersectPoint(): _node(NULL) {}
177 void Add( const vector< TGeomID >& fIDs, const SMDS_MeshNode* n=0 ) const;
178 int HasCommonFace( const B_IntersectPoint * other, int avoidFace=-1 ) const;
179 bool IsOnFace( int faceID ) const;
180 virtual ~B_IntersectPoint() {}
182 // --------------------------------------------------------------------------
184 * \brief Data of intersection between a GridLine and a TopoDS_Face
186 struct F_IntersectPoint : public B_IntersectPoint
189 mutable Transition _transition;
190 mutable size_t _indexOnLine;
192 bool operator< ( const F_IntersectPoint& o ) const { return _paramOnLine < o._paramOnLine; }
194 // --------------------------------------------------------------------------
196 * \brief Data of intersection between GridPlanes and a TopoDS_EDGE
198 struct E_IntersectPoint : public B_IntersectPoint
204 // --------------------------------------------------------------------------
206 * \brief A line of the grid and its intersections with 2D geometry
211 double _length; // line length
212 multiset< F_IntersectPoint > _intPoints;
214 void RemoveExcessIntPoints( const double tol );
215 bool GetIsOutBefore( multiset< F_IntersectPoint >::iterator ip, bool prevIsOut );
217 // --------------------------------------------------------------------------
219 * \brief Planes of the grid used to find intersections of an EDGE with a hexahedron
224 vector< gp_XYZ > _origins; // origin points of all planes in one direction
225 vector< double > _zProjs; // projections of origins to _zNorm
227 // --------------------------------------------------------------------------
229 * \brief Iterator on the parallel grid lines of one direction
235 size_t _iVar1, _iVar2, _iConst;
236 string _name1, _name2, _nameConst;
238 LineIndexer( size_t sz1, size_t sz2, size_t sz3,
239 size_t iv1, size_t iv2, size_t iConst,
240 const string& nv1, const string& nv2, const string& nConst )
242 _size[0] = sz1; _size[1] = sz2; _size[2] = sz3;
243 _curInd[0] = _curInd[1] = _curInd[2] = 0;
244 _iVar1 = iv1; _iVar2 = iv2; _iConst = iConst;
245 _name1 = nv1; _name2 = nv2; _nameConst = nConst;
248 size_t I() const { return _curInd[0]; }
249 size_t J() const { return _curInd[1]; }
250 size_t K() const { return _curInd[2]; }
251 void SetIJK( size_t i, size_t j, size_t k )
253 _curInd[0] = i; _curInd[1] = j; _curInd[2] = k;
257 if ( ++_curInd[_iVar1] == _size[_iVar1] )
258 _curInd[_iVar1] = 0, ++_curInd[_iVar2];
260 bool More() const { return _curInd[_iVar2] < _size[_iVar2]; }
261 size_t LineIndex () const { return _curInd[_iVar1] + _curInd[_iVar2]* _size[_iVar1]; }
262 size_t LineIndex10 () const { return (_curInd[_iVar1] + 1 ) + _curInd[_iVar2]* _size[_iVar1]; }
263 size_t LineIndex01 () const { return _curInd[_iVar1] + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
264 size_t LineIndex11 () const { return (_curInd[_iVar1] + 1 ) + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
265 void SetIndexOnLine (size_t i) { _curInd[ _iConst ] = i; }
266 size_t NbLines() const { return _size[_iVar1] * _size[_iVar2]; }
268 // --------------------------------------------------------------------------
270 * \brief Container of GridLine's
274 vector< double > _coords[3]; // coordinates of grid nodes
275 gp_XYZ _axes [3]; // axis directions
276 vector< GridLine > _lines [3]; // in 3 directions
277 double _tol, _minCellSize;
279 gp_Mat _invB; // inverted basis of _axes
281 vector< const SMDS_MeshNode* > _nodes; // mesh nodes at grid nodes
282 vector< const F_IntersectPoint* > _gridIntP; // grid node intersection with geometry
284 list< E_IntersectPoint > _edgeIntP; // intersections with EDGEs
285 TopTools_IndexedMapOfShape _shapes;
287 SMESH_MesherHelper* _helper;
289 size_t CellIndex( size_t i, size_t j, size_t k ) const
291 return i + j*(_coords[0].size()-1) + k*(_coords[0].size()-1)*(_coords[1].size()-1);
293 size_t NodeIndex( size_t i, size_t j, size_t k ) const
295 return i + j*_coords[0].size() + k*_coords[0].size()*_coords[1].size();
297 size_t NodeIndexDX() const { return 1; }
298 size_t NodeIndexDY() const { return _coords[0].size(); }
299 size_t NodeIndexDZ() const { return _coords[0].size() * _coords[1].size(); }
301 LineIndexer GetLineIndexer(size_t iDir) const;
303 void SetCoordinates(const vector<double>& xCoords,
304 const vector<double>& yCoords,
305 const vector<double>& zCoords,
306 const double* axesDirs,
307 const Bnd_Box& bndBox );
308 void ComputeUVW(const gp_XYZ& p, double uvw[3]);
309 void ComputeNodes(SMESH_MesherHelper& helper);
311 // --------------------------------------------------------------------------
313 * \brief Intersector of TopoDS_Face with all GridLine's
315 struct FaceGridIntersector
321 IntCurvesFace_Intersector* _surfaceInt;
322 vector< std::pair< GridLine*, F_IntersectPoint > > _intersections;
324 FaceGridIntersector(): _grid(0), _surfaceInt(0) {}
327 void StoreIntersections()
329 for ( size_t i = 0; i < _intersections.size(); ++i )
331 multiset< F_IntersectPoint >::iterator ip =
332 _intersections[i].first->_intPoints.insert( _intersections[i].second );
333 ip->_faceIDs.reserve( 1 );
334 ip->_faceIDs.push_back( _faceID );
337 const Bnd_Box& GetFaceBndBox()
339 GetCurveFaceIntersector();
342 IntCurvesFace_Intersector* GetCurveFaceIntersector()
346 _surfaceInt = new IntCurvesFace_Intersector( _face, Precision::PConfusion() );
347 _bndBox = _surfaceInt->Bounding();
348 if ( _bndBox.IsVoid() )
349 BRepBndLib::Add (_face, _bndBox);
353 bool IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const;
355 // --------------------------------------------------------------------------
357 * \brief Intersector of a surface with a GridLine
359 struct FaceLineIntersector
362 double _u, _v, _w; // params on the face and the line
363 Transition _transition; // transition of at intersection (see IntCurveSurface.cdl)
364 Transition _transIn, _transOut; // IN and OUT transitions depending of face orientation
367 gp_Cylinder _cylinder;
371 IntCurvesFace_Intersector* _surfaceInt;
373 vector< F_IntersectPoint > _intPoints;
375 void IntersectWithPlane (const GridLine& gridLine);
376 void IntersectWithCylinder(const GridLine& gridLine);
377 void IntersectWithCone (const GridLine& gridLine);
378 void IntersectWithSphere (const GridLine& gridLine);
379 void IntersectWithTorus (const GridLine& gridLine);
380 void IntersectWithSurface (const GridLine& gridLine);
382 bool UVIsOnFace() const;
383 void addIntPoint(const bool toClassify=true);
384 bool isParamOnLineOK( const double linLength )
386 return -_tol < _w && _w < linLength + _tol;
388 FaceLineIntersector():_surfaceInt(0) {}
389 ~FaceLineIntersector() { if (_surfaceInt ) delete _surfaceInt; _surfaceInt = 0; }
391 // --------------------------------------------------------------------------
393 * \brief Class representing topology of the hexahedron and creating a mesh
394 * volume basing on analysis of hexahedron intersection with geometry
398 // --------------------------------------------------------------------------------
401 // --------------------------------------------------------------------------------
402 struct _Node //!< node either at a hexahedron corner or at intersection
404 const SMDS_MeshNode* _node; // mesh node at hexahedron corner
405 const B_IntersectPoint* _intPoint;
406 const _Face* _usedInFace;
408 _Node(const SMDS_MeshNode* n=0, const B_IntersectPoint* ip=0)
409 :_node(n), _intPoint(ip), _usedInFace(0) {}
410 const SMDS_MeshNode* Node() const
411 { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
412 const E_IntersectPoint* EdgeIntPnt() const
413 { return static_cast< const E_IntersectPoint* >( _intPoint ); }
414 bool IsUsedInFace( const _Face* polygon = 0 )
416 return polygon ? ( _usedInFace == polygon ) : bool( _usedInFace );
418 void Add( const E_IntersectPoint* ip )
423 else if ( !_intPoint->_node ) {
424 ip->Add( _intPoint->_faceIDs );
428 _intPoint->Add( ip->_faceIDs );
431 TGeomID IsLinked( const B_IntersectPoint* other,
432 TGeomID avoidFace=-1 ) const // returns id of a common face
434 return _intPoint ? _intPoint->HasCommonFace( other, avoidFace ) : 0;
436 bool IsOnFace( TGeomID faceID ) const // returns true if faceID is found
438 return _intPoint ? _intPoint->IsOnFace( faceID ) : false;
442 if ( const SMDS_MeshNode* n = Node() )
443 return SMESH_TNodeXYZ( n );
444 if ( const E_IntersectPoint* eip =
445 dynamic_cast< const E_IntersectPoint* >( _intPoint ))
447 return gp_Pnt( 1e100, 0, 0 );
449 TGeomID ShapeID() const
451 if ( const E_IntersectPoint* eip = dynamic_cast< const E_IntersectPoint* >( _intPoint ))
452 return eip->_shapeID;
456 // --------------------------------------------------------------------------------
457 struct _Link // link connecting two _Node's
460 _Face* _faces[2]; // polygons sharing a link
461 vector< const F_IntersectPoint* > _fIntPoints; // GridLine intersections with FACEs
462 vector< _Node* > _fIntNodes; // _Node's at _fIntPoints
463 vector< _Link > _splits;
464 _Link() { _faces[0] = 0; }
466 // --------------------------------------------------------------------------------
471 _OrientedLink( _Link* link=0, bool reverse=false ): _link(link), _reverse(reverse) {}
472 void Reverse() { _reverse = !_reverse; }
473 int NbResultLinks() const { return _link->_splits.size(); }
474 _OrientedLink ResultLink(int i) const
476 return _OrientedLink(&_link->_splits[_reverse ? NbResultLinks()-i-1 : i],_reverse);
478 _Node* FirstNode() const { return _link->_nodes[ _reverse ]; }
479 _Node* LastNode() const { return _link->_nodes[ !_reverse ]; }
480 operator bool() const { return _link; }
481 vector< TGeomID > GetNotUsedFace(const set<TGeomID>& usedIDs ) const // returns supporting FACEs
483 vector< TGeomID > faces;
484 const B_IntersectPoint *ip0, *ip1;
485 if (( ip0 = _link->_nodes[0]->_intPoint ) &&
486 ( ip1 = _link->_nodes[1]->_intPoint ))
488 for ( size_t i = 0; i < ip0->_faceIDs.size(); ++i )
489 if ( ip1->IsOnFace ( ip0->_faceIDs[i] ) &&
490 !usedIDs.count( ip0->_faceIDs[i] ) )
491 faces.push_back( ip0->_faceIDs[i] );
495 bool HasEdgeNodes() const
497 return ( dynamic_cast< const E_IntersectPoint* >( _link->_nodes[0]->_intPoint ) ||
498 dynamic_cast< const E_IntersectPoint* >( _link->_nodes[1]->_intPoint ));
502 return !_link->_faces[0] ? 0 : 1 + bool( _link->_faces[1] );
504 void AddFace( _Face* f )
506 if ( _link->_faces[0] )
508 _link->_faces[1] = f;
512 _link->_faces[0] = f;
513 _link->_faces[1] = 0;
516 void RemoveFace( _Face* f )
518 if ( !_link->_faces[0] ) return;
520 if ( _link->_faces[1] == f )
522 _link->_faces[1] = 0;
524 else if ( _link->_faces[0] == f )
526 _link->_faces[0] = 0;
527 if ( _link->_faces[1] )
529 _link->_faces[0] = _link->_faces[1];
530 _link->_faces[1] = 0;
535 // --------------------------------------------------------------------------------
538 vector< _OrientedLink > _links; // links on GridLine's
539 vector< _Link > _polyLinks; // links added to close a polygonal face
540 vector< _Node* > _eIntNodes; // nodes at intersection with EDGEs
541 bool IsPolyLink( const _OrientedLink& ol )
543 return _polyLinks.empty() ? false :
544 ( &_polyLinks[0] <= ol._link && ol._link <= &_polyLinks.back() );
546 void AddPolyLink(_Node* n0, _Node* n1, _Face* faceToFindEqual=0)
548 if ( faceToFindEqual && faceToFindEqual != this ) {
549 for ( size_t iL = 0; iL < faceToFindEqual->_polyLinks.size(); ++iL )
550 if ( faceToFindEqual->_polyLinks[iL]._nodes[0] == n1 &&
551 faceToFindEqual->_polyLinks[iL]._nodes[1] == n0 )
554 ( _OrientedLink( & faceToFindEqual->_polyLinks[iL], /*reverse=*/true ));
561 _polyLinks.push_back( l );
562 _links.push_back( _OrientedLink( &_polyLinks.back() ));
565 // --------------------------------------------------------------------------------
566 struct _volumeDef // holder of nodes of a volume mesh element
568 vector< _Node* > _nodes;
569 vector< int > _quantities;
570 typedef boost::shared_ptr<_volumeDef> Ptr;
571 void set( const vector< _Node* >& nodes,
572 const vector< int >& quant = vector< int >() )
573 { _nodes = nodes; _quantities = quant; }
574 void set( _Node** nodes, int nb )
575 { _nodes.assign( nodes, nodes + nb ); }
578 // topology of a hexahedron
581 _Link _hexLinks [12];
584 // faces resulted from hexahedron intersection
585 vector< _Face > _polygons;
587 // intresections with EDGEs
588 vector< const E_IntersectPoint* > _eIntPoints;
590 // additional nodes created at intersection points
591 vector< _Node > _intNodes;
593 // nodes inside the hexahedron (at VERTEXes)
594 vector< _Node* > _vIntNodes;
596 // computed volume elements
597 //vector< _volumeDef::Ptr > _volumeDefs;
598 _volumeDef _volumeDefs;
601 double _sizeThreshold, _sideLength[3];
602 int _nbCornerNodes, _nbFaceIntNodes, _nbBndNodes;
603 int _origNodeInd; // index of _hexNodes[0] node within the _grid
607 Hexahedron(const double sizeThreshold, Grid* grid);
608 int MakeElements(SMESH_MesherHelper& helper,
609 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
610 void ComputeElements();
611 void Init() { init( _i, _j, _k ); }
614 Hexahedron(const Hexahedron& other );
615 void init( size_t i, size_t j, size_t k );
616 void init( size_t i );
617 void addEdges(SMESH_MesherHelper& helper,
618 vector< Hexahedron* >& intersectedHex,
619 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
620 gp_Pnt findIntPoint( double u1, double proj1, double u2, double proj2,
621 double proj, BRepAdaptor_Curve& curve,
622 const gp_XYZ& axis, const gp_XYZ& origin );
623 int getEntity( const E_IntersectPoint* ip, int* facets, int& sub );
624 bool addIntersection( const E_IntersectPoint& ip,
625 vector< Hexahedron* >& hexes,
626 int ijk[], int dIJK[] );
627 bool findChain( _Node* n1, _Node* n2, _Face& quad, vector<_Node*>& chainNodes );
628 bool closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const;
629 bool findChainOnEdge( const vector< _OrientedLink >& splits,
630 const _OrientedLink& prevSplit,
631 const _OrientedLink& avoidSplit,
634 vector<_Node*>& chn);
635 int addElements(SMESH_MesherHelper& helper);
636 bool isOutPoint( _Link& link, int iP, SMESH_MesherHelper& helper ) const;
637 void sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID face);
638 bool isInHole() const;
639 bool checkPolyhedronSize() const;
644 bool debugDumpLink( _Link* link );
645 _Node* findEqualNode( vector< _Node* >& nodes,
646 const E_IntersectPoint* ip,
649 for ( size_t i = 0; i < nodes.size(); ++i )
650 if ( nodes[i]->EdgeIntPnt() == ip ||
651 nodes[i]->Point().SquareDistance( ip->_point ) <= tol2 )
655 bool isImplementEdges() const { return !_grid->_edgeIntP.empty(); }
656 bool isOutParam(const double uvw[3]) const;
660 // --------------------------------------------------------------------------
662 * \brief Hexahedron computing volumes in one thread
664 struct ParallelHexahedron
666 vector< Hexahedron* >& _hexVec;
667 ParallelHexahedron( vector< Hexahedron* >& hv ): _hexVec(hv) {}
668 void operator() ( const tbb::blocked_range<size_t>& r ) const
670 for ( size_t i = r.begin(); i != r.end(); ++i )
671 if ( Hexahedron* hex = _hexVec[ i ] )
672 hex->ComputeElements();
675 // --------------------------------------------------------------------------
677 * \brief Structure intersecting certain nb of faces with GridLine's in one thread
679 struct ParallelIntersector
681 vector< FaceGridIntersector >& _faceVec;
682 ParallelIntersector( vector< FaceGridIntersector >& faceVec): _faceVec(faceVec){}
683 void operator() ( const tbb::blocked_range<size_t>& r ) const
685 for ( size_t i = r.begin(); i != r.end(); ++i )
686 _faceVec[i].Intersect();
691 //=============================================================================
692 // Implementation of internal utils
693 //=============================================================================
695 * \brief adjust \a i to have \a val between values[i] and values[i+1]
697 inline void locateValue( int & i, double val, const vector<double>& values,
698 int& di, double tol )
700 //val += values[0]; // input \a val is measured from 0.
701 if ( i > (int) values.size()-2 )
704 while ( i+2 < (int) values.size() && val > values[ i+1 ])
706 while ( i > 0 && val < values[ i ])
709 if ( i > 0 && val - values[ i ] < tol )
711 else if ( i+2 < (int) values.size() && values[ i+1 ] - val < tol )
716 //=============================================================================
718 * Remove coincident intersection points
720 void GridLine::RemoveExcessIntPoints( const double tol )
722 if ( _intPoints.size() < 2 ) return;
724 set< Transition > tranSet;
725 multiset< F_IntersectPoint >::iterator ip1, ip2 = _intPoints.begin();
726 while ( ip2 != _intPoints.end() )
730 while ( ip2 != _intPoints.end() && ip2->_paramOnLine - ip1->_paramOnLine <= tol )
732 tranSet.insert( ip1->_transition );
733 tranSet.insert( ip2->_transition );
734 ip2->Add( ip1->_faceIDs );
735 _intPoints.erase( ip1 );
738 if ( tranSet.size() > 1 ) // points with different transition coincide
740 bool isIN = tranSet.count( Trans_IN );
741 bool isOUT = tranSet.count( Trans_OUT );
743 (*ip1)._transition = Trans_TANGENT;
745 (*ip1)._transition = isIN ? Trans_IN : Trans_OUT;
749 //================================================================================
751 * Return "is OUT" state for nodes before the given intersection point
753 bool GridLine::GetIsOutBefore( multiset< F_IntersectPoint >::iterator ip, bool prevIsOut )
755 if ( ip->_transition == Trans_IN )
757 if ( ip->_transition == Trans_OUT )
759 if ( ip->_transition == Trans_APEX )
761 // singularity point (apex of a cone)
762 if ( _intPoints.size() == 1 || ip == _intPoints.begin() )
764 multiset< F_IntersectPoint >::iterator ipBef = ip, ipAft = ++ip;
765 if ( ipAft == _intPoints.end() )
768 if ( ipBef->_transition != ipAft->_transition )
769 return ( ipBef->_transition == Trans_OUT );
770 return ( ipBef->_transition != Trans_OUT );
772 // _transition == Trans_TANGENT
775 //================================================================================
779 void B_IntersectPoint::Add( const vector< TGeomID >& fIDs,
780 const SMDS_MeshNode* n) const
782 if ( _faceIDs.empty() )
785 for ( size_t i = 0; i < fIDs.size(); ++i )
787 vector< TGeomID >::iterator it =
788 std::find( _faceIDs.begin(), _faceIDs.end(), fIDs[i] );
789 if ( it == _faceIDs.end() )
790 _faceIDs.push_back( fIDs[i] );
795 //================================================================================
797 * Returns index of a common face if any, else zero
799 int B_IntersectPoint::HasCommonFace( const B_IntersectPoint * other, int avoidFace ) const
802 for ( size_t i = 0; i < other->_faceIDs.size(); ++i )
803 if ( avoidFace != other->_faceIDs[i] &&
804 IsOnFace ( other->_faceIDs[i] ))
805 return other->_faceIDs[i];
808 //================================================================================
810 * Returns \c true if \a faceID in in this->_faceIDs
812 bool B_IntersectPoint::IsOnFace( int faceID ) const // returns true if faceID is found
814 vector< TGeomID >::const_iterator it =
815 std::find( _faceIDs.begin(), _faceIDs.end(), faceID );
816 return ( it != _faceIDs.end() );
818 //================================================================================
820 * Return an iterator on GridLine's in a given direction
822 LineIndexer Grid::GetLineIndexer(size_t iDir) const
824 const size_t indices[] = { 1,2,0, 0,2,1, 0,1,2 };
825 const string s [] = { "X", "Y", "Z" };
826 LineIndexer li( _coords[0].size(), _coords[1].size(), _coords[2].size(),
827 indices[iDir*3], indices[iDir*3+1], indices[iDir*3+2],
828 s[indices[iDir*3]], s[indices[iDir*3+1]], s[indices[iDir*3+2]]);
831 //=============================================================================
833 * Creates GridLine's of the grid
835 void Grid::SetCoordinates(const vector<double>& xCoords,
836 const vector<double>& yCoords,
837 const vector<double>& zCoords,
838 const double* axesDirs,
839 const Bnd_Box& shapeBox)
841 _coords[0] = xCoords;
842 _coords[1] = yCoords;
843 _coords[2] = zCoords;
845 _axes[0].SetCoord( axesDirs[0],
848 _axes[1].SetCoord( axesDirs[3],
851 _axes[2].SetCoord( axesDirs[6],
854 _axes[0].Normalize();
855 _axes[1].Normalize();
856 _axes[2].Normalize();
858 _invB.SetCols( _axes[0], _axes[1], _axes[2] );
862 _minCellSize = Precision::Infinite();
863 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
865 for ( size_t i = 1; i < _coords[ iDir ].size(); ++i )
867 double cellLen = _coords[ iDir ][ i ] - _coords[ iDir ][ i-1 ];
868 if ( cellLen < _minCellSize )
869 _minCellSize = cellLen;
872 if ( _minCellSize < Precision::Confusion() )
873 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
874 SMESH_Comment("Too small cell size: ") << _minCellSize );
875 _tol = _minCellSize / 1000.;
877 // attune grid extremities to shape bounding box
879 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
880 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
881 double* cP[6] = { &_coords[0].front(), &_coords[1].front(), &_coords[2].front(),
882 &_coords[0].back(), &_coords[1].back(), &_coords[2].back() };
883 for ( int i = 0; i < 6; ++i )
884 if ( fabs( sP[i] - *cP[i] ) < _tol )
885 *cP[i] = sP[i];// + _tol/1000. * ( i < 3 ? +1 : -1 );
887 for ( int iDir = 0; iDir < 3; ++iDir )
889 if ( _coords[iDir][0] - sP[iDir] > _tol )
891 _minCellSize = Min( _minCellSize, _coords[iDir][0] - sP[iDir] );
892 _coords[iDir].insert( _coords[iDir].begin(), sP[iDir] + _tol/1000.);
894 if ( sP[iDir+3] - _coords[iDir].back() > _tol )
896 _minCellSize = Min( _minCellSize, sP[iDir+3] - _coords[iDir].back() );
897 _coords[iDir].push_back( sP[iDir+3] - _tol/1000.);
900 _tol = _minCellSize / 1000.;
902 _origin = ( _coords[0][0] * _axes[0] +
903 _coords[1][0] * _axes[1] +
904 _coords[2][0] * _axes[2] );
907 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
909 LineIndexer li = GetLineIndexer( iDir );
910 _lines[iDir].resize( li.NbLines() );
911 double len = _coords[ iDir ].back() - _coords[iDir].front();
912 for ( ; li.More(); ++li )
914 GridLine& gl = _lines[iDir][ li.LineIndex() ];
915 gl._line.SetLocation( _coords[0][li.I()] * _axes[0] +
916 _coords[1][li.J()] * _axes[1] +
917 _coords[2][li.K()] * _axes[2] );
918 gl._line.SetDirection( _axes[ iDir ]);
923 //================================================================================
925 * Computes coordinates of a point in the grid CS
927 void Grid::ComputeUVW(const gp_XYZ& P, double UVW[3])
929 gp_XYZ p = P * _invB;
930 p.Coord( UVW[0], UVW[1], UVW[2] );
932 //================================================================================
936 void Grid::ComputeNodes(SMESH_MesherHelper& helper)
938 // state of each node of the grid relative to the geometry
939 const size_t nbGridNodes = _coords[0].size() * _coords[1].size() * _coords[2].size();
940 vector< bool > isNodeOut( nbGridNodes, false );
941 _nodes.resize( nbGridNodes, 0 );
942 _gridIntP.resize( nbGridNodes, NULL );
944 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
946 LineIndexer li = GetLineIndexer( iDir );
948 // find out a shift of node index while walking along a GridLine in this direction
949 li.SetIndexOnLine( 0 );
950 size_t nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
951 li.SetIndexOnLine( 1 );
952 const size_t nShift = NodeIndex( li.I(), li.J(), li.K() ) - nIndex0;
954 const vector<double> & coords = _coords[ iDir ];
955 for ( ; li.More(); ++li ) // loop on lines in iDir
957 li.SetIndexOnLine( 0 );
958 nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
960 GridLine& line = _lines[ iDir ][ li.LineIndex() ];
961 const gp_XYZ lineLoc = line._line.Location().XYZ();
962 const gp_XYZ lineDir = line._line.Direction().XYZ();
963 line.RemoveExcessIntPoints( _tol );
964 multiset< F_IntersectPoint >& intPnts = line._intPoints;
965 multiset< F_IntersectPoint >::iterator ip = intPnts.begin();
968 const double* nodeCoord = & coords[0];
969 const double* coord0 = nodeCoord;
970 const double* coordEnd = coord0 + coords.size();
971 double nodeParam = 0;
972 for ( ; ip != intPnts.end(); ++ip )
974 // set OUT state or just skip IN nodes before ip
975 if ( nodeParam < ip->_paramOnLine - _tol )
977 isOut = line.GetIsOutBefore( ip, isOut );
979 while ( nodeParam < ip->_paramOnLine - _tol )
982 isNodeOut[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = isOut;
983 if ( ++nodeCoord < coordEnd )
984 nodeParam = *nodeCoord - *coord0;
988 if ( nodeCoord == coordEnd ) break;
990 // create a mesh node on a GridLine at ip if it does not coincide with a grid node
991 if ( nodeParam > ip->_paramOnLine + _tol )
993 // li.SetIndexOnLine( 0 );
994 // double xyz[3] = { _coords[0][ li.I() ], _coords[1][ li.J() ], _coords[2][ li.K() ]};
995 // xyz[ li._iConst ] += ip->_paramOnLine;
996 gp_XYZ xyz = lineLoc + ip->_paramOnLine * lineDir;
997 ip->_node = helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() );
998 ip->_indexOnLine = nodeCoord-coord0-1;
1000 // create a mesh node at ip concident with a grid node
1003 int nodeIndex = nIndex0 + nShift * ( nodeCoord-coord0 );
1004 if ( !_nodes[ nodeIndex ] )
1006 //li.SetIndexOnLine( nodeCoord-coord0 );
1007 //double xyz[3] = { _coords[0][ li.I() ], _coords[1][ li.J() ], _coords[2][ li.K() ]};
1008 gp_XYZ xyz = lineLoc + nodeParam * lineDir;
1009 _nodes [ nodeIndex ] = helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1010 _gridIntP[ nodeIndex ] = & * ip;
1012 if ( _gridIntP[ nodeIndex ] )
1013 _gridIntP[ nodeIndex ]->Add( ip->_faceIDs );
1015 _gridIntP[ nodeIndex ] = & * ip;
1016 // ip->_node = _nodes[ nodeIndex ]; -- to differ from ip on links
1017 ip->_indexOnLine = nodeCoord-coord0;
1018 if ( ++nodeCoord < coordEnd )
1019 nodeParam = *nodeCoord - *coord0;
1022 // set OUT state to nodes after the last ip
1023 for ( ; nodeCoord < coordEnd; ++nodeCoord )
1024 isNodeOut[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = true;
1028 // Create mesh nodes at !OUT nodes of the grid
1030 for ( size_t z = 0; z < _coords[2].size(); ++z )
1031 for ( size_t y = 0; y < _coords[1].size(); ++y )
1032 for ( size_t x = 0; x < _coords[0].size(); ++x )
1034 size_t nodeIndex = NodeIndex( x, y, z );
1035 if ( !isNodeOut[ nodeIndex ] && !_nodes[ nodeIndex] )
1037 //_nodes[ nodeIndex ] = helper.AddNode( _coords[0][x], _coords[1][y], _coords[2][z] );
1038 gp_XYZ xyz = ( _coords[0][x] * _axes[0] +
1039 _coords[1][y] * _axes[1] +
1040 _coords[2][z] * _axes[2] );
1041 _nodes[ nodeIndex ] = helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1046 // check validity of transitions
1047 const char* trName[] = { "TANGENT", "IN", "OUT", "APEX" };
1048 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1050 LineIndexer li = GetLineIndexer( iDir );
1051 for ( ; li.More(); ++li )
1053 multiset< F_IntersectPoint >& intPnts = _lines[ iDir ][ li.LineIndex() ]._intPoints;
1054 if ( intPnts.empty() ) continue;
1055 if ( intPnts.size() == 1 )
1057 if ( intPnts.begin()->_transition != Trans_TANGENT &&
1058 intPnts.begin()->_transition != Trans_APEX )
1059 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1060 SMESH_Comment("Wrong SOLE transition of GridLine (")
1061 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1062 << ") along " << li._nameConst
1063 << ": " << trName[ intPnts.begin()->_transition] );
1067 if ( intPnts.begin()->_transition == Trans_OUT )
1068 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1069 SMESH_Comment("Wrong START transition of GridLine (")
1070 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1071 << ") along " << li._nameConst
1072 << ": " << trName[ intPnts.begin()->_transition ]);
1073 if ( intPnts.rbegin()->_transition == Trans_IN )
1074 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1075 SMESH_Comment("Wrong END transition of GridLine (")
1076 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1077 << ") along " << li._nameConst
1078 << ": " << trName[ intPnts.rbegin()->_transition ]);
1085 //=============================================================================
1087 * Intersects TopoDS_Face with all GridLine's
1089 void FaceGridIntersector::Intersect()
1091 FaceLineIntersector intersector;
1092 intersector._surfaceInt = GetCurveFaceIntersector();
1093 intersector._tol = _grid->_tol;
1094 intersector._transOut = _face.Orientation() == TopAbs_REVERSED ? Trans_IN : Trans_OUT;
1095 intersector._transIn = _face.Orientation() == TopAbs_REVERSED ? Trans_OUT : Trans_IN;
1097 typedef void (FaceLineIntersector::* PIntFun )(const GridLine& gridLine);
1098 PIntFun interFunction;
1100 bool isDirect = true;
1101 BRepAdaptor_Surface surf( _face );
1102 switch ( surf.GetType() ) {
1104 intersector._plane = surf.Plane();
1105 interFunction = &FaceLineIntersector::IntersectWithPlane;
1106 isDirect = intersector._plane.Direct();
1108 case GeomAbs_Cylinder:
1109 intersector._cylinder = surf.Cylinder();
1110 interFunction = &FaceLineIntersector::IntersectWithCylinder;
1111 isDirect = intersector._cylinder.Direct();
1114 intersector._cone = surf.Cone();
1115 interFunction = &FaceLineIntersector::IntersectWithCone;
1116 //isDirect = intersector._cone.Direct();
1118 case GeomAbs_Sphere:
1119 intersector._sphere = surf.Sphere();
1120 interFunction = &FaceLineIntersector::IntersectWithSphere;
1121 isDirect = intersector._sphere.Direct();
1124 intersector._torus = surf.Torus();
1125 interFunction = &FaceLineIntersector::IntersectWithTorus;
1126 //isDirect = intersector._torus.Direct();
1129 interFunction = &FaceLineIntersector::IntersectWithSurface;
1132 std::swap( intersector._transOut, intersector._transIn );
1134 _intersections.clear();
1135 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1137 if ( surf.GetType() == GeomAbs_Plane )
1139 // check if all lines in this direction are parallel to a plane
1140 if ( intersector._plane.Axis().IsNormal( _grid->_lines[iDir][0]._line.Position(),
1141 Precision::Angular()))
1143 // find out a transition, that is the same for all lines of a direction
1144 gp_Dir plnNorm = intersector._plane.Axis().Direction();
1145 gp_Dir lineDir = _grid->_lines[iDir][0]._line.Direction();
1146 intersector._transition =
1147 ( plnNorm * lineDir < 0 ) ? intersector._transIn : intersector._transOut;
1149 if ( surf.GetType() == GeomAbs_Cylinder )
1151 // check if all lines in this direction are parallel to a cylinder
1152 if ( intersector._cylinder.Axis().IsParallel( _grid->_lines[iDir][0]._line.Position(),
1153 Precision::Angular()))
1157 // intersect the grid lines with the face
1158 for ( size_t iL = 0; iL < _grid->_lines[iDir].size(); ++iL )
1160 GridLine& gridLine = _grid->_lines[iDir][iL];
1161 if ( _bndBox.IsOut( gridLine._line )) continue;
1163 intersector._intPoints.clear();
1164 (intersector.*interFunction)( gridLine ); // <- intersection with gridLine
1165 for ( size_t i = 0; i < intersector._intPoints.size(); ++i )
1166 _intersections.push_back( make_pair( &gridLine, intersector._intPoints[i] ));
1170 //================================================================================
1172 * Return true if (_u,_v) is on the face
1174 bool FaceLineIntersector::UVIsOnFace() const
1176 TopAbs_State state = _surfaceInt->ClassifyUVPoint(gp_Pnt2d( _u,_v ));
1177 return ( state == TopAbs_IN || state == TopAbs_ON );
1179 //================================================================================
1181 * Store an intersection if it is IN or ON the face
1183 void FaceLineIntersector::addIntPoint(const bool toClassify)
1185 if ( !toClassify || UVIsOnFace() )
1188 p._paramOnLine = _w;
1189 p._transition = _transition;
1190 _intPoints.push_back( p );
1193 //================================================================================
1195 * Intersect a line with a plane
1197 void FaceLineIntersector::IntersectWithPlane(const GridLine& gridLine)
1199 IntAna_IntConicQuad linPlane( gridLine._line, _plane, Precision::Angular());
1200 _w = linPlane.ParamOnConic(1);
1201 if ( isParamOnLineOK( gridLine._length ))
1203 ElSLib::Parameters(_plane, linPlane.Point(1) ,_u,_v);
1207 //================================================================================
1209 * Intersect a line with a cylinder
1211 void FaceLineIntersector::IntersectWithCylinder(const GridLine& gridLine)
1213 IntAna_IntConicQuad linCylinder( gridLine._line, _cylinder );
1214 if ( linCylinder.IsDone() && linCylinder.NbPoints() > 0 )
1216 _w = linCylinder.ParamOnConic(1);
1217 if ( linCylinder.NbPoints() == 1 )
1218 _transition = Trans_TANGENT;
1220 _transition = _w < linCylinder.ParamOnConic(2) ? _transIn : _transOut;
1221 if ( isParamOnLineOK( gridLine._length ))
1223 ElSLib::Parameters(_cylinder, linCylinder.Point(1) ,_u,_v);
1226 if ( linCylinder.NbPoints() > 1 )
1228 _w = linCylinder.ParamOnConic(2);
1229 if ( isParamOnLineOK( gridLine._length ))
1231 ElSLib::Parameters(_cylinder, linCylinder.Point(2) ,_u,_v);
1232 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
1238 //================================================================================
1240 * Intersect a line with a cone
1242 void FaceLineIntersector::IntersectWithCone (const GridLine& gridLine)
1244 IntAna_IntConicQuad linCone(gridLine._line,_cone);
1245 if ( !linCone.IsDone() ) return;
1247 gp_Vec du, dv, norm;
1248 for ( int i = 1; i <= linCone.NbPoints(); ++i )
1250 _w = linCone.ParamOnConic( i );
1251 if ( !isParamOnLineOK( gridLine._length )) continue;
1252 ElSLib::Parameters(_cone, linCone.Point(i) ,_u,_v);
1255 ElSLib::D1( _u, _v, _cone, P, du, dv );
1257 double normSize2 = norm.SquareMagnitude();
1258 if ( normSize2 > Precision::Angular() * Precision::Angular() )
1260 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
1261 cos /= sqrt( normSize2 );
1262 if ( cos < -Precision::Angular() )
1263 _transition = _transIn;
1264 else if ( cos > Precision::Angular() )
1265 _transition = _transOut;
1267 _transition = Trans_TANGENT;
1271 _transition = Trans_APEX;
1273 addIntPoint( /*toClassify=*/false);
1277 //================================================================================
1279 * Intersect a line with a sphere
1281 void FaceLineIntersector::IntersectWithSphere (const GridLine& gridLine)
1283 IntAna_IntConicQuad linSphere(gridLine._line,_sphere);
1284 if ( linSphere.IsDone() && linSphere.NbPoints() > 0 )
1286 _w = linSphere.ParamOnConic(1);
1287 if ( linSphere.NbPoints() == 1 )
1288 _transition = Trans_TANGENT;
1290 _transition = _w < linSphere.ParamOnConic(2) ? _transIn : _transOut;
1291 if ( isParamOnLineOK( gridLine._length ))
1293 ElSLib::Parameters(_sphere, linSphere.Point(1) ,_u,_v);
1296 if ( linSphere.NbPoints() > 1 )
1298 _w = linSphere.ParamOnConic(2);
1299 if ( isParamOnLineOK( gridLine._length ))
1301 ElSLib::Parameters(_sphere, linSphere.Point(2) ,_u,_v);
1302 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
1308 //================================================================================
1310 * Intersect a line with a torus
1312 void FaceLineIntersector::IntersectWithTorus (const GridLine& gridLine)
1314 IntAna_IntLinTorus linTorus(gridLine._line,_torus);
1315 if ( !linTorus.IsDone()) return;
1317 gp_Vec du, dv, norm;
1318 for ( int i = 1; i <= linTorus.NbPoints(); ++i )
1320 _w = linTorus.ParamOnLine( i );
1321 if ( !isParamOnLineOK( gridLine._length )) continue;
1322 linTorus.ParamOnTorus( i, _u,_v );
1325 ElSLib::D1( _u, _v, _torus, P, du, dv );
1327 double normSize = norm.Magnitude();
1328 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
1330 if ( cos < -Precision::Angular() )
1331 _transition = _transIn;
1332 else if ( cos > Precision::Angular() )
1333 _transition = _transOut;
1335 _transition = Trans_TANGENT;
1336 addIntPoint( /*toClassify=*/false);
1340 //================================================================================
1342 * Intersect a line with a non-analytical surface
1344 void FaceLineIntersector::IntersectWithSurface (const GridLine& gridLine)
1346 _surfaceInt->Perform( gridLine._line, 0.0, gridLine._length );
1347 if ( !_surfaceInt->IsDone() ) return;
1348 for ( int i = 1; i <= _surfaceInt->NbPnt(); ++i )
1350 _transition = Transition( _surfaceInt->Transition( i ) );
1351 _w = _surfaceInt->WParameter( i );
1352 addIntPoint(/*toClassify=*/false);
1355 //================================================================================
1357 * check if its face can be safely intersected in a thread
1359 bool FaceGridIntersector::IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const
1364 TopLoc_Location loc;
1365 Handle(Geom_Surface) surf = BRep_Tool::Surface( _face, loc );
1366 Handle(Geom_RectangularTrimmedSurface) ts =
1367 Handle(Geom_RectangularTrimmedSurface)::DownCast( surf );
1368 while( !ts.IsNull() ) {
1369 surf = ts->BasisSurface();
1370 ts = Handle(Geom_RectangularTrimmedSurface)::DownCast(surf);
1372 if ( surf->IsKind( STANDARD_TYPE(Geom_BSplineSurface )) ||
1373 surf->IsKind( STANDARD_TYPE(Geom_BezierSurface )))
1374 #if OCC_VERSION_MAJOR < 7
1375 if ( !noSafeTShapes.insert((const Standard_Transient*) _face.TShape() ).second )
1377 if ( !noSafeTShapes.insert( _face.TShape().get() ).second )
1382 TopExp_Explorer exp( _face, TopAbs_EDGE );
1383 for ( ; exp.More(); exp.Next() )
1385 bool edgeIsSafe = true;
1386 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1389 Handle(Geom_Curve) c = BRep_Tool::Curve( e, loc, f, l);
1392 Handle(Geom_TrimmedCurve) tc = Handle(Geom_TrimmedCurve)::DownCast(c);
1393 while( !tc.IsNull() ) {
1394 c = tc->BasisCurve();
1395 tc = Handle(Geom_TrimmedCurve)::DownCast(c);
1397 if ( c->IsKind( STANDARD_TYPE(Geom_BSplineCurve )) ||
1398 c->IsKind( STANDARD_TYPE(Geom_BezierCurve )))
1405 Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( e, surf, loc, f, l);
1408 Handle(Geom2d_TrimmedCurve) tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
1409 while( !tc.IsNull() ) {
1410 c2 = tc->BasisCurve();
1411 tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
1413 if ( c2->IsKind( STANDARD_TYPE(Geom2d_BSplineCurve )) ||
1414 c2->IsKind( STANDARD_TYPE(Geom2d_BezierCurve )))
1418 #if OCC_VERSION_MAJOR < 7
1419 if ( !edgeIsSafe && !noSafeTShapes.insert((const Standard_Transient*) e.TShape() ).second )
1421 if ( !edgeIsSafe && !noSafeTShapes.insert( e.TShape().get() ).second )
1427 //================================================================================
1429 * \brief Creates topology of the hexahedron
1431 Hexahedron::Hexahedron(const double sizeThreshold, Grid* grid)
1432 : _grid( grid ), _sizeThreshold( sizeThreshold ), _nbFaceIntNodes(0)
1434 _polygons.reserve(100); // to avoid reallocation;
1436 //set nodes shift within grid->_nodes from the node 000
1437 size_t dx = _grid->NodeIndexDX();
1438 size_t dy = _grid->NodeIndexDY();
1439 size_t dz = _grid->NodeIndexDZ();
1441 size_t i100 = i000 + dx;
1442 size_t i010 = i000 + dy;
1443 size_t i110 = i010 + dx;
1444 size_t i001 = i000 + dz;
1445 size_t i101 = i100 + dz;
1446 size_t i011 = i010 + dz;
1447 size_t i111 = i110 + dz;
1448 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V000 )] = i000;
1449 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V100 )] = i100;
1450 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V010 )] = i010;
1451 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V110 )] = i110;
1452 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V001 )] = i001;
1453 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V101 )] = i101;
1454 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V011 )] = i011;
1455 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V111 )] = i111;
1457 vector< int > idVec;
1458 // set nodes to links
1459 for ( int linkID = SMESH_Block::ID_Ex00; linkID <= SMESH_Block::ID_E11z; ++linkID )
1461 SMESH_Block::GetEdgeVertexIDs( linkID, idVec );
1462 _Link& link = _hexLinks[ SMESH_Block::ShapeIndex( linkID )];
1463 link._nodes[0] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[0] )];
1464 link._nodes[1] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[1] )];
1467 // set links to faces
1468 int interlace[4] = { 0, 3, 1, 2 }; // to walk by links around a face: { u0, 1v, u1, 0v }
1469 for ( int faceID = SMESH_Block::ID_Fxy0; faceID <= SMESH_Block::ID_F1yz; ++faceID )
1471 SMESH_Block::GetFaceEdgesIDs( faceID, idVec );
1472 _Face& quad = _hexQuads[ SMESH_Block::ShapeIndex( faceID )];
1473 bool revFace = ( faceID == SMESH_Block::ID_Fxy0 ||
1474 faceID == SMESH_Block::ID_Fx1z ||
1475 faceID == SMESH_Block::ID_F0yz );
1476 quad._links.resize(4);
1477 vector<_OrientedLink>::iterator frwLinkIt = quad._links.begin();
1478 vector<_OrientedLink>::reverse_iterator revLinkIt = quad._links.rbegin();
1479 for ( int i = 0; i < 4; ++i )
1481 bool revLink = revFace;
1482 if ( i > 1 ) // reverse links u1 and v0
1484 _OrientedLink& link = revFace ? *revLinkIt++ : *frwLinkIt++;
1485 link = _OrientedLink( & _hexLinks[ SMESH_Block::ShapeIndex( idVec[interlace[i]] )],
1490 //================================================================================
1492 * \brief Copy constructor
1494 Hexahedron::Hexahedron( const Hexahedron& other )
1495 :_grid( other._grid ), _sizeThreshold( other._sizeThreshold ), _nbFaceIntNodes(0)
1497 _polygons.reserve(100); // to avoid reallocation;
1499 for ( int i = 0; i < 8; ++i )
1500 _nodeShift[i] = other._nodeShift[i];
1502 for ( int i = 0; i < 12; ++i )
1504 const _Link& srcLink = other._hexLinks[ i ];
1505 _Link& tgtLink = this->_hexLinks[ i ];
1506 tgtLink._nodes[0] = _hexNodes + ( srcLink._nodes[0] - other._hexNodes );
1507 tgtLink._nodes[1] = _hexNodes + ( srcLink._nodes[1] - other._hexNodes );
1510 for ( int i = 0; i < 6; ++i )
1512 const _Face& srcQuad = other._hexQuads[ i ];
1513 _Face& tgtQuad = this->_hexQuads[ i ];
1514 tgtQuad._links.resize(4);
1515 for ( int j = 0; j < 4; ++j )
1517 const _OrientedLink& srcLink = srcQuad._links[ j ];
1518 _OrientedLink& tgtLink = tgtQuad._links[ j ];
1519 tgtLink._reverse = srcLink._reverse;
1520 tgtLink._link = _hexLinks + ( srcLink._link - other._hexLinks );
1525 //================================================================================
1527 * \brief Initializes its data by given grid cell
1529 void Hexahedron::init( size_t i, size_t j, size_t k )
1531 _i = i; _j = j; _k = k;
1532 // set nodes of grid to nodes of the hexahedron and
1533 // count nodes at hexahedron corners located IN and ON geometry
1534 _nbCornerNodes = _nbBndNodes = 0;
1535 _origNodeInd = _grid->NodeIndex( i,j,k );
1536 for ( int iN = 0; iN < 8; ++iN )
1538 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _nodeShift[iN] ];
1539 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _nodeShift[iN] ];
1540 _nbCornerNodes += bool( _hexNodes[iN]._node );
1541 _nbBndNodes += bool( _hexNodes[iN]._intPoint );
1543 _sideLength[0] = _grid->_coords[0][i+1] - _grid->_coords[0][i];
1544 _sideLength[1] = _grid->_coords[1][j+1] - _grid->_coords[1][j];
1545 _sideLength[2] = _grid->_coords[2][k+1] - _grid->_coords[2][k];
1550 if ( _nbFaceIntNodes + _eIntPoints.size() > 0 &&
1551 _nbFaceIntNodes + _nbCornerNodes + _eIntPoints.size() > 3)
1553 _intNodes.reserve( 3 * _nbBndNodes + _nbFaceIntNodes + _eIntPoints.size() );
1555 // this method can be called in parallel, so use own helper
1556 SMESH_MesherHelper helper( *_grid->_helper->GetMesh() );
1558 // create sub-links (_splits) by splitting links with _fIntPoints
1560 for ( int iLink = 0; iLink < 12; ++iLink )
1562 _Link& link = _hexLinks[ iLink ];
1563 link._fIntNodes.resize( link._fIntPoints.size() );
1564 for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
1566 _intNodes.push_back( _Node( 0, link._fIntPoints[i] ));
1567 link._fIntNodes[ i ] = & _intNodes.back();
1570 link._splits.clear();
1571 split._nodes[ 0 ] = link._nodes[0];
1572 bool isOut = ( ! link._nodes[0]->Node() );
1573 bool checkTransition;
1574 for ( size_t i = 0; i < link._fIntNodes.size(); ++i )
1576 const bool isGridNode = ( ! link._fIntNodes[i]->Node() );
1577 if ( !isGridNode ) // intersection non-coincident with a grid node
1579 if ( split._nodes[ 0 ]->Node() && !isOut )
1581 split._nodes[ 1 ] = link._fIntNodes[i];
1582 link._splits.push_back( split );
1584 split._nodes[ 0 ] = link._fIntNodes[i];
1585 checkTransition = true;
1587 else // FACE intersection coincident with a grid node (at link ends)
1589 checkTransition = ( i == 0 && link._nodes[0]->Node() );
1591 if ( checkTransition )
1593 if ( link._fIntPoints[i]->_faceIDs.size() > 1 || _eIntPoints.size() > 0 )
1594 isOut = isOutPoint( link, i, helper );
1596 switch ( link._fIntPoints[i]->_transition ) {
1597 case Trans_OUT: isOut = true; break;
1598 case Trans_IN : isOut = false; break;
1600 isOut = isOutPoint( link, i, helper );
1604 if ( link._nodes[ 1 ]->Node() && split._nodes[ 0 ]->Node() && !isOut )
1606 split._nodes[ 1 ] = link._nodes[1];
1607 link._splits.push_back( split );
1611 // Create _Node's at intersections with EDGEs.
1613 const double tol2 = _grid->_tol * _grid->_tol;
1614 int facets[3], nbFacets, subEntity;
1616 for ( size_t iP = 0; iP < _eIntPoints.size(); ++iP )
1618 nbFacets = getEntity( _eIntPoints[iP], facets, subEntity );
1619 _Node* equalNode = 0;
1620 switch( nbFacets ) {
1621 case 1: // in a _Face
1623 _Face& quad = _hexQuads[ facets[0] - SMESH_Block::ID_FirstF ];
1624 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
1626 equalNode->Add( _eIntPoints[ iP ] );
1629 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
1630 quad._eIntNodes.push_back( & _intNodes.back() );
1634 case 2: // on a _Link
1636 _Link& link = _hexLinks[ subEntity - SMESH_Block::ID_FirstE ];
1637 if ( link._splits.size() > 0 )
1639 equalNode = findEqualNode( link._fIntNodes, _eIntPoints[ iP ], tol2 );
1641 equalNode->Add( _eIntPoints[ iP ] );
1645 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
1646 for ( int iF = 0; iF < 2; ++iF )
1648 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
1649 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
1651 equalNode->Add( _eIntPoints[ iP ] );
1654 quad._eIntNodes.push_back( & _intNodes.back() );
1660 case 3: // at a corner
1662 _Node& node = _hexNodes[ subEntity - SMESH_Block::ID_FirstV ];
1663 if ( node.Node() > 0 )
1665 if ( node._intPoint )
1666 node._intPoint->Add( _eIntPoints[ iP ]->_faceIDs, _eIntPoints[ iP ]->_node );
1670 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
1671 for ( int iF = 0; iF < 3; ++iF )
1673 _Face& quad = _hexQuads[ facets[iF] - SMESH_Block::ID_FirstF ];
1674 equalNode = findEqualNode( quad._eIntNodes, _eIntPoints[ iP ], tol2 );
1676 equalNode->Add( _eIntPoints[ iP ] );
1679 quad._eIntNodes.push_back( & _intNodes.back() );
1685 } // switch( nbFacets )
1687 if ( nbFacets == 0 ||
1688 _grid->_shapes( _eIntPoints[ iP ]->_shapeID ).ShapeType() == TopAbs_VERTEX )
1690 equalNode = findEqualNode( _vIntNodes, _eIntPoints[ iP ], tol2 );
1692 equalNode->Add( _eIntPoints[ iP ] );
1694 else if ( nbFacets == 0 ) {
1695 if ( _intNodes.empty() || _intNodes.back().EdgeIntPnt() != _eIntPoints[ iP ])
1696 _intNodes.push_back( _Node( 0, _eIntPoints[ iP ]));
1697 _vIntNodes.push_back( & _intNodes.back() );
1700 } // loop on _eIntPoints
1702 else if ( 3 < _nbCornerNodes && _nbCornerNodes < 8 ) // _nbFaceIntNodes == 0
1705 // create sub-links (_splits) of whole links
1706 for ( int iLink = 0; iLink < 12; ++iLink )
1708 _Link& link = _hexLinks[ iLink ];
1709 link._splits.clear();
1710 if ( link._nodes[ 0 ]->Node() && link._nodes[ 1 ]->Node() )
1712 split._nodes[ 0 ] = link._nodes[0];
1713 split._nodes[ 1 ] = link._nodes[1];
1714 link._splits.push_back( split );
1720 //================================================================================
1722 * \brief Initializes its data by given grid cell (countered from zero)
1724 void Hexahedron::init( size_t iCell )
1726 size_t iNbCell = _grid->_coords[0].size() - 1;
1727 size_t jNbCell = _grid->_coords[1].size() - 1;
1728 _i = iCell % iNbCell;
1729 _j = ( iCell % ( iNbCell * jNbCell )) / iNbCell;
1730 _k = iCell / iNbCell / jNbCell;
1734 //================================================================================
1736 * \brief Compute mesh volumes resulted from intersection of the Hexahedron
1738 void Hexahedron::ComputeElements()
1742 int nbIntersections = _nbFaceIntNodes + _eIntPoints.size();
1743 if ( _nbCornerNodes + nbIntersections < 4 )
1746 if ( _nbBndNodes == _nbCornerNodes && nbIntersections == 0 && isInHole() )
1750 _polygons.reserve( 20 );
1752 // Create polygons from quadrangles
1753 // --------------------------------
1755 vector< _OrientedLink > splits;
1756 vector<_Node*> chainNodes;
1757 _Face* coplanarPolyg;
1759 bool hasEdgeIntersections = !_eIntPoints.empty();
1761 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
1763 _Face& quad = _hexQuads[ iF ] ;
1765 _polygons.resize( _polygons.size() + 1 );
1766 _Face* polygon = &_polygons.back();
1767 polygon->_polyLinks.reserve( 20 );
1770 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
1771 for ( int iS = 0; iS < quad._links[ iE ].NbResultLinks(); ++iS )
1772 splits.push_back( quad._links[ iE ].ResultLink( iS ));
1774 // add splits of links to a polygon and add _polyLinks to make
1775 // polygon's boundary closed
1777 int nbSplits = splits.size();
1778 if (( nbSplits == 1 ) &&
1779 ( quad._eIntNodes.empty() ||
1780 splits[0].FirstNode()->IsLinked( splits[0].LastNode()->_intPoint )))
1781 //( quad._eIntNodes.empty() || _nbCornerNodes + nbIntersections > 6 ))
1785 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
1786 if ( quad._eIntNodes[ iP ]->IsUsedInFace( polygon ))
1787 quad._eIntNodes[ iP ]->_usedInFace = 0;
1789 size_t nbUsedEdgeNodes = 0;
1790 _Face* prevPolyg = 0; // polygon previously created from this quad
1792 while ( nbSplits > 0 )
1795 while ( !splits[ iS ] )
1798 if ( !polygon->_links.empty() )
1800 _polygons.resize( _polygons.size() + 1 );
1801 polygon = &_polygons.back();
1802 polygon->_polyLinks.reserve( 20 );
1804 polygon->_links.push_back( splits[ iS ] );
1805 splits[ iS++ ]._link = 0;
1808 _Node* nFirst = polygon->_links.back().FirstNode();
1809 _Node *n1,*n2 = polygon->_links.back().LastNode();
1810 for ( ; nFirst != n2 && iS < splits.size(); ++iS )
1812 _OrientedLink& split = splits[ iS ];
1813 if ( !split ) continue;
1815 n1 = split.FirstNode();
1818 n1->_intPoint->_faceIDs.size() > 1 )
1820 // n1 is at intersection with EDGE
1821 if ( findChainOnEdge( splits, polygon->_links.back(), split, iS, quad, chainNodes ))
1823 for ( size_t i = 1; i < chainNodes.size(); ++i )
1824 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
1825 prevPolyg = polygon;
1826 n2 = chainNodes.back();
1830 else if ( n1 != n2 )
1832 // try to connect to intersections with EDGEs
1833 if ( quad._eIntNodes.size() > nbUsedEdgeNodes &&
1834 findChain( n2, n1, quad, chainNodes ))
1836 for ( size_t i = 1; i < chainNodes.size(); ++i )
1838 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i] );
1839 nbUsedEdgeNodes += ( chainNodes[i]->IsUsedInFace( polygon ));
1841 if ( chainNodes.back() != n1 )
1843 n2 = chainNodes.back();
1848 // try to connect to a split ending on the same FACE
1851 _OrientedLink foundSplit;
1852 for ( size_t i = iS; i < splits.size() && !foundSplit; ++i )
1853 if (( foundSplit = splits[ i ]) &&
1854 ( n2->IsLinked( foundSplit.FirstNode()->_intPoint )))
1860 foundSplit._link = 0;
1864 if ( n2 != foundSplit.FirstNode() )
1866 polygon->AddPolyLink( n2, foundSplit.FirstNode() );
1867 n2 = foundSplit.FirstNode();
1873 if ( n2->IsLinked( nFirst->_intPoint ))
1875 polygon->AddPolyLink( n2, n1, prevPolyg );
1878 } // if ( n1 != n2 )
1880 polygon->_links.push_back( split );
1883 n2 = polygon->_links.back().LastNode();
1887 if ( nFirst != n2 ) // close a polygon
1889 if ( !findChain( n2, nFirst, quad, chainNodes ))
1891 if ( !closePolygon( polygon, chainNodes ))
1892 if ( !isImplementEdges() )
1893 chainNodes.push_back( nFirst );
1895 for ( size_t i = 1; i < chainNodes.size(); ++i )
1897 polygon->AddPolyLink( chainNodes[i-1], chainNodes[i], prevPolyg );
1898 nbUsedEdgeNodes += bool( chainNodes[i]->IsUsedInFace( polygon ));
1902 if ( polygon->_links.size() < 3 && nbSplits > 0 )
1904 polygon->_polyLinks.clear();
1905 polygon->_links.clear();
1907 } // while ( nbSplits > 0 )
1909 if ( polygon->_links.size() < 3 )
1911 _polygons.pop_back();
1913 } // loop on 6 hexahedron sides
1915 // Create polygons closing holes in a polyhedron
1916 // ----------------------------------------------
1918 // clear _usedInFace
1919 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
1920 _intNodes[ iN ]._usedInFace = 0;
1922 // add polygons to their links and mark used nodes
1923 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
1925 _Face& polygon = _polygons[ iP ];
1926 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
1928 polygon._links[ iL ].AddFace( &polygon );
1929 polygon._links[ iL ].FirstNode()->_usedInFace = &polygon;
1933 vector< _OrientedLink* > freeLinks;
1934 freeLinks.reserve(20);
1935 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
1937 _Face& polygon = _polygons[ iP ];
1938 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
1939 if ( polygon._links[ iL ].NbFaces() < 2 )
1940 freeLinks.push_back( & polygon._links[ iL ]);
1942 int nbFreeLinks = freeLinks.size();
1943 if ( nbFreeLinks == 1 ) return;
1945 // put not used intersection nodes to _vIntNodes
1946 int nbVertexNodes = 0; // nb not used vertex nodes
1948 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
1949 nbVertexNodes += ( !_vIntNodes[ iN ]->IsUsedInFace() );
1951 const double tol = 1e-3 * Min( Min( _sideLength[0], _sideLength[1] ), _sideLength[0] );
1952 for ( size_t iN = _nbFaceIntNodes; iN < _intNodes.size(); ++iN )
1954 if ( _intNodes[ iN ].IsUsedInFace() ) continue;
1955 if ( dynamic_cast< const F_IntersectPoint* >( _intNodes[ iN ]._intPoint )) continue;
1957 findEqualNode( _vIntNodes, _intNodes[ iN ].EdgeIntPnt(), tol*tol );
1960 _vIntNodes.push_back( &_intNodes[ iN ]);
1966 set<TGeomID> usedFaceIDs;
1967 vector< TGeomID > faces;
1968 TGeomID curFace = 0;
1969 const size_t nbQuadPolygons = _polygons.size();
1970 E_IntersectPoint ipTmp;
1972 // create polygons by making closed chains of free links
1973 size_t iPolygon = _polygons.size();
1974 while ( nbFreeLinks > 0 )
1976 if ( iPolygon == _polygons.size() )
1978 _polygons.resize( _polygons.size() + 1 );
1979 _polygons[ iPolygon ]._polyLinks.reserve( 20 );
1980 _polygons[ iPolygon ]._links.reserve( 20 );
1982 _Face& polygon = _polygons[ iPolygon ];
1984 _OrientedLink* curLink = 0;
1986 if (( !hasEdgeIntersections ) ||
1987 ( nbFreeLinks < 4 && nbVertexNodes == 0 ))
1989 // get a remaining link to start from
1990 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
1991 if (( curLink = freeLinks[ iL ] ))
1992 freeLinks[ iL ] = 0;
1993 polygon._links.push_back( *curLink );
1997 // find all links connected to curLink
1998 curNode = curLink->FirstNode();
2000 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2001 if ( freeLinks[ iL ] && freeLinks[ iL ]->LastNode() == curNode )
2003 curLink = freeLinks[ iL ];
2004 freeLinks[ iL ] = 0;
2006 polygon._links.push_back( *curLink );
2008 } while ( curLink );
2010 else // there are intersections with EDGEs
2012 // get a remaining link to start from, one lying on minimal nb of FACEs
2014 typedef pair< TGeomID, int > TFaceOfLink;
2015 TFaceOfLink faceOfLink( -1, -1 );
2016 TFaceOfLink facesOfLink[3] = { faceOfLink, faceOfLink, faceOfLink };
2017 for ( size_t iL = 0; iL < freeLinks.size(); ++iL )
2018 if ( freeLinks[ iL ] )
2020 faces = freeLinks[ iL ]->GetNotUsedFace( usedFaceIDs );
2021 if ( faces.size() == 1 )
2023 faceOfLink = TFaceOfLink( faces[0], iL );
2024 if ( !freeLinks[ iL ]->HasEdgeNodes() )
2026 facesOfLink[0] = faceOfLink;
2028 else if ( facesOfLink[0].first < 0 )
2030 faceOfLink = TFaceOfLink(( faces.empty() ? -1 : faces[0]), iL );
2031 facesOfLink[ 1 + faces.empty() ] = faceOfLink;
2034 for ( int i = 0; faceOfLink.first < 0 && i < 3; ++i )
2035 faceOfLink = facesOfLink[i];
2037 if ( faceOfLink.first < 0 ) // all faces used
2039 for ( size_t iL = 0; iL < freeLinks.size() && faceOfLink.first < 1; ++iL )
2040 if (( curLink = freeLinks[ iL ]))
2043 curLink->FirstNode()->IsLinked( curLink->LastNode()->_intPoint );
2044 faceOfLink.second = iL;
2046 usedFaceIDs.clear();
2048 curFace = faceOfLink.first;
2049 curLink = freeLinks[ faceOfLink.second ];
2050 freeLinks[ faceOfLink.second ] = 0;
2052 usedFaceIDs.insert( curFace );
2053 polygon._links.push_back( *curLink );
2056 // find all links lying on a curFace
2059 // go forward from curLink
2060 curNode = curLink->LastNode();
2062 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2063 if ( freeLinks[ iL ] &&
2064 freeLinks[ iL ]->FirstNode() == curNode &&
2065 freeLinks[ iL ]->LastNode()->IsOnFace( curFace ))
2067 curLink = freeLinks[ iL ];
2068 freeLinks[ iL ] = 0;
2069 polygon._links.push_back( *curLink );
2072 } while ( curLink );
2074 std::reverse( polygon._links.begin(), polygon._links.end() );
2076 curLink = & polygon._links.back();
2079 // go backward from curLink
2080 curNode = curLink->FirstNode();
2082 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2083 if ( freeLinks[ iL ] &&
2084 freeLinks[ iL ]->LastNode() == curNode &&
2085 freeLinks[ iL ]->FirstNode()->IsOnFace( curFace ))
2087 curLink = freeLinks[ iL ];
2088 freeLinks[ iL ] = 0;
2089 polygon._links.push_back( *curLink );
2092 } while ( curLink );
2094 curNode = polygon._links.back().FirstNode();
2096 if ( polygon._links[0].LastNode() != curNode )
2098 if ( nbVertexNodes > 0 )
2100 // add links with _vIntNodes if not already used
2102 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
2103 if ( !_vIntNodes[ iN ]->IsUsedInFace() &&
2104 _vIntNodes[ iN ]->IsOnFace( curFace ))
2106 _vIntNodes[ iN ]->_usedInFace = &polygon;
2107 chainNodes.push_back( _vIntNodes[ iN ] );
2109 if ( chainNodes.size() > 1 )
2111 sortVertexNodes( chainNodes, curNode, curFace );
2113 for ( size_t i = 0; i < chainNodes.size(); ++i )
2115 polygon.AddPolyLink( chainNodes[ i ], curNode );
2116 curNode = chainNodes[ i ];
2117 freeLinks.push_back( &polygon._links.back() );
2120 nbVertexNodes -= chainNodes.size();
2122 // if ( polygon._links.size() > 1 )
2124 polygon.AddPolyLink( polygon._links[0].LastNode(), curNode );
2125 freeLinks.push_back( &polygon._links.back() );
2129 } // if there are intersections with EDGEs
2131 if ( polygon._links.size() < 2 ||
2132 polygon._links[0].LastNode() != polygon._links.back().FirstNode() )
2133 return; // closed polygon not found -> invalid polyhedron
2135 if ( polygon._links.size() == 2 )
2137 if ( freeLinks.back() == &polygon._links.back() )
2139 freeLinks.pop_back();
2142 if ( polygon._links.front().NbFaces() > 0 )
2143 polygon._links.back().AddFace( polygon._links.front()._link->_faces[0] );
2144 if ( polygon._links.back().NbFaces() > 0 )
2145 polygon._links.front().AddFace( polygon._links.back()._link->_faces[0] );
2147 if ( iPolygon == _polygons.size()-1 )
2148 _polygons.pop_back();
2150 else // polygon._links.size() >= 2
2152 // add polygon to its links
2153 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
2155 polygon._links[ iL ].AddFace( &polygon );
2156 polygon._links[ iL ].Reverse();
2158 if ( /*hasEdgeIntersections &&*/ iPolygon == _polygons.size() - 1 )
2160 // check that a polygon does not lie on a hexa side
2162 for ( size_t iL = 0; iL < polygon._links.size() && !coplanarPolyg; ++iL )
2164 if ( polygon._links[ iL ].NbFaces() < 2 )
2165 continue; // it's a just added free link
2166 // look for a polygon made on a hexa side and sharing
2167 // two or more haxa links
2169 coplanarPolyg = polygon._links[ iL ]._link->_faces[0];
2170 for ( iL2 = iL + 1; iL2 < polygon._links.size(); ++iL2 )
2171 if ( polygon._links[ iL2 ]._link->_faces[0] == coplanarPolyg &&
2172 !coplanarPolyg->IsPolyLink( polygon._links[ iL ]) &&
2173 !coplanarPolyg->IsPolyLink( polygon._links[ iL2 ]) &&
2174 coplanarPolyg < & _polygons[ nbQuadPolygons ])
2176 if ( iL2 == polygon._links.size() )
2179 if ( coplanarPolyg ) // coplanar polygon found
2181 freeLinks.resize( freeLinks.size() - polygon._polyLinks.size() );
2182 nbFreeLinks -= polygon._polyLinks.size();
2184 // an E_IntersectPoint used to mark nodes of coplanarPolyg
2185 // as lying on curFace while they are not at intersection with geometry
2186 ipTmp._faceIDs.resize(1);
2187 ipTmp._faceIDs[0] = curFace;
2189 // fill freeLinks with links not shared by coplanarPolyg and polygon
2190 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
2191 if ( polygon._links[ iL ]._link->_faces[1] &&
2192 polygon._links[ iL ]._link->_faces[0] != coplanarPolyg )
2194 _Face* p = polygon._links[ iL ]._link->_faces[0];
2195 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
2196 if ( p->_links[ iL2 ]._link == polygon._links[ iL ]._link )
2198 freeLinks.push_back( & p->_links[ iL2 ] );
2200 freeLinks.back()->RemoveFace( &polygon );
2204 for ( size_t iL = 0; iL < coplanarPolyg->_links.size(); ++iL )
2205 if ( coplanarPolyg->_links[ iL ]._link->_faces[1] &&
2206 coplanarPolyg->_links[ iL ]._link->_faces[1] != &polygon )
2208 _Face* p = coplanarPolyg->_links[ iL ]._link->_faces[0];
2209 if ( p == coplanarPolyg )
2210 p = coplanarPolyg->_links[ iL ]._link->_faces[1];
2211 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
2212 if ( p->_links[ iL2 ]._link == coplanarPolyg->_links[ iL ]._link )
2214 // set links of coplanarPolyg in place of used freeLinks
2215 // to re-create coplanarPolyg next
2217 for ( ; iL3 < freeLinks.size() && freeLinks[ iL3 ]; ++iL3 );
2218 if ( iL3 < freeLinks.size() )
2219 freeLinks[ iL3 ] = ( & p->_links[ iL2 ] );
2221 freeLinks.push_back( & p->_links[ iL2 ] );
2223 freeLinks[ iL3 ]->RemoveFace( coplanarPolyg );
2224 // mark nodes of coplanarPolyg as lying on curFace
2225 for ( int iN = 0; iN < 2; ++iN )
2227 _Node* n = freeLinks[ iL3 ]->_link->_nodes[ iN ];
2228 if ( n->_intPoint ) n->_intPoint->Add( ipTmp._faceIDs );
2229 else n->_intPoint = &ipTmp;
2234 // set coplanarPolyg to be re-created next
2235 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
2236 if ( coplanarPolyg == & _polygons[ iP ] )
2239 _polygons[ iPolygon ]._links.clear();
2240 _polygons[ iPolygon ]._polyLinks.clear();
2243 _polygons.pop_back();
2244 usedFaceIDs.erase( curFace );
2246 } // if ( coplanarPolyg )
2247 } // if ( hasEdgeIntersections ) - search for coplanarPolyg
2249 iPolygon = _polygons.size();
2251 } // end of case ( polygon._links.size() > 2 )
2252 } // while ( nbFreeLinks > 0 )
2254 if ( ! checkPolyhedronSize() )
2259 for ( size_t i = 0; i < 8; ++i )
2260 if ( _hexNodes[ i ]._intPoint == &ipTmp )
2261 _hexNodes[ i ]._intPoint = 0;
2263 // create a classic cell if possible
2266 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
2267 nbPolygons += (_polygons[ iF ]._links.size() > 0 );
2269 //const int nbNodes = _nbCornerNodes + nbIntersections;
2271 for ( size_t i = 0; i < 8; ++i )
2272 nbNodes += _hexNodes[ i ].IsUsedInFace();
2273 for ( size_t i = 0; i < _intNodes.size(); ++i )
2274 nbNodes += _intNodes[ i ].IsUsedInFace();
2276 bool isClassicElem = false;
2277 if ( nbNodes == 8 && nbPolygons == 6 ) isClassicElem = addHexa();
2278 else if ( nbNodes == 4 && nbPolygons == 4 ) isClassicElem = addTetra();
2279 else if ( nbNodes == 6 && nbPolygons == 5 ) isClassicElem = addPenta();
2280 else if ( nbNodes == 5 && nbPolygons == 5 ) isClassicElem = addPyra ();
2281 if ( !isClassicElem )
2283 _volumeDefs._nodes.clear();
2284 _volumeDefs._quantities.clear();
2286 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
2288 const size_t nbLinks = _polygons[ iF ]._links.size();
2289 if ( nbLinks == 0 ) continue;
2290 _volumeDefs._quantities.push_back( nbLinks );
2291 for ( size_t iL = 0; iL < nbLinks; ++iL )
2292 _volumeDefs._nodes.push_back( _polygons[ iF ]._links[ iL ].FirstNode() );
2296 //================================================================================
2298 * \brief Create elements in the mesh
2300 int Hexahedron::MakeElements(SMESH_MesherHelper& helper,
2301 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
2303 SMESHDS_Mesh* mesh = helper.GetMeshDS();
2305 size_t nbCells[3] = { _grid->_coords[0].size() - 1,
2306 _grid->_coords[1].size() - 1,
2307 _grid->_coords[2].size() - 1 };
2308 const size_t nbGridCells = nbCells[0] * nbCells[1] * nbCells[2];
2309 vector< Hexahedron* > allHexa( nbGridCells, 0 );
2312 // set intersection nodes from GridLine's to links of allHexa
2313 int i,j,k, iDirOther[3][2] = {{ 1,2 },{ 0,2 },{ 0,1 }};
2314 for ( int iDir = 0; iDir < 3; ++iDir )
2316 int dInd[4][3] = { {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} };
2317 dInd[1][ iDirOther[iDir][0] ] = -1;
2318 dInd[2][ iDirOther[iDir][1] ] = -1;
2319 dInd[3][ iDirOther[iDir][0] ] = -1; dInd[3][ iDirOther[iDir][1] ] = -1;
2320 // loop on GridLine's parallel to iDir
2321 LineIndexer lineInd = _grid->GetLineIndexer( iDir );
2322 for ( ; lineInd.More(); ++lineInd )
2324 GridLine& line = _grid->_lines[ iDir ][ lineInd.LineIndex() ];
2325 multiset< F_IntersectPoint >::const_iterator ip = line._intPoints.begin();
2326 for ( ; ip != line._intPoints.end(); ++ip )
2328 // if ( !ip->_node ) continue; // intersection at a grid node
2329 lineInd.SetIndexOnLine( ip->_indexOnLine );
2330 for ( int iL = 0; iL < 4; ++iL ) // loop on 4 cells sharing a link
2332 i = int(lineInd.I()) + dInd[iL][0];
2333 j = int(lineInd.J()) + dInd[iL][1];
2334 k = int(lineInd.K()) + dInd[iL][2];
2335 if ( i < 0 || i >= (int) nbCells[0] ||
2336 j < 0 || j >= (int) nbCells[1] ||
2337 k < 0 || k >= (int) nbCells[2] ) continue;
2339 const size_t hexIndex = _grid->CellIndex( i,j,k );
2340 Hexahedron *& hex = allHexa[ hexIndex ];
2343 hex = new Hexahedron( *this );
2349 const int iLink = iL + iDir * 4;
2350 hex->_hexLinks[iLink]._fIntPoints.push_back( &(*ip) );
2351 hex->_nbFaceIntNodes += bool( ip->_node );
2357 // implement geom edges into the mesh
2358 addEdges( helper, allHexa, edge2faceIDsMap );
2360 // add not split hexadrons to the mesh
2362 vector< Hexahedron* > intHexa( nbIntHex, (Hexahedron*) NULL );
2363 for ( size_t i = 0; i < allHexa.size(); ++i )
2365 Hexahedron * & hex = allHexa[ i ];
2368 intHexa.push_back( hex );
2369 if ( hex->_nbFaceIntNodes > 0 || hex->_eIntPoints.size() > 0 )
2370 continue; // treat intersected hex later
2371 this->init( hex->_i, hex->_j, hex->_k );
2377 if (( _nbCornerNodes == 8 ) &&
2378 ( _nbBndNodes < _nbCornerNodes || !isInHole() ))
2380 // order of _hexNodes is defined by enum SMESH_Block::TShapeID
2381 SMDS_MeshElement* el =
2382 mesh->AddVolume( _hexNodes[0].Node(), _hexNodes[2].Node(),
2383 _hexNodes[3].Node(), _hexNodes[1].Node(),
2384 _hexNodes[4].Node(), _hexNodes[6].Node(),
2385 _hexNodes[7].Node(), _hexNodes[5].Node() );
2386 mesh->SetMeshElementOnShape( el, helper.GetSubShapeID() );
2391 else if ( _nbCornerNodes > 3 && !hex )
2393 // all intersection of hex with geometry are at grid nodes
2394 hex = new Hexahedron( *this );
2398 intHexa.push_back( hex );
2402 // add elements resulted from hexadron intersection
2404 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, intHexa.size() ),
2405 ParallelHexahedron( intHexa ),
2406 tbb::simple_partitioner()); // ComputeElements() is called here
2407 for ( size_t i = 0; i < intHexa.size(); ++i )
2408 if ( Hexahedron * hex = intHexa[ i ] )
2409 nbAdded += hex->addElements( helper );
2411 for ( size_t i = 0; i < intHexa.size(); ++i )
2412 if ( Hexahedron * hex = intHexa[ i ] )
2414 hex->ComputeElements();
2415 nbAdded += hex->addElements( helper );
2419 for ( size_t i = 0; i < allHexa.size(); ++i )
2421 delete allHexa[ i ];
2426 //================================================================================
2428 * \brief Implements geom edges into the mesh
2430 void Hexahedron::addEdges(SMESH_MesherHelper& helper,
2431 vector< Hexahedron* >& hexes,
2432 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
2434 if ( edge2faceIDsMap.empty() ) return;
2436 // Prepare planes for intersecting with EDGEs
2439 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ ) // iDirZ gives normal direction to planes
2441 GridPlanes& planes = pln[ iDirZ ];
2442 int iDirX = ( iDirZ + 1 ) % 3;
2443 int iDirY = ( iDirZ + 2 ) % 3;
2444 planes._zNorm = ( _grid->_axes[ iDirX ] ^ _grid->_axes[ iDirY ] ).Normalized();
2445 planes._zProjs.resize ( _grid->_coords[ iDirZ ].size() );
2446 planes._zProjs [0] = 0;
2447 const double zFactor = _grid->_axes[ iDirZ ] * planes._zNorm;
2448 const vector< double > & u = _grid->_coords[ iDirZ ];
2449 for ( size_t i = 1; i < planes._zProjs.size(); ++i )
2451 planes._zProjs [i] = zFactor * ( u[i] - u[0] );
2455 const double deflection = _grid->_minCellSize / 20.;
2456 const double tol = _grid->_tol;
2457 E_IntersectPoint ip;
2459 // Intersect EDGEs with the planes
2460 map< TGeomID, vector< TGeomID > >::const_iterator e2fIt = edge2faceIDsMap.begin();
2461 for ( ; e2fIt != edge2faceIDsMap.end(); ++e2fIt )
2463 const TGeomID edgeID = e2fIt->first;
2464 const TopoDS_Edge & E = TopoDS::Edge( _grid->_shapes( edgeID ));
2465 BRepAdaptor_Curve curve( E );
2466 TopoDS_Vertex v1 = helper.IthVertex( 0, E, false );
2467 TopoDS_Vertex v2 = helper.IthVertex( 1, E, false );
2469 ip._faceIDs = e2fIt->second;
2470 ip._shapeID = edgeID;
2472 // discretize the EGDE
2473 GCPnts_UniformDeflection discret( curve, deflection, true );
2474 if ( !discret.IsDone() || discret.NbPoints() < 2 )
2477 // perform intersection
2478 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ )
2480 GridPlanes& planes = pln[ iDirZ ];
2481 int iDirX = ( iDirZ + 1 ) % 3;
2482 int iDirY = ( iDirZ + 2 ) % 3;
2483 double xLen = _grid->_coords[ iDirX ].back() - _grid->_coords[ iDirX ][0];
2484 double yLen = _grid->_coords[ iDirY ].back() - _grid->_coords[ iDirY ][0];
2485 double zLen = _grid->_coords[ iDirZ ].back() - _grid->_coords[ iDirZ ][0];
2486 int dIJK[3], d000[3] = { 0,0,0 };
2487 double o[3] = { _grid->_coords[0][0],
2488 _grid->_coords[1][0],
2489 _grid->_coords[2][0] };
2491 // locate the 1st point of a segment within the grid
2492 gp_XYZ p1 = discret.Value( 1 ).XYZ();
2493 double u1 = discret.Parameter( 1 );
2494 double zProj1 = planes._zNorm * ( p1 - _grid->_origin );
2496 _grid->ComputeUVW( p1, ip._uvw );
2497 int iX1 = int(( ip._uvw[iDirX] - o[iDirX]) / xLen * (_grid->_coords[ iDirX ].size() - 1));
2498 int iY1 = int(( ip._uvw[iDirY] - o[iDirY]) / yLen * (_grid->_coords[ iDirY ].size() - 1));
2499 int iZ1 = int(( ip._uvw[iDirZ] - o[iDirZ]) / zLen * (_grid->_coords[ iDirZ ].size() - 1));
2500 locateValue( iX1, ip._uvw[iDirX], _grid->_coords[ iDirX ], dIJK[ iDirX ], tol );
2501 locateValue( iY1, ip._uvw[iDirY], _grid->_coords[ iDirY ], dIJK[ iDirY ], tol );
2502 locateValue( iZ1, ip._uvw[iDirZ], _grid->_coords[ iDirZ ], dIJK[ iDirZ ], tol );
2504 int ijk[3]; // grid index where a segment intersect a plane
2509 // add the 1st vertex point to a hexahedron
2513 ip._shapeID = _grid->_shapes.Add( v1 );
2514 _grid->_edgeIntP.push_back( ip );
2515 if ( !addIntersection( _grid->_edgeIntP.back(), hexes, ijk, d000 ))
2516 _grid->_edgeIntP.pop_back();
2517 ip._shapeID = edgeID;
2519 for ( int iP = 2; iP <= discret.NbPoints(); ++iP )
2521 // locate the 2nd point of a segment within the grid
2522 gp_XYZ p2 = discret.Value( iP ).XYZ();
2523 double u2 = discret.Parameter( iP );
2524 double zProj2 = planes._zNorm * ( p2 - _grid->_origin );
2526 if ( Abs( zProj2 - zProj1 ) > std::numeric_limits<double>::min() )
2528 locateValue( iZ2, zProj2, planes._zProjs, dIJK[ iDirZ ], tol );
2530 // treat intersections with planes between 2 end points of a segment
2531 int dZ = ( iZ1 <= iZ2 ) ? +1 : -1;
2532 int iZ = iZ1 + ( iZ1 < iZ2 );
2533 for ( int i = 0, nb = Abs( iZ1 - iZ2 ); i < nb; ++i, iZ += dZ )
2535 ip._point = findIntPoint( u1, zProj1, u2, zProj2,
2536 planes._zProjs[ iZ ],
2537 curve, planes._zNorm, _grid->_origin );
2538 _grid->ComputeUVW( ip._point.XYZ(), ip._uvw );
2539 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
2540 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
2543 // add ip to hex "above" the plane
2544 _grid->_edgeIntP.push_back( ip );
2546 bool added = addIntersection(_grid->_edgeIntP.back(), hexes, ijk, dIJK);
2548 // add ip to hex "below" the plane
2549 ijk[ iDirZ ] = iZ-1;
2550 if ( !addIntersection( _grid->_edgeIntP.back(), hexes, ijk, dIJK ) &&
2552 _grid->_edgeIntP.pop_back();
2560 // add the 2nd vertex point to a hexahedron
2563 ip._shapeID = _grid->_shapes.Add( v2 );
2565 _grid->ComputeUVW( p1, ip._uvw );
2566 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
2567 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
2569 _grid->_edgeIntP.push_back( ip );
2570 if ( !addIntersection( _grid->_edgeIntP.back(), hexes, ijk, d000 ))
2571 _grid->_edgeIntP.pop_back();
2572 ip._shapeID = edgeID;
2574 } // loop on 3 grid directions
2579 //================================================================================
2581 * \brief Finds intersection of a curve with a plane
2582 * \param [in] u1 - parameter of one curve point
2583 * \param [in] proj1 - projection of the curve point to the plane normal
2584 * \param [in] u2 - parameter of another curve point
2585 * \param [in] proj2 - projection of the other curve point to the plane normal
2586 * \param [in] proj - projection of a point where the curve intersects the plane
2587 * \param [in] curve - the curve
2588 * \param [in] axis - the plane normal
2589 * \param [in] origin - the plane origin
2590 * \return gp_Pnt - the found intersection point
2592 gp_Pnt Hexahedron::findIntPoint( double u1, double proj1,
2593 double u2, double proj2,
2595 BRepAdaptor_Curve& curve,
2597 const gp_XYZ& origin)
2599 double r = (( proj - proj1 ) / ( proj2 - proj1 ));
2600 double u = u1 * ( 1 - r ) + u2 * r;
2601 gp_Pnt p = curve.Value( u );
2602 double newProj = axis * ( p.XYZ() - origin );
2603 if ( Abs( proj - newProj ) > _grid->_tol / 10. )
2606 return findIntPoint( u2, proj2, u, newProj, proj, curve, axis, origin );
2608 return findIntPoint( u1, proj2, u, newProj, proj, curve, axis, origin );
2613 //================================================================================
2615 * \brief Returns indices of a hexahedron sub-entities holding a point
2616 * \param [in] ip - intersection point
2617 * \param [out] facets - 0-3 facets holding a point
2618 * \param [out] sub - index of a vertex or an edge holding a point
2619 * \return int - number of facets holding a point
2621 int Hexahedron::getEntity( const E_IntersectPoint* ip, int* facets, int& sub )
2623 enum { X = 1, Y = 2, Z = 4 }; // == 001, 010, 100
2625 int vertex = 0, egdeMask = 0;
2627 if ( Abs( _grid->_coords[0][ _i ] - ip->_uvw[0] ) < _grid->_tol ) {
2628 facets[ nbFacets++ ] = SMESH_Block::ID_F0yz;
2631 else if ( Abs( _grid->_coords[0][ _i+1 ] - ip->_uvw[0] ) < _grid->_tol ) {
2632 facets[ nbFacets++ ] = SMESH_Block::ID_F1yz;
2636 if ( Abs( _grid->_coords[1][ _j ] - ip->_uvw[1] ) < _grid->_tol ) {
2637 facets[ nbFacets++ ] = SMESH_Block::ID_Fx0z;
2640 else if ( Abs( _grid->_coords[1][ _j+1 ] - ip->_uvw[1] ) < _grid->_tol ) {
2641 facets[ nbFacets++ ] = SMESH_Block::ID_Fx1z;
2645 if ( Abs( _grid->_coords[2][ _k ] - ip->_uvw[2] ) < _grid->_tol ) {
2646 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy0;
2649 else if ( Abs( _grid->_coords[2][ _k+1 ] - ip->_uvw[2] ) < _grid->_tol ) {
2650 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy1;
2657 case 0: sub = 0; break;
2658 case 1: sub = facets[0]; break;
2660 const int edge [3][8] = {
2661 { SMESH_Block::ID_E00z, SMESH_Block::ID_E10z,
2662 SMESH_Block::ID_E01z, SMESH_Block::ID_E11z },
2663 { SMESH_Block::ID_E0y0, SMESH_Block::ID_E1y0, 0, 0,
2664 SMESH_Block::ID_E0y1, SMESH_Block::ID_E1y1 },
2665 { SMESH_Block::ID_Ex00, 0, SMESH_Block::ID_Ex10, 0,
2666 SMESH_Block::ID_Ex01, 0, SMESH_Block::ID_Ex11 }
2668 switch ( egdeMask ) {
2669 case X | Y: sub = edge[ 0 ][ vertex ]; break;
2670 case X | Z: sub = edge[ 1 ][ vertex ]; break;
2671 default: sub = edge[ 2 ][ vertex ];
2677 sub = vertex + SMESH_Block::ID_FirstV;
2682 //================================================================================
2684 * \brief Adds intersection with an EDGE
2686 bool Hexahedron::addIntersection( const E_IntersectPoint& ip,
2687 vector< Hexahedron* >& hexes,
2688 int ijk[], int dIJK[] )
2692 size_t hexIndex[4] = {
2693 _grid->CellIndex( ijk[0], ijk[1], ijk[2] ),
2694 dIJK[0] ? _grid->CellIndex( ijk[0]+dIJK[0], ijk[1], ijk[2] ) : -1,
2695 dIJK[1] ? _grid->CellIndex( ijk[0], ijk[1]+dIJK[1], ijk[2] ) : -1,
2696 dIJK[2] ? _grid->CellIndex( ijk[0], ijk[1], ijk[2]+dIJK[2] ) : -1
2698 for ( int i = 0; i < 4; ++i )
2700 if ( /*0 <= hexIndex[i] &&*/ hexIndex[i] < hexes.size() && hexes[ hexIndex[i] ] )
2702 Hexahedron* h = hexes[ hexIndex[i] ];
2703 // check if ip is really inside the hex
2705 if ( h->isOutParam( ip._uvw ))
2706 throw SALOME_Exception("ip outside a hex");
2708 h->_eIntPoints.push_back( & ip );
2714 //================================================================================
2716 * \brief Finds nodes at a path from one node to another via intersections with EDGEs
2718 bool Hexahedron::findChain( _Node* n1,
2721 vector<_Node*>& chn )
2724 chn.push_back( n1 );
2725 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2726 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
2727 n1->IsLinked( quad._eIntNodes[ iP ]->_intPoint ) &&
2728 n2->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
2730 chn.push_back( quad._eIntNodes[ iP ]);
2731 chn.push_back( n2 );
2732 quad._eIntNodes[ iP ]->_usedInFace = &quad;
2739 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2740 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
2741 chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
2743 chn.push_back( quad._eIntNodes[ iP ]);
2744 found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
2747 } while ( found && ! chn.back()->IsLinked( n2->_intPoint ) );
2749 if ( chn.back() != n2 && chn.back()->IsLinked( n2->_intPoint ))
2750 chn.push_back( n2 );
2752 return chn.size() > 1;
2754 //================================================================================
2756 * \brief Try to heal a polygon whose ends are not connected
2758 bool Hexahedron::closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const
2760 int i = -1, nbLinks = polygon->_links.size();
2763 vector< _OrientedLink > newLinks;
2764 // find a node lying on the same FACE as the last one
2765 _Node* node = polygon->_links.back().LastNode();
2766 int avoidFace = node->IsLinked( polygon->_links.back().FirstNode()->_intPoint );
2767 for ( i = nbLinks - 2; i >= 0; --i )
2768 if ( node->IsLinked( polygon->_links[i].FirstNode()->_intPoint, avoidFace ))
2772 for ( ; i < nbLinks; ++i )
2773 newLinks.push_back( polygon->_links[i] );
2777 // find a node lying on the same FACE as the first one
2778 node = polygon->_links[0].FirstNode();
2779 avoidFace = node->IsLinked( polygon->_links[0].LastNode()->_intPoint );
2780 for ( i = 1; i < nbLinks; ++i )
2781 if ( node->IsLinked( polygon->_links[i].LastNode()->_intPoint, avoidFace ))
2784 for ( nbLinks = i + 1, i = 0; i < nbLinks; ++i )
2785 newLinks.push_back( polygon->_links[i] );
2787 if ( newLinks.size() > 1 )
2789 polygon->_links.swap( newLinks );
2791 chainNodes.push_back( polygon->_links.back().LastNode() );
2792 chainNodes.push_back( polygon->_links[0].FirstNode() );
2797 //================================================================================
2799 * \brief Finds nodes on the same EDGE as the first node of avoidSplit.
2801 * This function is for a case where an EDGE lies on a quad which lies on a FACE
2802 * so that a part of quad in ON and another part in IN
2804 bool Hexahedron::findChainOnEdge( const vector< _OrientedLink >& splits,
2805 const _OrientedLink& prevSplit,
2806 const _OrientedLink& avoidSplit,
2809 vector<_Node*>& chn )
2811 if ( !isImplementEdges() )
2814 _Node* pn1 = prevSplit.FirstNode();
2815 _Node* pn2 = prevSplit.LastNode();
2816 int avoidFace = pn1->IsLinked( pn2->_intPoint ); // FACE under the quad
2817 if ( avoidFace < 1 && pn1->_intPoint )
2820 _Node* n, *stopNode = avoidSplit.LastNode();
2823 if ( !quad._eIntNodes.empty() )
2825 chn.push_back( pn2 );
2830 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2831 if (( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad )) &&
2832 ( chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint, avoidFace )) &&
2833 ( !avoidFace || quad._eIntNodes[ iP ]->IsOnFace( avoidFace )))
2835 chn.push_back( quad._eIntNodes[ iP ]);
2836 found = ( quad._eIntNodes[ iP ]->_usedInFace = &quad );
2844 for ( i = splits.size()-1; i >= 0; --i )
2849 n = splits[i].LastNode();
2850 if ( n == stopNode )
2853 ( n->IsLinked( pn2->_intPoint, avoidFace )) &&
2854 ( !avoidFace || n->IsOnFace( avoidFace )))
2857 n = splits[i].FirstNode();
2858 if ( n == stopNode )
2860 if (( n->IsLinked( pn2->_intPoint, avoidFace )) &&
2861 ( !avoidFace || n->IsOnFace( avoidFace )))
2865 if ( n && n != stopNode)
2868 chn.push_back( pn2 );
2875 //================================================================================
2877 * \brief Checks transition at the ginen intersection node of a link
2879 bool Hexahedron::isOutPoint( _Link& link, int iP, SMESH_MesherHelper& helper ) const
2883 const bool moreIntPoints = ( iP+1 < (int) link._fIntPoints.size() );
2886 _Node* n1 = link._fIntNodes[ iP ];
2888 n1 = link._nodes[0];
2889 _Node* n2 = moreIntPoints ? link._fIntNodes[ iP+1 ] : 0;
2890 if ( !n2 || !n2->Node() )
2891 n2 = link._nodes[1];
2895 // get all FACEs under n1 and n2
2896 set< TGeomID > faceIDs;
2897 if ( moreIntPoints ) faceIDs.insert( link._fIntPoints[iP+1]->_faceIDs.begin(),
2898 link._fIntPoints[iP+1]->_faceIDs.end() );
2899 if ( n2->_intPoint ) faceIDs.insert( n2->_intPoint->_faceIDs.begin(),
2900 n2->_intPoint->_faceIDs.end() );
2901 if ( faceIDs.empty() )
2902 return false; // n2 is inside
2903 if ( n1->_intPoint ) faceIDs.insert( n1->_intPoint->_faceIDs.begin(),
2904 n1->_intPoint->_faceIDs.end() );
2905 faceIDs.insert( link._fIntPoints[iP]->_faceIDs.begin(),
2906 link._fIntPoints[iP]->_faceIDs.end() );
2908 // get a point between 2 nodes
2909 gp_Pnt p1 = n1->Point();
2910 gp_Pnt p2 = n2->Point();
2911 gp_Pnt pOnLink = 0.8 * p1.XYZ() + 0.2 * p2.XYZ();
2913 TopLoc_Location loc;
2915 set< TGeomID >::iterator faceID = faceIDs.begin();
2916 for ( ; faceID != faceIDs.end(); ++faceID )
2918 // project pOnLink on a FACE
2919 if ( *faceID < 1 ) continue;
2920 const TopoDS_Face& face = TopoDS::Face( _grid->_shapes( *faceID ));
2921 GeomAPI_ProjectPointOnSurf& proj =
2922 helper.GetProjector( face, loc, 0.1*_grid->_tol );
2923 gp_Pnt testPnt = pOnLink.Transformed( loc.Transformation().Inverted() );
2924 proj.Perform( testPnt );
2925 if ( proj.IsDone() && proj.NbPoints() > 0 )
2927 Quantity_Parameter u,v;
2928 proj.LowerDistanceParameters( u,v );
2930 if ( proj.LowerDistance() <= 0.1 * _grid->_tol )
2936 // find isOut by normals
2938 if ( GeomLib::NormEstim( BRep_Tool::Surface( face, loc ),
2943 if ( face.Orientation() == TopAbs_REVERSED )
2945 gp_Vec v( proj.NearestPoint(), testPnt );
2946 isOut = ( v * normal > 0 );
2951 // classify a projection
2952 if ( !n1->IsOnFace( *faceID ) || !n2->IsOnFace( *faceID ))
2954 BRepTopAdaptor_FClass2d cls( face, Precision::Confusion() );
2955 TopAbs_State state = cls.Perform( gp_Pnt2d( u,v ));
2956 if ( state == TopAbs_OUT )
2968 //================================================================================
2970 * \brief Sort nodes on a FACE
2972 void Hexahedron::sortVertexNodes(vector<_Node*>& nodes, _Node* curNode, TGeomID faceID)
2974 if ( nodes.size() > 20 ) return;
2976 // get shapes under nodes
2977 TGeomID nShapeIds[20], *nShapeIdsEnd = &nShapeIds[0] + nodes.size();
2978 for ( size_t i = 0; i < nodes.size(); ++i )
2979 if ( !( nShapeIds[i] = nodes[i]->ShapeID() ))
2982 // get shapes of the FACE
2983 const TopoDS_Face& face = TopoDS::Face( _grid->_shapes( faceID ));
2984 list< TopoDS_Edge > edges;
2985 list< int > nbEdges;
2986 int nbW = SMESH_Block::GetOrderedEdges (face, edges, nbEdges);
2988 // select a WIRE - remove EDGEs of irrelevant WIREs from edges
2989 list< TopoDS_Edge >::iterator e = edges.begin(), eEnd = e;
2990 list< int >::iterator nE = nbEdges.begin();
2991 for ( ; nbW > 0; ++nE, --nbW )
2993 std::advance( eEnd, *nE );
2994 for ( ; e != eEnd; ++e )
2995 for ( int i = 0; i < 2; ++i )
2998 _grid->_shapes.FindIndex( *e ) :
2999 _grid->_shapes.FindIndex( SMESH_MesherHelper::IthVertex( 0, *e ));
3001 ( std::find( &nShapeIds[0], nShapeIdsEnd, id ) != nShapeIdsEnd ))
3003 edges.erase( eEnd, edges.end() ); // remove rest wires
3004 e = eEnd = edges.end();
3011 edges.erase( edges.begin(), eEnd ); // remove a current irrelevant wire
3014 // rotate edges to have the first one at least partially out of the hexa
3015 list< TopoDS_Edge >::iterator e = edges.begin(), eMidOut = edges.end();
3016 for ( ; e != edges.end(); ++e )
3018 if ( !_grid->_shapes.FindIndex( *e ))
3023 for ( int i = 0; i < 2 && !isOut; ++i )
3027 TopoDS_Vertex v = SMESH_MesherHelper::IthVertex( 0, *e );
3028 p = BRep_Tool::Pnt( v );
3030 else if ( eMidOut == edges.end() )
3032 TopLoc_Location loc;
3033 Handle(Geom_Curve) c = BRep_Tool::Curve( *e, loc, f, l);
3034 if ( c.IsNull() ) break;
3035 p = c->Value( 0.5 * ( f + l )).Transformed( loc );
3042 _grid->ComputeUVW( p.XYZ(), uvw );
3043 if ( isOutParam( uvw ))
3054 if ( e != edges.end() )
3055 edges.splice( edges.end(), edges, edges.begin(), e );
3056 else if ( eMidOut != edges.end() )
3057 edges.splice( edges.end(), edges, edges.begin(), eMidOut );
3059 // sort nodes accoring to the order of edges
3060 _Node* orderNodes [20];
3061 //TGeomID orderShapeIDs[20];
3063 TGeomID id, *pID = 0;
3064 for ( e = edges.begin(); e != edges.end(); ++e )
3066 if (( id = _grid->_shapes.FindIndex( SMESH_MesherHelper::IthVertex( 0, *e ))) &&
3067 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
3069 //orderShapeIDs[ nbN ] = id;
3070 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
3073 if (( id = _grid->_shapes.FindIndex( *e )) &&
3074 (( pID = std::find( &nShapeIds[0], nShapeIdsEnd, id )) != nShapeIdsEnd ))
3076 //orderShapeIDs[ nbN ] = id;
3077 orderNodes [ nbN++ ] = nodes[ pID - &nShapeIds[0] ];
3081 if ( nbN != nodes.size() )
3084 bool reverse = ( orderNodes[0 ]->Point().SquareDistance( curNode->Point() ) >
3085 orderNodes[nbN-1]->Point().SquareDistance( curNode->Point() ));
3087 for ( size_t i = 0; i < nodes.size(); ++i )
3088 nodes[ i ] = orderNodes[ reverse ? nbN-1-i : i ];
3091 //================================================================================
3093 * \brief Adds computed elements to the mesh
3095 int Hexahedron::addElements(SMESH_MesherHelper& helper)
3098 // add elements resulted from hexahedron intersection
3099 //for ( size_t i = 0; i < _volumeDefs.size(); ++i )
3101 vector< const SMDS_MeshNode* > nodes( _volumeDefs._nodes.size() );
3102 for ( size_t iN = 0; iN < nodes.size(); ++iN )
3103 if ( !( nodes[iN] = _volumeDefs._nodes[iN]->Node() ))
3105 if ( const E_IntersectPoint* eip = _volumeDefs._nodes[iN]->EdgeIntPnt() )
3106 nodes[iN] = _volumeDefs._nodes[iN]->_intPoint->_node =
3107 helper.AddNode( eip->_point.X(),
3111 throw SALOME_Exception("Bug: no node at intersection point");
3114 if ( !_volumeDefs._quantities.empty() )
3116 helper.AddPolyhedralVolume( nodes, _volumeDefs._quantities );
3120 switch ( nodes.size() )
3122 case 8: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],
3123 nodes[4],nodes[5],nodes[6],nodes[7] );
3125 case 4: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3] );
3127 case 6: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3], nodes[4],nodes[5] );
3130 helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4] );
3134 nbAdded += int ( _volumeDefs._nodes.size() > 0 );
3139 //================================================================================
3141 * \brief Return true if the element is in a hole
3143 bool Hexahedron::isInHole() const
3145 if ( !_vIntNodes.empty() )
3148 const size_t ijk[3] = { _i, _j, _k };
3149 F_IntersectPoint curIntPnt;
3151 // consider a cell to be in a hole if all links in any direction
3152 // comes OUT of geometry
3153 for ( int iDir = 0; iDir < 3; ++iDir )
3155 const vector<double>& coords = _grid->_coords[ iDir ];
3156 LineIndexer li = _grid->GetLineIndexer( iDir );
3157 li.SetIJK( _i,_j,_k );
3158 size_t lineIndex[4] = { li.LineIndex (),
3162 bool allLinksOut = true, hasLinks = false;
3163 for ( int iL = 0; iL < 4 && allLinksOut; ++iL ) // loop on 4 links parallel to iDir
3165 const _Link& link = _hexLinks[ iL + 4*iDir ];
3166 // check transition of the first node of a link
3167 const F_IntersectPoint* firstIntPnt = 0;
3168 if ( link._nodes[0]->Node() ) // 1st node is a hexa corner
3170 curIntPnt._paramOnLine = coords[ ijk[ iDir ]] - coords[0];
3171 const GridLine& line = _grid->_lines[ iDir ][ lineIndex[ iL ]];
3172 multiset< F_IntersectPoint >::const_iterator ip =
3173 line._intPoints.upper_bound( curIntPnt );
3175 firstIntPnt = &(*ip);
3177 else if ( !link._fIntPoints.empty() )
3179 firstIntPnt = link._fIntPoints[0];
3185 allLinksOut = ( firstIntPnt->_transition == Trans_OUT );
3188 if ( hasLinks && allLinksOut )
3194 //================================================================================
3196 * \brief Return true if a polyhedron passes _sizeThreshold criterion
3198 bool Hexahedron::checkPolyhedronSize() const
3201 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
3203 const _Face& polygon = _polygons[iP];
3204 if ( polygon._links.empty() )
3206 gp_XYZ area (0,0,0);
3207 gp_XYZ p1 = polygon._links[ 0 ].FirstNode()->Point().XYZ();
3208 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
3210 gp_XYZ p2 = polygon._links[ iL ].LastNode()->Point().XYZ();
3214 volume += p1 * area;
3218 double initVolume = _sideLength[0] * _sideLength[1] * _sideLength[2];
3220 return volume > initVolume / _sizeThreshold;
3222 //================================================================================
3224 * \brief Tries to create a hexahedron
3226 bool Hexahedron::addHexa()
3228 int nbQuad = 0, iQuad = -1;
3229 for ( size_t i = 0; i < _polygons.size(); ++i )
3231 if ( _polygons[i]._links.empty() )
3233 if ( _polygons[i]._links.size() != 4 )
3244 for ( int iL = 0; iL < 4; ++iL )
3247 nodes[iL] = _polygons[iQuad]._links[iL].FirstNode();
3250 // find a top node above the base node
3251 _Link* link = _polygons[iQuad]._links[iL]._link;
3252 if ( !link->_faces[0] || !link->_faces[1] )
3253 return debugDumpLink( link );
3254 // a quadrangle sharing <link> with _polygons[iQuad]
3255 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[iQuad] )];
3256 for ( int i = 0; i < 4; ++i )
3257 if ( quad->_links[i]._link == link )
3259 // 1st node of a link opposite to <link> in <quad>
3260 nodes[iL+4] = quad->_links[(i+2)%4].FirstNode();
3266 _volumeDefs.set( &nodes[0], 8 );
3270 //================================================================================
3272 * \brief Tries to create a tetrahedron
3274 bool Hexahedron::addTetra()
3277 for ( size_t i = 0; i < _polygons.size() && iTria < 0; ++i )
3278 if ( _polygons[i]._links.size() == 3 )
3284 nodes[0] = _polygons[iTria]._links[0].FirstNode();
3285 nodes[1] = _polygons[iTria]._links[1].FirstNode();
3286 nodes[2] = _polygons[iTria]._links[2].FirstNode();
3288 _Link* link = _polygons[iTria]._links[0]._link;
3289 if ( !link->_faces[0] || !link->_faces[1] )
3290 return debugDumpLink( link );
3292 // a triangle sharing <link> with _polygons[0]
3293 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[iTria] )];
3294 for ( int i = 0; i < 3; ++i )
3295 if ( tria->_links[i]._link == link )
3297 nodes[3] = tria->_links[(i+1)%3].LastNode();
3298 _volumeDefs.set( &nodes[0], 4 );
3304 //================================================================================
3306 * \brief Tries to create a pentahedron
3308 bool Hexahedron::addPenta()
3310 // find a base triangular face
3312 for ( int iF = 0; iF < 5 && iTri < 0; ++iF )
3313 if ( _polygons[ iF ]._links.size() == 3 )
3315 if ( iTri < 0 ) return false;
3320 for ( int iL = 0; iL < 3; ++iL )
3323 nodes[iL] = _polygons[ iTri ]._links[iL].FirstNode();
3326 // find a top node above the base node
3327 _Link* link = _polygons[ iTri ]._links[iL]._link;
3328 if ( !link->_faces[0] || !link->_faces[1] )
3329 return debugDumpLink( link );
3330 // a quadrangle sharing <link> with a base triangle
3331 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[ iTri ] )];
3332 if ( quad->_links.size() != 4 ) return false;
3333 for ( int i = 0; i < 4; ++i )
3334 if ( quad->_links[i]._link == link )
3336 // 1st node of a link opposite to <link> in <quad>
3337 nodes[iL+3] = quad->_links[(i+2)%4].FirstNode();
3343 _volumeDefs.set( &nodes[0], 6 );
3345 return ( nbN == 6 );
3347 //================================================================================
3349 * \brief Tries to create a pyramid
3351 bool Hexahedron::addPyra()
3353 // find a base quadrangle
3355 for ( int iF = 0; iF < 5 && iQuad < 0; ++iF )
3356 if ( _polygons[ iF ]._links.size() == 4 )
3358 if ( iQuad < 0 ) return false;
3362 nodes[0] = _polygons[iQuad]._links[0].FirstNode();
3363 nodes[1] = _polygons[iQuad]._links[1].FirstNode();
3364 nodes[2] = _polygons[iQuad]._links[2].FirstNode();
3365 nodes[3] = _polygons[iQuad]._links[3].FirstNode();
3367 _Link* link = _polygons[iQuad]._links[0]._link;
3368 if ( !link->_faces[0] || !link->_faces[1] )
3369 return debugDumpLink( link );
3371 // a triangle sharing <link> with a base quadrangle
3372 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[ iQuad ] )];
3373 if ( tria->_links.size() != 3 ) return false;
3374 for ( int i = 0; i < 3; ++i )
3375 if ( tria->_links[i]._link == link )
3377 nodes[4] = tria->_links[(i+1)%3].LastNode();
3378 _volumeDefs.set( &nodes[0], 5 );
3384 //================================================================================
3386 * \brief Dump a link and return \c false
3388 bool Hexahedron::debugDumpLink( Hexahedron::_Link* link )
3391 gp_Pnt p1 = link->_nodes[0]->Point(), p2 = link->_nodes[1]->Point();
3392 cout << "BUG: not shared link. IKJ = ( "<< _i << " " << _j << " " << _k << " )" << endl
3393 << "n1 (" << p1.X() << ", "<< p1.Y() << ", "<< p1.Z() << " )" << endl
3394 << "n2 (" << p2.X() << ", "<< p2.Y() << ", "<< p2.Z() << " )" << endl;
3398 //================================================================================
3400 * \brief Classify a point by grid paremeters
3402 bool Hexahedron::isOutParam(const double uvw[3]) const
3404 return (( _grid->_coords[0][ _i ] - _grid->_tol > uvw[0] ) ||
3405 ( _grid->_coords[0][ _i+1 ] + _grid->_tol < uvw[0] ) ||
3406 ( _grid->_coords[1][ _j ] - _grid->_tol > uvw[1] ) ||
3407 ( _grid->_coords[1][ _j+1 ] + _grid->_tol < uvw[1] ) ||
3408 ( _grid->_coords[2][ _k ] - _grid->_tol > uvw[2] ) ||
3409 ( _grid->_coords[2][ _k+1 ] + _grid->_tol < uvw[2] ));
3412 //================================================================================
3414 * \brief computes exact bounding box with axes parallel to given ones
3416 //================================================================================
3418 void getExactBndBox( const vector< TopoDS_Shape >& faceVec,
3419 const double* axesDirs,
3423 TopoDS_Compound allFacesComp;
3424 b.MakeCompound( allFacesComp );
3425 for ( size_t iF = 0; iF < faceVec.size(); ++iF )
3426 b.Add( allFacesComp, faceVec[ iF ] );
3428 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
3429 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
3431 for ( int i = 0; i < 6; ++i )
3432 farDist = Max( farDist, 10 * sP[i] );
3434 gp_XYZ axis[3] = { gp_XYZ( axesDirs[0], axesDirs[1], axesDirs[2] ),
3435 gp_XYZ( axesDirs[3], axesDirs[4], axesDirs[5] ),
3436 gp_XYZ( axesDirs[6], axesDirs[7], axesDirs[8] ) };
3437 axis[0].Normalize();
3438 axis[1].Normalize();
3439 axis[2].Normalize();
3441 gp_Mat basis( axis[0], axis[1], axis[2] );
3442 gp_Mat bi = basis.Inverted();
3445 for ( int iDir = 0; iDir < 3; ++iDir )
3447 gp_XYZ axis0 = axis[ iDir ];
3448 gp_XYZ axis1 = axis[ ( iDir + 1 ) % 3 ];
3449 gp_XYZ axis2 = axis[ ( iDir + 2 ) % 3 ];
3450 for ( int isMax = 0; isMax < 2; ++isMax )
3452 double shift = isMax ? farDist : -farDist;
3453 gp_XYZ orig = shift * axis0;
3454 gp_XYZ norm = axis1 ^ axis2;
3455 gp_Pln pln( orig, norm );
3456 norm = pln.Axis().Direction().XYZ();
3457 BRepBuilderAPI_MakeFace plane( pln, -farDist, farDist, -farDist, farDist );
3459 gp_Pnt& pAxis = isMax ? pMax : pMin;
3460 gp_Pnt pPlane, pFaces;
3461 double dist = GEOMUtils::GetMinDistance( plane, allFacesComp, pPlane, pFaces );
3466 for ( int i = 0; i < 2; ++i ) {
3467 corner.SetCoord( 1, sP[ i*3 ]);
3468 for ( int j = 0; j < 2; ++j ) {
3469 corner.SetCoord( 2, sP[ i*3 + 1 ]);
3470 for ( int k = 0; k < 2; ++k )
3472 corner.SetCoord( 3, sP[ i*3 + 2 ]);
3478 corner = isMax ? bb.CornerMax() : bb.CornerMin();
3479 pAxis.SetCoord( iDir+1, corner.Coord( iDir+1 ));
3483 gp_XYZ pf = pFaces.XYZ() * bi;
3484 pAxis.SetCoord( iDir+1, pf.Coord( iDir+1 ) );
3490 shapeBox.Add( pMin );
3491 shapeBox.Add( pMax );
3498 //=============================================================================
3500 * \brief Generates 3D structured Cartesian mesh in the internal part of
3501 * solid shapes and polyhedral volumes near the shape boundary.
3502 * \param theMesh - mesh to fill in
3503 * \param theShape - a compound of all SOLIDs to mesh
3504 * \retval bool - true in case of success
3506 //=============================================================================
3508 bool StdMeshers_Cartesian_3D::Compute(SMESH_Mesh & theMesh,
3509 const TopoDS_Shape & theShape)
3511 // The algorithm generates the mesh in following steps:
3513 // 1) Intersection of grid lines with the geometry boundary.
3514 // This step allows to find out if a given node of the initial grid is
3515 // inside or outside the geometry.
3517 // 2) For each cell of the grid, check how many of it's nodes are outside
3518 // of the geometry boundary. Depending on a result of this check
3519 // - skip a cell, if all it's nodes are outside
3520 // - skip a cell, if it is too small according to the size threshold
3521 // - add a hexahedron in the mesh, if all nodes are inside
3522 // - add a polyhedron in the mesh, if some nodes are inside and some outside
3524 _computeCanceled = false;
3526 SMESH_MesherHelper helper( theMesh );
3531 grid._helper = &helper;
3533 vector< TopoDS_Shape > faceVec;
3535 TopTools_MapOfShape faceMap;
3536 TopExp_Explorer fExp;
3537 for ( fExp.Init( theShape, TopAbs_FACE ); fExp.More(); fExp.Next() )
3538 if ( !faceMap.Add( fExp.Current() ))
3539 faceMap.Remove( fExp.Current() ); // remove a face shared by two solids
3541 for ( fExp.ReInit(); fExp.More(); fExp.Next() )
3542 if ( faceMap.Contains( fExp.Current() ))
3543 faceVec.push_back( fExp.Current() );
3545 vector<FaceGridIntersector> facesItersectors( faceVec.size() );
3546 map< TGeomID, vector< TGeomID > > edge2faceIDsMap;
3547 TopExp_Explorer eExp;
3549 for ( size_t i = 0; i < faceVec.size(); ++i )
3551 facesItersectors[i]._face = TopoDS::Face ( faceVec[i] );
3552 facesItersectors[i]._faceID = grid._shapes.Add( faceVec[i] );
3553 facesItersectors[i]._grid = &grid;
3554 shapeBox.Add( facesItersectors[i].GetFaceBndBox() );
3556 if ( _hyp->GetToAddEdges() )
3558 helper.SetSubShape( faceVec[i] );
3559 for ( eExp.Init( faceVec[i], TopAbs_EDGE ); eExp.More(); eExp.Next() )
3561 const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
3562 if ( !SMESH_Algo::isDegenerated( edge ) &&
3563 !helper.IsRealSeam( edge ))
3564 edge2faceIDsMap[ grid._shapes.Add( edge )].push_back( facesItersectors[i]._faceID );
3569 getExactBndBox( faceVec, _hyp->GetAxisDirs(), shapeBox );
3571 vector<double> xCoords, yCoords, zCoords;
3572 _hyp->GetCoordinates( xCoords, yCoords, zCoords, shapeBox );
3574 grid.SetCoordinates( xCoords, yCoords, zCoords, _hyp->GetAxisDirs(), shapeBox );
3576 if ( _computeCanceled ) return false;
3579 { // copy partner faces and curves of not thread-safe types
3580 set< const Standard_Transient* > tshapes;
3581 BRepBuilderAPI_Copy copier;
3582 for ( size_t i = 0; i < facesItersectors.size(); ++i )
3584 if ( !facesItersectors[i].IsThreadSafe(tshapes) )
3586 copier.Perform( facesItersectors[i]._face );
3587 facesItersectors[i]._face = TopoDS::Face( copier );
3591 // Intersection of grid lines with the geometry boundary.
3592 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, facesItersectors.size() ),
3593 ParallelIntersector( facesItersectors ),
3594 tbb::simple_partitioner());
3596 for ( size_t i = 0; i < facesItersectors.size(); ++i )
3597 facesItersectors[i].Intersect();
3600 // put interesection points onto the GridLine's; this is done after intersection
3601 // to avoid contention of facesItersectors for writing into the same GridLine
3602 // in case of parallel work of facesItersectors
3603 for ( size_t i = 0; i < facesItersectors.size(); ++i )
3604 facesItersectors[i].StoreIntersections();
3606 TopExp_Explorer solidExp (theShape, TopAbs_SOLID);
3607 helper.SetSubShape( solidExp.Current() );
3608 helper.SetElementsOnShape( true );
3610 if ( _computeCanceled ) return false;
3612 // create nodes on the geometry
3613 grid.ComputeNodes(helper);
3615 if ( _computeCanceled ) return false;
3617 // create volume elements
3618 Hexahedron hex( _hyp->GetSizeThreshold(), &grid );
3619 int nbAdded = hex.MakeElements( helper, edge2faceIDsMap );
3621 SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
3624 // make all SOLIDs computed
3625 if ( SMESHDS_SubMesh* sm1 = meshDS->MeshElements( solidExp.Current()) )
3627 SMDS_ElemIteratorPtr volIt = sm1->GetElements();
3628 for ( ; solidExp.More() && volIt->more(); solidExp.Next() )
3630 const SMDS_MeshElement* vol = volIt->next();
3631 sm1->RemoveElement( vol, /*isElemDeleted=*/false );
3632 meshDS->SetMeshElementOnShape( vol, solidExp.Current() );
3635 // make other sub-shapes computed
3636 setSubmeshesComputed( theMesh, theShape );
3639 // remove free nodes
3640 if ( SMESHDS_SubMesh * smDS = meshDS->MeshElements( helper.GetSubShapeID() ))
3642 TIDSortedNodeSet nodesToRemove;
3643 // get intersection nodes
3644 for ( int iDir = 0; iDir < 3; ++iDir )
3646 vector< GridLine >& lines = grid._lines[ iDir ];
3647 for ( size_t i = 0; i < lines.size(); ++i )
3649 multiset< F_IntersectPoint >::iterator ip = lines[i]._intPoints.begin();
3650 for ( ; ip != lines[i]._intPoints.end(); ++ip )
3651 if ( ip->_node && ip->_node->NbInverseElements() == 0 )
3652 nodesToRemove.insert( nodesToRemove.end(), ip->_node );
3656 for ( size_t i = 0; i < grid._nodes.size(); ++i )
3657 if ( grid._nodes[i] && grid._nodes[i]->NbInverseElements() == 0 )
3658 nodesToRemove.insert( nodesToRemove.end(), grid._nodes[i] );
3661 TIDSortedNodeSet::iterator n = nodesToRemove.begin();
3662 for ( ; n != nodesToRemove.end(); ++n )
3663 meshDS->RemoveFreeNode( *n, smDS, /*fromGroups=*/false );
3669 // SMESH_ComputeError is not caught at SMESH_submesh level for an unknown reason
3670 catch ( SMESH_ComputeError& e)
3672 return error( SMESH_ComputeErrorPtr( new SMESH_ComputeError( e )));
3677 //=============================================================================
3681 //=============================================================================
3683 bool StdMeshers_Cartesian_3D::Evaluate(SMESH_Mesh & theMesh,
3684 const TopoDS_Shape & theShape,
3685 MapShapeNbElems& theResMap)
3688 // std::vector<int> aResVec(SMDSEntity_Last);
3689 // for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
3690 // if(IsQuadratic) {
3691 // aResVec[SMDSEntity_Quad_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
3692 // int nb1d_face0_int = ( nb2d_face0*4 - nb1d ) / 2;
3693 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
3696 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
3697 // aResVec[SMDSEntity_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
3699 // SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
3700 // aResMap.insert(std::make_pair(sm,aResVec));
3705 //=============================================================================
3709 * \brief Event listener setting/unsetting _alwaysComputed flag to
3710 * submeshes of inferior levels to prevent their computing
3712 struct _EventListener : public SMESH_subMeshEventListener
3716 _EventListener(const string& algoName):
3717 SMESH_subMeshEventListener(/*isDeletable=*/true,"StdMeshers_Cartesian_3D::_EventListener"),
3720 // --------------------------------------------------------------------------------
3721 // setting/unsetting _alwaysComputed flag to submeshes of inferior levels
3723 static void setAlwaysComputed( const bool isComputed,
3724 SMESH_subMesh* subMeshOfSolid)
3726 SMESH_subMeshIteratorPtr smIt =
3727 subMeshOfSolid->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3728 while ( smIt->more() )
3730 SMESH_subMesh* sm = smIt->next();
3731 sm->SetIsAlwaysComputed( isComputed );
3733 subMeshOfSolid->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3736 // --------------------------------------------------------------------------------
3737 // unsetting _alwaysComputed flag if "Cartesian_3D" was removed
3739 virtual void ProcessEvent(const int event,
3740 const int eventType,
3741 SMESH_subMesh* subMeshOfSolid,
3742 SMESH_subMeshEventListenerData* data,
3743 const SMESH_Hypothesis* hyp = 0)
3745 if ( eventType == SMESH_subMesh::COMPUTE_EVENT )
3747 setAlwaysComputed( subMeshOfSolid->GetComputeState() == SMESH_subMesh::COMPUTE_OK,
3752 SMESH_Algo* algo3D = subMeshOfSolid->GetAlgo();
3753 if ( !algo3D || _algoName != algo3D->GetName() )
3754 setAlwaysComputed( false, subMeshOfSolid );
3758 // --------------------------------------------------------------------------------
3759 // set the event listener
3761 static void SetOn( SMESH_subMesh* subMeshOfSolid, const string& algoName )
3763 subMeshOfSolid->SetEventListener( new _EventListener( algoName ),
3768 }; // struct _EventListener
3772 //================================================================================
3774 * \brief Sets event listener to submeshes if necessary
3775 * \param subMesh - submesh where algo is set
3776 * This method is called when a submesh gets HYP_OK algo_state.
3777 * After being set, event listener is notified on each event of a submesh.
3779 //================================================================================
3781 void StdMeshers_Cartesian_3D::SetEventListener(SMESH_subMesh* subMesh)
3783 _EventListener::SetOn( subMesh, GetName() );
3786 //================================================================================
3788 * \brief Set _alwaysComputed flag to submeshes of inferior levels to avoid their computing
3790 //================================================================================
3792 void StdMeshers_Cartesian_3D::setSubmeshesComputed(SMESH_Mesh& theMesh,
3793 const TopoDS_Shape& theShape)
3795 for ( TopExp_Explorer soExp( theShape, TopAbs_SOLID ); soExp.More(); soExp.Next() )
3796 _EventListener::setAlwaysComputed( true, theMesh.GetSubMesh( soExp.Current() ));