1 // Copyright (C) 2007-2014 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 "SMESH_Block.hxx"
29 #include "SMESH_Comment.hxx"
30 #include "SMESH_Mesh.hxx"
31 #include "SMESH_MesherHelper.hxx"
32 #include "SMESH_subMesh.hxx"
33 #include "SMESH_subMeshEventListener.hxx"
34 #include "StdMeshers_CartesianParameters3D.hxx"
36 #include <utilities.h>
37 #include <Utils_ExceptHandlers.hxx>
38 #include <Basics_OCCTVersion.hxx>
40 #include <GEOMUtils.hxx>
42 #include <BRepAdaptor_Curve.hxx>
43 #include <BRepAdaptor_Surface.hxx>
44 #include <BRepBndLib.hxx>
45 #include <BRepBuilderAPI_Copy.hxx>
46 #include <BRepBuilderAPI_MakeFace.hxx>
47 #include <BRepTools.hxx>
48 #include <BRep_Builder.hxx>
49 #include <BRep_Tool.hxx>
50 #include <Bnd_B3d.hxx>
51 #include <Bnd_Box.hxx>
53 #include <GCPnts_UniformDeflection.hxx>
54 #include <Geom2d_BSplineCurve.hxx>
55 #include <Geom2d_BezierCurve.hxx>
56 #include <Geom2d_TrimmedCurve.hxx>
57 #include <GeomAPI_ProjectPointOnSurf.hxx>
58 #include <GeomLib.hxx>
59 #include <Geom_BSplineCurve.hxx>
60 #include <Geom_BSplineSurface.hxx>
61 #include <Geom_BezierCurve.hxx>
62 #include <Geom_BezierSurface.hxx>
63 #include <Geom_RectangularTrimmedSurface.hxx>
64 #include <Geom_TrimmedCurve.hxx>
65 #include <IntAna_IntConicQuad.hxx>
66 #include <IntAna_IntLinTorus.hxx>
67 #include <IntAna_Quadric.hxx>
68 #include <IntCurveSurface_TransitionOnCurve.hxx>
69 #include <IntCurvesFace_Intersector.hxx>
70 #include <Poly_Triangulation.hxx>
71 #include <Precision.hxx>
73 #include <TopExp_Explorer.hxx>
74 #include <TopLoc_Location.hxx>
75 #include <TopTools_MapOfShape.hxx>
77 #include <TopoDS_Compound.hxx>
78 #include <TopoDS_Face.hxx>
79 #include <TopoDS_TShape.hxx>
80 #include <gp_Cone.hxx>
81 #include <gp_Cylinder.hxx>
84 #include <gp_Pnt2d.hxx>
85 #include <gp_Sphere.hxx>
86 #include <gp_Torus.hxx>
92 #include <tbb/parallel_for.h>
93 //#include <tbb/enumerable_thread_specific.h>
102 #if OCC_VERSION_LARGE <= 0x06050300
103 // workaround is required only for OCCT6.5.3 and older (see OCC22809)
104 #define ELLIPSOLID_WORKAROUND
107 #ifdef ELLIPSOLID_WORKAROUND
108 #include <BRepIntCurveSurface_Inter.hxx>
109 #include <BRepTopAdaptor_TopolTool.hxx>
110 #include <BRepAdaptor_HSurface.hxx>
113 //=============================================================================
117 //=============================================================================
119 StdMeshers_Cartesian_3D::StdMeshers_Cartesian_3D(int hypId, int studyId, SMESH_Gen * gen)
120 :SMESH_3D_Algo(hypId, studyId, gen)
122 _name = "Cartesian_3D";
123 _shapeType = (1 << TopAbs_SOLID); // 1 bit /shape type
124 _compatibleHypothesis.push_back("CartesianParameters3D");
126 _onlyUnaryInput = false; // to mesh all SOLIDs at once
127 _requireDiscreteBoundary = false; // 2D mesh not needed
128 _supportSubmeshes = false; // do not use any existing mesh
131 //=============================================================================
133 * Check presence of a hypothesis
135 //=============================================================================
137 bool StdMeshers_Cartesian_3D::CheckHypothesis (SMESH_Mesh& aMesh,
138 const TopoDS_Shape& aShape,
139 Hypothesis_Status& aStatus)
141 aStatus = SMESH_Hypothesis::HYP_MISSING;
143 const list<const SMESHDS_Hypothesis*>& hyps = GetUsedHypothesis(aMesh, aShape);
144 list <const SMESHDS_Hypothesis* >::const_iterator h = hyps.begin();
145 if ( h == hyps.end())
150 for ( ; h != hyps.end(); ++h )
152 if (( _hyp = dynamic_cast<const StdMeshers_CartesianParameters3D*>( *h )))
154 aStatus = _hyp->IsDefined() ? HYP_OK : HYP_BAD_PARAMETER;
159 return aStatus == HYP_OK;
166 //=============================================================================
167 // Definitions of internal utils
168 // --------------------------------------------------------------------------
170 Trans_TANGENT = IntCurveSurface_Tangent,
171 Trans_IN = IntCurveSurface_In,
172 Trans_OUT = IntCurveSurface_Out,
175 // --------------------------------------------------------------------------
177 * \brief Common data of any intersection between a Grid and a shape
179 struct B_IntersectPoint
181 mutable const SMDS_MeshNode* _node;
182 mutable vector< TGeomID > _faceIDs;
184 B_IntersectPoint(): _node(NULL) {}
185 void Add( const vector< TGeomID >& fIDs, const SMDS_MeshNode* n=0 ) const;
186 int HasCommonFace( const B_IntersectPoint * other, int avoidFace=-1 ) const;
187 bool IsOnFace( int faceID ) const;
188 virtual ~B_IntersectPoint() {}
190 // --------------------------------------------------------------------------
192 * \brief Data of intersection between a GridLine and a TopoDS_Face
194 struct F_IntersectPoint : public B_IntersectPoint
197 mutable Transition _transition;
198 mutable size_t _indexOnLine;
200 bool operator< ( const F_IntersectPoint& o ) const { return _paramOnLine < o._paramOnLine; }
202 // --------------------------------------------------------------------------
204 * \brief Data of intersection between GridPlanes and a TopoDS_EDGE
206 struct E_IntersectPoint : public B_IntersectPoint
212 // --------------------------------------------------------------------------
214 * \brief A line of the grid and its intersections with 2D geometry
219 double _length; // line length
220 multiset< F_IntersectPoint > _intPoints;
222 void RemoveExcessIntPoints( const double tol );
223 bool GetIsOutBefore( multiset< F_IntersectPoint >::iterator ip, bool prevIsOut );
225 // --------------------------------------------------------------------------
227 * \brief Planes of the grid used to find intersections of an EDGE with a hexahedron
232 vector< gp_XYZ > _origins; // origin points of all planes in one direction
233 vector< double > _zProjs; // projections of origins to _zNorm
235 // --------------------------------------------------------------------------
237 * \brief Iterator on the parallel grid lines of one direction
243 size_t _iVar1, _iVar2, _iConst;
244 string _name1, _name2, _nameConst;
246 LineIndexer( size_t sz1, size_t sz2, size_t sz3,
247 size_t iv1, size_t iv2, size_t iConst,
248 const string& nv1, const string& nv2, const string& nConst )
250 _size[0] = sz1; _size[1] = sz2; _size[2] = sz3;
251 _curInd[0] = _curInd[1] = _curInd[2] = 0;
252 _iVar1 = iv1; _iVar2 = iv2; _iConst = iConst;
253 _name1 = nv1; _name2 = nv2; _nameConst = nConst;
256 size_t I() const { return _curInd[0]; }
257 size_t J() const { return _curInd[1]; }
258 size_t K() const { return _curInd[2]; }
259 void SetIJK( size_t i, size_t j, size_t k )
261 _curInd[0] = i; _curInd[1] = j; _curInd[2] = k;
265 if ( ++_curInd[_iVar1] == _size[_iVar1] )
266 _curInd[_iVar1] = 0, ++_curInd[_iVar2];
268 bool More() const { return _curInd[_iVar2] < _size[_iVar2]; }
269 size_t LineIndex () const { return _curInd[_iVar1] + _curInd[_iVar2]* _size[_iVar1]; }
270 size_t LineIndex10 () const { return (_curInd[_iVar1] + 1 ) + _curInd[_iVar2]* _size[_iVar1]; }
271 size_t LineIndex01 () const { return _curInd[_iVar1] + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
272 size_t LineIndex11 () const { return (_curInd[_iVar1] + 1 ) + (_curInd[_iVar2] + 1 )* _size[_iVar1]; }
273 void SetIndexOnLine (size_t i) { _curInd[ _iConst ] = i; }
274 size_t NbLines() const { return _size[_iVar1] * _size[_iVar2]; }
276 // --------------------------------------------------------------------------
278 * \brief Container of GridLine's
282 vector< double > _coords[3]; // coordinates of grid nodes
283 gp_XYZ _axes [3]; // axis directions
284 vector< GridLine > _lines [3]; // in 3 directions
285 double _tol, _minCellSize;
287 gp_Mat _invB; // inverted basis of _axes
289 vector< const SMDS_MeshNode* > _nodes; // mesh nodes at grid nodes
290 vector< const F_IntersectPoint* > _gridIntP; // grid node intersection with geometry
292 list< E_IntersectPoint > _edgeIntP; // intersections with EDGEs
293 TopTools_IndexedMapOfShape _shapes;
295 SMESH_MesherHelper* _helper;
297 size_t CellIndex( size_t i, size_t j, size_t k ) const
299 return i + j*(_coords[0].size()-1) + k*(_coords[0].size()-1)*(_coords[1].size()-1);
301 size_t NodeIndex( size_t i, size_t j, size_t k ) const
303 return i + j*_coords[0].size() + k*_coords[0].size()*_coords[1].size();
305 size_t NodeIndexDX() const { return 1; }
306 size_t NodeIndexDY() const { return _coords[0].size(); }
307 size_t NodeIndexDZ() const { return _coords[0].size() * _coords[1].size(); }
309 LineIndexer GetLineIndexer(size_t iDir) const;
311 void SetCoordinates(const vector<double>& xCoords,
312 const vector<double>& yCoords,
313 const vector<double>& zCoords,
314 const double* axesDirs,
315 const Bnd_Box& bndBox );
316 void ComputeUVW(const gp_XYZ& p, double uvw[3]);
317 void ComputeNodes(SMESH_MesherHelper& helper);
319 #ifdef ELLIPSOLID_WORKAROUND
320 // --------------------------------------------------------------------------
322 * \brief struct temporary replacing IntCurvesFace_Intersector until
323 * OCCT bug 0022809 is fixed
324 * http://tracker.dev.opencascade.org/view.php?id=22809
326 struct TMP_IntCurvesFace_Intersector
328 BRepAdaptor_Surface _surf;
330 BRepIntCurveSurface_Inter _intcs;
331 vector<IntCurveSurface_IntersectionPoint> _points;
332 BRepTopAdaptor_TopolTool _clsf;
334 TMP_IntCurvesFace_Intersector(const TopoDS_Face& face, const double tol)
335 :_surf( face ), _tol( tol ), _clsf( new BRepAdaptor_HSurface(_surf) ) {}
336 Bnd_Box Bounding() const { Bnd_Box b; BRepBndLib::Add (_surf.Face(), b); return b; }
337 void Perform( const gp_Lin& line, const double w0, const double w1 )
340 for ( _intcs.Init( _surf.Face(), line, _tol ); _intcs.More(); _intcs.Next() )
341 if ( w0 <= _intcs.W() && _intcs.W() <= w1 )
342 _points.push_back( _intcs.Point() );
344 bool IsDone() const { return true; }
345 int NbPnt() const { return _points.size(); }
346 IntCurveSurface_TransitionOnCurve Transition( const int i ) const { return _points[ i-1 ].Transition(); }
347 double WParameter( const int i ) const { return _points[ i-1 ].W(); }
348 TopAbs_State ClassifyUVPoint(const gp_Pnt2d& p) { return _clsf.Classify( p, _tol ); }
350 #define __IntCurvesFace_Intersector TMP_IntCurvesFace_Intersector
352 #define __IntCurvesFace_Intersector IntCurvesFace_Intersector
354 // --------------------------------------------------------------------------
356 * \brief Intersector of TopoDS_Face with all GridLine's
358 struct FaceGridIntersector
364 __IntCurvesFace_Intersector* _surfaceInt;
365 vector< std::pair< GridLine*, F_IntersectPoint > > _intersections;
367 FaceGridIntersector(): _grid(0), _surfaceInt(0) {}
370 void StoreIntersections()
372 for ( size_t i = 0; i < _intersections.size(); ++i )
374 multiset< F_IntersectPoint >::iterator ip =
375 _intersections[i].first->_intPoints.insert( _intersections[i].second );
376 ip->_faceIDs.reserve( 1 );
377 ip->_faceIDs.push_back( _faceID );
380 const Bnd_Box& GetFaceBndBox()
382 GetCurveFaceIntersector();
385 __IntCurvesFace_Intersector* GetCurveFaceIntersector()
389 _surfaceInt = new __IntCurvesFace_Intersector( _face, Precision::PConfusion() );
390 _bndBox = _surfaceInt->Bounding();
391 if ( _bndBox.IsVoid() )
392 BRepBndLib::Add (_face, _bndBox);
396 bool IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const;
398 // --------------------------------------------------------------------------
400 * \brief Intersector of a surface with a GridLine
402 struct FaceLineIntersector
405 double _u, _v, _w; // params on the face and the line
406 Transition _transition; // transition of at intersection (see IntCurveSurface.cdl)
407 Transition _transIn, _transOut; // IN and OUT transitions depending of face orientation
410 gp_Cylinder _cylinder;
414 __IntCurvesFace_Intersector* _surfaceInt;
416 vector< F_IntersectPoint > _intPoints;
418 void IntersectWithPlane (const GridLine& gridLine);
419 void IntersectWithCylinder(const GridLine& gridLine);
420 void IntersectWithCone (const GridLine& gridLine);
421 void IntersectWithSphere (const GridLine& gridLine);
422 void IntersectWithTorus (const GridLine& gridLine);
423 void IntersectWithSurface (const GridLine& gridLine);
425 bool UVIsOnFace() const;
426 void addIntPoint(const bool toClassify=true);
427 bool isParamOnLineOK( const double linLength )
429 return -_tol < _w && _w < linLength + _tol;
431 FaceLineIntersector():_surfaceInt(0) {}
432 ~FaceLineIntersector() { if (_surfaceInt ) delete _surfaceInt; _surfaceInt = 0; }
434 // --------------------------------------------------------------------------
436 * \brief Class representing topology of the hexahedron and creating a mesh
437 * volume basing on analysis of hexahedron intersection with geometry
441 // --------------------------------------------------------------------------------
444 // --------------------------------------------------------------------------------
445 struct _Node //!< node either at a hexahedron corner or at intersection
447 const SMDS_MeshNode* _node; // mesh node at hexahedron corner
448 const B_IntersectPoint* _intPoint;
449 const _Face* _usedInFace;
451 _Node(const SMDS_MeshNode* n=0, const B_IntersectPoint* ip=0)
452 :_node(n), _intPoint(ip), _usedInFace(0) {}
453 const SMDS_MeshNode* Node() const
454 { return ( _intPoint && _intPoint->_node ) ? _intPoint->_node : _node; }
455 //const F_IntersectPoint* FaceIntPnt() const
456 //{ return static_cast< const F_IntersectPoint* >( _intPoint ); }
457 const E_IntersectPoint* EdgeIntPnt() const
458 { return static_cast< const E_IntersectPoint* >( _intPoint ); }
459 bool IsUsedInFace( const _Face* polygon = 0 )
461 return polygon ? ( _usedInFace == polygon ) : bool( _usedInFace );
463 void Add( const E_IntersectPoint* ip )
468 else if ( !_intPoint->_node ) {
469 ip->Add( _intPoint->_faceIDs );
473 _intPoint->Add( ip->_faceIDs );
476 int IsLinked( const B_IntersectPoint* other,
477 int avoidFace=-1 ) const // returns id of a common face
479 return _intPoint ? _intPoint->HasCommonFace( other, avoidFace ) : 0;
481 bool IsOnFace( int faceID ) const // returns true if faceID is found
483 return _intPoint ? _intPoint->IsOnFace( faceID ) : false;
487 if ( const SMDS_MeshNode* n = Node() )
488 return SMESH_TNodeXYZ( n );
489 if ( const E_IntersectPoint* eip =
490 dynamic_cast< const E_IntersectPoint* >( _intPoint ))
492 return gp_Pnt( 1e100, 0, 0 );
495 // --------------------------------------------------------------------------------
496 struct _Link // link connecting two _Node's
499 _Face* _faces[2]; // polygons sharing a link
500 vector< const F_IntersectPoint* > _fIntPoints; // GridLine intersections with FACEs
501 vector< _Node* > _fIntNodes; // _Node's at _fIntPoints
502 vector< _Link > _splits;
503 _Link() { _faces[0] = 0; }
505 // --------------------------------------------------------------------------------
510 _OrientedLink( _Link* link=0, bool reverse=false ): _link(link), _reverse(reverse) {}
511 void Reverse() { _reverse = !_reverse; }
512 int NbResultLinks() const { return _link->_splits.size(); }
513 _OrientedLink ResultLink(int i) const
515 return _OrientedLink(&_link->_splits[_reverse ? NbResultLinks()-i-1 : i],_reverse);
517 _Node* FirstNode() const { return _link->_nodes[ _reverse ]; }
518 _Node* LastNode() const { return _link->_nodes[ !_reverse ]; }
519 operator bool() const { return _link; }
520 vector< TGeomID > GetNotUsedFace(const set<TGeomID>& usedIDs ) const // returns supporting FACEs
522 vector< TGeomID > faces;
523 const B_IntersectPoint *ip0, *ip1;
524 if (( ip0 = _link->_nodes[0]->_intPoint ) &&
525 ( ip1 = _link->_nodes[1]->_intPoint ))
527 for ( size_t i = 0; i < ip0->_faceIDs.size(); ++i )
528 if ( ip1->IsOnFace ( ip0->_faceIDs[i] ) &&
529 !usedIDs.count( ip0->_faceIDs[i] ) )
530 faces.push_back( ip0->_faceIDs[i] );
534 bool HasEdgeNodes() const
536 return ( dynamic_cast< const E_IntersectPoint* >( _link->_nodes[0]->_intPoint ) ||
537 dynamic_cast< const E_IntersectPoint* >( _link->_nodes[1]->_intPoint ));
541 return !_link->_faces[0] ? 0 : 1 + bool( _link->_faces[1] );
543 void AddFace( _Face* f )
545 if ( _link->_faces[0] )
547 _link->_faces[1] = f;
551 _link->_faces[0] = f;
552 _link->_faces[1] = 0;
555 void RemoveFace( _Face* f )
557 if ( !_link->_faces[0] ) return;
559 if ( _link->_faces[1] == f )
561 _link->_faces[1] = 0;
563 else if ( _link->_faces[0] == f )
565 _link->_faces[0] = 0;
566 if ( _link->_faces[1] )
568 _link->_faces[0] = _link->_faces[1];
569 _link->_faces[1] = 0;
574 // --------------------------------------------------------------------------------
577 vector< _OrientedLink > _links; // links on GridLine's
578 vector< _Link > _polyLinks; // links added to close a polygonal face
579 vector< _Node* > _eIntNodes; // nodes at intersection with EDGEs
580 bool isPolyLink( const _OrientedLink& ol )
582 return _polyLinks.empty() ? false :
583 ( &_polyLinks[0] <= ol._link && ol._link <= &_polyLinks.back() );
586 // --------------------------------------------------------------------------------
587 struct _volumeDef // holder of nodes of a volume mesh element
589 vector< _Node* > _nodes;
590 vector< int > _quantities;
591 typedef boost::shared_ptr<_volumeDef> Ptr;
592 void set( const vector< _Node* >& nodes,
593 const vector< int >& quant = vector< int >() )
594 { _nodes = nodes; _quantities = quant; }
597 // topology of a hexahedron
600 _Link _hexLinks [12];
603 // faces resulted from hexahedron intersection
604 vector< _Face > _polygons;
606 // intresections with EDGEs
607 vector< const E_IntersectPoint* > _eIntPoints;
609 // additional nodes created at intersection points
610 vector< _Node > _intNodes;
612 // nodes inside the hexahedron (at VERTEXes)
613 vector< _Node* > _vIntNodes;
615 // computed volume elements
616 //vector< _volumeDef::Ptr > _volumeDefs;
617 _volumeDef _volumeDefs;
620 double _sizeThreshold, _sideLength[3];
621 int _nbCornerNodes, _nbFaceIntNodes, _nbBndNodes;
622 int _origNodeInd; // index of _hexNodes[0] node within the _grid
626 Hexahedron(const double sizeThreshold, Grid* grid);
627 int MakeElements(SMESH_MesherHelper& helper,
628 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
629 void ComputeElements();
630 void Init() { init( _i, _j, _k ); }
633 Hexahedron(const Hexahedron& other );
634 void init( size_t i, size_t j, size_t k );
635 void init( size_t i );
636 void addEdges(SMESH_MesherHelper& helper,
637 vector< Hexahedron* >& intersectedHex,
638 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap);
639 gp_Pnt findIntPoint( double u1, double proj1, double u2, double proj2,
640 double proj, BRepAdaptor_Curve& curve,
641 const gp_XYZ& axis, const gp_XYZ& origin );
642 int getEntity( const E_IntersectPoint* ip, int* facets, int& sub );
643 bool addIntersection( const E_IntersectPoint& ip,
644 vector< Hexahedron* >& hexes,
645 int ijk[], int dIJK[] );
646 bool findChain( _Node* n1, _Node* n2, _Face& quad, vector<_Node*>& chainNodes );
647 bool closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const;
648 int addElements(SMESH_MesherHelper& helper);
649 bool is1stNodeOut( _Link& link ) const;
650 bool isInHole() const;
651 bool checkPolyhedronSize() const;
656 bool debugDumpLink( _Link* link );
657 _Node* FindEqualNode( vector< _Node* >& nodes,
658 const E_IntersectPoint* ip,
661 for ( size_t i = 0; i < nodes.size(); ++i )
662 if ( nodes[i]->EdgeIntPnt() == ip ||
663 nodes[i]->Point().SquareDistance( ip->_point ) <= tol2 )
670 // --------------------------------------------------------------------------
672 * \brief Hexahedron computing volumes in one thread
674 struct ParallelHexahedron
676 vector< Hexahedron* >& _hexVec;
678 ParallelHexahedron( vector< Hexahedron* >& hv, vector<int>& ind): _hexVec(hv), _index(ind) {}
679 void operator() ( const tbb::blocked_range<size_t>& r ) const
681 for ( size_t i = r.begin(); i != r.end(); ++i )
682 if ( Hexahedron* hex = _hexVec[ _index[i]] )
683 hex->ComputeElements();
686 // --------------------------------------------------------------------------
688 * \brief Structure intersecting certain nb of faces with GridLine's in one thread
690 struct ParallelIntersector
692 vector< FaceGridIntersector >& _faceVec;
693 ParallelIntersector( vector< FaceGridIntersector >& faceVec): _faceVec(faceVec){}
694 void operator() ( const tbb::blocked_range<size_t>& r ) const
696 for ( size_t i = r.begin(); i != r.end(); ++i )
697 _faceVec[i].Intersect();
702 //=============================================================================
703 // Implementation of internal utils
704 //=============================================================================
706 * \brief adjust \a i to have \a val between values[i] and values[i+1]
708 inline void locateValue( int & i, double val, const vector<double>& values,
709 int& di, double tol )
711 //val += values[0]; // input \a val is measured from 0.
712 if ( i > values.size()-2 )
715 while ( i+2 < values.size() && val > values[ i+1 ])
717 while ( i > 0 && val < values[ i ])
720 if ( i > 0 && val - values[ i ] < tol )
722 else if ( i+2 < values.size() && values[ i+1 ] - val < tol )
727 //=============================================================================
729 * Remove coincident intersection points
731 void GridLine::RemoveExcessIntPoints( const double tol )
733 if ( _intPoints.size() < 2 ) return;
735 set< Transition > tranSet;
736 multiset< F_IntersectPoint >::iterator ip1, ip2 = _intPoints.begin();
737 while ( ip2 != _intPoints.end() )
741 while ( ip2 != _intPoints.end() && ip2->_paramOnLine - ip1->_paramOnLine <= tol )
743 tranSet.insert( ip1->_transition );
744 tranSet.insert( ip2->_transition );
745 ip2->Add( ip1->_faceIDs );
746 _intPoints.erase( ip1 );
749 if ( tranSet.size() > 1 ) // points with different transition coincide
751 bool isIN = tranSet.count( Trans_IN );
752 bool isOUT = tranSet.count( Trans_OUT );
754 (*ip1)._transition = Trans_TANGENT;
756 (*ip1)._transition = isIN ? Trans_IN : Trans_OUT;
760 //================================================================================
762 * Return "is OUT" state for nodes before the given intersection point
764 bool GridLine::GetIsOutBefore( multiset< F_IntersectPoint >::iterator ip, bool prevIsOut )
766 if ( ip->_transition == Trans_IN )
768 if ( ip->_transition == Trans_OUT )
770 if ( ip->_transition == Trans_APEX )
772 // singularity point (apex of a cone)
773 if ( _intPoints.size() == 1 || ip == _intPoints.begin() )
775 multiset< F_IntersectPoint >::iterator ipBef = ip, ipAft = ++ip;
776 if ( ipAft == _intPoints.end() )
779 if ( ipBef->_transition != ipAft->_transition )
780 return ( ipBef->_transition == Trans_OUT );
781 return ( ipBef->_transition != Trans_OUT );
783 // _transition == Trans_TANGENT
786 //================================================================================
790 void B_IntersectPoint::Add( const vector< TGeomID >& fIDs,
791 const SMDS_MeshNode* n) const
793 if ( _faceIDs.empty() )
796 for ( size_t i = 0; i < fIDs.size(); ++i )
798 vector< TGeomID >::iterator it =
799 std::find( _faceIDs.begin(), _faceIDs.end(), fIDs[i] );
800 if ( it == _faceIDs.end() )
801 _faceIDs.push_back( fIDs[i] );
806 //================================================================================
808 * Returns index of a common face if any, else zero
810 int B_IntersectPoint::HasCommonFace( const B_IntersectPoint * other, int avoidFace ) const
813 for ( size_t i = 0; i < other->_faceIDs.size(); ++i )
814 if ( avoidFace != other->_faceIDs[i] &&
815 IsOnFace ( other->_faceIDs[i] ))
816 return other->_faceIDs[i];
819 //================================================================================
821 * Returns \c true if \a faceID in in this->_faceIDs
823 bool B_IntersectPoint::IsOnFace( int faceID ) const // returns true if faceID is found
825 vector< TGeomID >::const_iterator it =
826 std::find( _faceIDs.begin(), _faceIDs.end(), faceID );
827 return ( it != _faceIDs.end() );
829 //================================================================================
831 * Return an iterator on GridLine's in a given direction
833 LineIndexer Grid::GetLineIndexer(size_t iDir) const
835 const size_t indices[] = { 1,2,0, 0,2,1, 0,1,2 };
836 const string s [] = { "X", "Y", "Z" };
837 LineIndexer li( _coords[0].size(), _coords[1].size(), _coords[2].size(),
838 indices[iDir*3], indices[iDir*3+1], indices[iDir*3+2],
839 s[indices[iDir*3]], s[indices[iDir*3+1]], s[indices[iDir*3+2]]);
842 //=============================================================================
844 * Creates GridLine's of the grid
846 void Grid::SetCoordinates(const vector<double>& xCoords,
847 const vector<double>& yCoords,
848 const vector<double>& zCoords,
849 const double* axesDirs,
850 const Bnd_Box& shapeBox)
852 _coords[0] = xCoords;
853 _coords[1] = yCoords;
854 _coords[2] = zCoords;
856 _axes[0].SetCoord( axesDirs[0],
859 _axes[1].SetCoord( axesDirs[3],
862 _axes[2].SetCoord( axesDirs[6],
865 _axes[0].Normalize();
866 _axes[1].Normalize();
867 _axes[2].Normalize();
869 _invB.SetCols( _axes[0], _axes[1], _axes[2] );
873 _minCellSize = Precision::Infinite();
874 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
876 for ( size_t i = 1; i < _coords[ iDir ].size(); ++i )
878 double cellLen = _coords[ iDir ][ i ] - _coords[ iDir ][ i-1 ];
879 if ( cellLen < _minCellSize )
880 _minCellSize = cellLen;
883 if ( _minCellSize < Precision::Confusion() )
884 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
885 SMESH_Comment("Too small cell size: ") << _minCellSize );
886 _tol = _minCellSize / 1000.;
888 // attune grid extremities to shape bounding box
890 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
891 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
892 double* cP[6] = { &_coords[0].front(), &_coords[1].front(), &_coords[2].front(),
893 &_coords[0].back(), &_coords[1].back(), &_coords[2].back() };
894 for ( int i = 0; i < 6; ++i )
895 if ( fabs( sP[i] - *cP[i] ) < _tol )
896 *cP[i] = sP[i];// + _tol/1000. * ( i < 3 ? +1 : -1 );
898 for ( int iDir = 0; iDir < 3; ++iDir )
900 if ( _coords[iDir][0] - sP[iDir] > _tol )
902 _minCellSize = Min( _minCellSize, _coords[iDir][0] - sP[iDir] );
903 _coords[iDir].insert( _coords[iDir].begin(), sP[iDir] + _tol/1000.);
905 if ( sP[iDir+3] - _coords[iDir].back() > _tol )
907 _minCellSize = Min( _minCellSize, sP[iDir+3] - _coords[iDir].back() );
908 _coords[iDir].push_back( sP[iDir+3] - _tol/1000.);
911 _tol = _minCellSize / 1000.;
913 _origin = ( _coords[0][0] * _axes[0] +
914 _coords[1][0] * _axes[1] +
915 _coords[2][0] * _axes[2] );
918 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
920 LineIndexer li = GetLineIndexer( iDir );
921 _lines[iDir].resize( li.NbLines() );
922 double len = _coords[ iDir ].back() - _coords[iDir].front();
923 for ( ; li.More(); ++li )
925 GridLine& gl = _lines[iDir][ li.LineIndex() ];
926 gl._line.SetLocation( _coords[0][li.I()] * _axes[0] +
927 _coords[1][li.J()] * _axes[1] +
928 _coords[2][li.K()] * _axes[2] );
929 gl._line.SetDirection( _axes[ iDir ]);
934 //================================================================================
936 * Computes coordinates of a point in the grid CS
938 void Grid::ComputeUVW(const gp_XYZ& P, double UVW[3])
940 gp_XYZ p = P * _invB;
941 p.Coord( UVW[0], UVW[1], UVW[2] );
943 //================================================================================
947 void Grid::ComputeNodes(SMESH_MesherHelper& helper)
949 // state of each node of the grid relative to the geometry
950 const size_t nbGridNodes = _coords[0].size() * _coords[1].size() * _coords[2].size();
951 vector< bool > isNodeOut( nbGridNodes, false );
952 _nodes.resize( nbGridNodes, 0 );
953 _gridIntP.resize( nbGridNodes, NULL );
955 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
957 LineIndexer li = GetLineIndexer( iDir );
959 // find out a shift of node index while walking along a GridLine in this direction
960 li.SetIndexOnLine( 0 );
961 size_t nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
962 li.SetIndexOnLine( 1 );
963 const size_t nShift = NodeIndex( li.I(), li.J(), li.K() ) - nIndex0;
965 const vector<double> & coords = _coords[ iDir ];
966 for ( ; li.More(); ++li ) // loop on lines in iDir
968 li.SetIndexOnLine( 0 );
969 nIndex0 = NodeIndex( li.I(), li.J(), li.K() );
971 GridLine& line = _lines[ iDir ][ li.LineIndex() ];
972 const gp_XYZ lineLoc = line._line.Location().XYZ();
973 const gp_XYZ lineDir = line._line.Direction().XYZ();
974 line.RemoveExcessIntPoints( _tol );
975 multiset< F_IntersectPoint >& intPnts = line._intPoints;
976 multiset< F_IntersectPoint >::iterator ip = intPnts.begin();
979 const double* nodeCoord = & coords[0];
980 const double* coord0 = nodeCoord;
981 const double* coordEnd = coord0 + coords.size();
982 double nodeParam = 0;
983 for ( ; ip != intPnts.end(); ++ip )
985 // set OUT state or just skip IN nodes before ip
986 if ( nodeParam < ip->_paramOnLine - _tol )
988 isOut = line.GetIsOutBefore( ip, isOut );
990 while ( nodeParam < ip->_paramOnLine - _tol )
993 isNodeOut[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = isOut;
994 if ( ++nodeCoord < coordEnd )
995 nodeParam = *nodeCoord - *coord0;
999 if ( nodeCoord == coordEnd ) break;
1001 // create a mesh node on a GridLine at ip if it does not coincide with a grid node
1002 if ( nodeParam > ip->_paramOnLine + _tol )
1004 // li.SetIndexOnLine( 0 );
1005 // double xyz[3] = { _coords[0][ li.I() ], _coords[1][ li.J() ], _coords[2][ li.K() ]};
1006 // xyz[ li._iConst ] += ip->_paramOnLine;
1007 gp_XYZ xyz = lineLoc + ip->_paramOnLine * lineDir;
1008 ip->_node = helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1009 ip->_indexOnLine = nodeCoord-coord0-1;
1011 // create a mesh node at ip concident with a grid node
1014 int nodeIndex = nIndex0 + nShift * ( nodeCoord-coord0 );
1015 if ( !_nodes[ nodeIndex ] )
1017 //li.SetIndexOnLine( nodeCoord-coord0 );
1018 //double xyz[3] = { _coords[0][ li.I() ], _coords[1][ li.J() ], _coords[2][ li.K() ]};
1019 gp_XYZ xyz = lineLoc + nodeParam * lineDir;
1020 _nodes [ nodeIndex ] = helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1021 _gridIntP[ nodeIndex ] = & * ip;
1023 if ( _gridIntP[ nodeIndex ] )
1024 _gridIntP[ nodeIndex ]->Add( ip->_faceIDs );
1026 _gridIntP[ nodeIndex ] = & * ip;
1027 // ip->_node = _nodes[ nodeIndex ]; -- to differ from ip on links
1028 ip->_indexOnLine = nodeCoord-coord0;
1029 if ( ++nodeCoord < coordEnd )
1030 nodeParam = *nodeCoord - *coord0;
1033 // set OUT state to nodes after the last ip
1034 for ( ; nodeCoord < coordEnd; ++nodeCoord )
1035 isNodeOut[ nIndex0 + nShift * ( nodeCoord-coord0 ) ] = true;
1039 // Create mesh nodes at !OUT nodes of the grid
1041 for ( size_t z = 0; z < _coords[2].size(); ++z )
1042 for ( size_t y = 0; y < _coords[1].size(); ++y )
1043 for ( size_t x = 0; x < _coords[0].size(); ++x )
1045 size_t nodeIndex = NodeIndex( x, y, z );
1046 if ( !isNodeOut[ nodeIndex ] && !_nodes[ nodeIndex] )
1048 //_nodes[ nodeIndex ] = helper.AddNode( _coords[0][x], _coords[1][y], _coords[2][z] );
1049 gp_XYZ xyz = ( _coords[0][x] * _axes[0] +
1050 _coords[1][y] * _axes[1] +
1051 _coords[2][z] * _axes[2] );
1052 _nodes[ nodeIndex ] = helper.AddNode( xyz.X(), xyz.Y(), xyz.Z() );
1057 // check validity of transitions
1058 const char* trName[] = { "TANGENT", "IN", "OUT", "APEX" };
1059 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1061 LineIndexer li = GetLineIndexer( iDir );
1062 for ( ; li.More(); ++li )
1064 multiset< F_IntersectPoint >& intPnts = _lines[ iDir ][ li.LineIndex() ]._intPoints;
1065 if ( intPnts.empty() ) continue;
1066 if ( intPnts.size() == 1 )
1068 if ( intPnts.begin()->_transition != Trans_TANGENT &&
1069 intPnts.begin()->_transition != Trans_APEX )
1070 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1071 SMESH_Comment("Wrong SOLE transition of GridLine (")
1072 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1073 << ") along " << li._nameConst
1074 << ": " << trName[ intPnts.begin()->_transition] );
1078 if ( intPnts.begin()->_transition == Trans_OUT )
1079 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1080 SMESH_Comment("Wrong START transition of GridLine (")
1081 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1082 << ") along " << li._nameConst
1083 << ": " << trName[ intPnts.begin()->_transition ]);
1084 if ( intPnts.rbegin()->_transition == Trans_IN )
1085 throw SMESH_ComputeError (COMPERR_ALGO_FAILED,
1086 SMESH_Comment("Wrong END transition of GridLine (")
1087 << li._curInd[li._iVar1] << ", " << li._curInd[li._iVar2]
1088 << ") along " << li._nameConst
1089 << ": " << trName[ intPnts.rbegin()->_transition ]);
1096 //=============================================================================
1098 * Intersects TopoDS_Face with all GridLine's
1100 void FaceGridIntersector::Intersect()
1102 FaceLineIntersector intersector;
1103 intersector._surfaceInt = GetCurveFaceIntersector();
1104 intersector._tol = _grid->_tol;
1105 intersector._transOut = _face.Orientation() == TopAbs_REVERSED ? Trans_IN : Trans_OUT;
1106 intersector._transIn = _face.Orientation() == TopAbs_REVERSED ? Trans_OUT : Trans_IN;
1108 typedef void (FaceLineIntersector::* PIntFun )(const GridLine& gridLine);
1109 PIntFun interFunction;
1111 bool isDirect = true;
1112 BRepAdaptor_Surface surf( _face );
1113 switch ( surf.GetType() ) {
1115 intersector._plane = surf.Plane();
1116 interFunction = &FaceLineIntersector::IntersectWithPlane;
1117 isDirect = intersector._plane.Direct();
1119 case GeomAbs_Cylinder:
1120 intersector._cylinder = surf.Cylinder();
1121 interFunction = &FaceLineIntersector::IntersectWithCylinder;
1122 isDirect = intersector._cylinder.Direct();
1125 intersector._cone = surf.Cone();
1126 interFunction = &FaceLineIntersector::IntersectWithCone;
1127 //isDirect = intersector._cone.Direct();
1129 case GeomAbs_Sphere:
1130 intersector._sphere = surf.Sphere();
1131 interFunction = &FaceLineIntersector::IntersectWithSphere;
1132 isDirect = intersector._sphere.Direct();
1135 intersector._torus = surf.Torus();
1136 interFunction = &FaceLineIntersector::IntersectWithTorus;
1137 //isDirect = intersector._torus.Direct();
1140 interFunction = &FaceLineIntersector::IntersectWithSurface;
1143 std::swap( intersector._transOut, intersector._transIn );
1145 _intersections.clear();
1146 for ( int iDir = 0; iDir < 3; ++iDir ) // loop on 3 line directions
1148 if ( surf.GetType() == GeomAbs_Plane )
1150 // check if all lines in this direction are parallel to a plane
1151 if ( intersector._plane.Axis().IsNormal( _grid->_lines[iDir][0]._line.Position(),
1152 Precision::Angular()))
1154 // find out a transition, that is the same for all lines of a direction
1155 gp_Dir plnNorm = intersector._plane.Axis().Direction();
1156 gp_Dir lineDir = _grid->_lines[iDir][0]._line.Direction();
1157 intersector._transition =
1158 ( plnNorm * lineDir < 0 ) ? intersector._transIn : intersector._transOut;
1160 if ( surf.GetType() == GeomAbs_Cylinder )
1162 // check if all lines in this direction are parallel to a cylinder
1163 if ( intersector._cylinder.Axis().IsParallel( _grid->_lines[iDir][0]._line.Position(),
1164 Precision::Angular()))
1168 // intersect the grid lines with the face
1169 for ( size_t iL = 0; iL < _grid->_lines[iDir].size(); ++iL )
1171 GridLine& gridLine = _grid->_lines[iDir][iL];
1172 if ( _bndBox.IsOut( gridLine._line )) continue;
1174 intersector._intPoints.clear();
1175 (intersector.*interFunction)( gridLine ); // <- intersection with gridLine
1176 for ( size_t i = 0; i < intersector._intPoints.size(); ++i )
1177 _intersections.push_back( make_pair( &gridLine, intersector._intPoints[i] ));
1181 //================================================================================
1183 * Return true if (_u,_v) is on the face
1185 bool FaceLineIntersector::UVIsOnFace() const
1187 TopAbs_State state = _surfaceInt->ClassifyUVPoint(gp_Pnt2d( _u,_v ));
1188 return ( state == TopAbs_IN || state == TopAbs_ON );
1190 //================================================================================
1192 * Store an intersection if it is IN or ON the face
1194 void FaceLineIntersector::addIntPoint(const bool toClassify)
1196 if ( !toClassify || UVIsOnFace() )
1199 p._paramOnLine = _w;
1200 p._transition = _transition;
1201 _intPoints.push_back( p );
1204 //================================================================================
1206 * Intersect a line with a plane
1208 void FaceLineIntersector::IntersectWithPlane (const GridLine& gridLine)
1210 IntAna_IntConicQuad linPlane( gridLine._line, _plane, Precision::Angular());
1211 _w = linPlane.ParamOnConic(1);
1212 if ( isParamOnLineOK( gridLine._length ))
1214 ElSLib::Parameters(_plane, linPlane.Point(1) ,_u,_v);
1218 //================================================================================
1220 * Intersect a line with a cylinder
1222 void FaceLineIntersector::IntersectWithCylinder(const GridLine& gridLine)
1224 IntAna_IntConicQuad linCylinder( gridLine._line, _cylinder );
1225 if ( linCylinder.IsDone() && linCylinder.NbPoints() > 0 )
1227 _w = linCylinder.ParamOnConic(1);
1228 if ( linCylinder.NbPoints() == 1 )
1229 _transition = Trans_TANGENT;
1231 _transition = _w < linCylinder.ParamOnConic(2) ? _transIn : _transOut;
1232 if ( isParamOnLineOK( gridLine._length ))
1234 ElSLib::Parameters(_cylinder, linCylinder.Point(1) ,_u,_v);
1237 if ( linCylinder.NbPoints() > 1 )
1239 _w = linCylinder.ParamOnConic(2);
1240 if ( isParamOnLineOK( gridLine._length ))
1242 ElSLib::Parameters(_cylinder, linCylinder.Point(2) ,_u,_v);
1243 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
1249 //================================================================================
1251 * Intersect a line with a cone
1253 void FaceLineIntersector::IntersectWithCone (const GridLine& gridLine)
1255 IntAna_IntConicQuad linCone(gridLine._line,_cone);
1256 if ( !linCone.IsDone() ) return;
1258 gp_Vec du, dv, norm;
1259 for ( int i = 1; i <= linCone.NbPoints(); ++i )
1261 _w = linCone.ParamOnConic( i );
1262 if ( !isParamOnLineOK( gridLine._length )) continue;
1263 ElSLib::Parameters(_cone, linCone.Point(i) ,_u,_v);
1266 ElSLib::D1( _u, _v, _cone, P, du, dv );
1268 double normSize2 = norm.SquareMagnitude();
1269 if ( normSize2 > Precision::Angular() * Precision::Angular() )
1271 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
1272 cos /= sqrt( normSize2 );
1273 if ( cos < -Precision::Angular() )
1274 _transition = _transIn;
1275 else if ( cos > Precision::Angular() )
1276 _transition = _transOut;
1278 _transition = Trans_TANGENT;
1282 _transition = Trans_APEX;
1284 addIntPoint( /*toClassify=*/false);
1288 //================================================================================
1290 * Intersect a line with a sphere
1292 void FaceLineIntersector::IntersectWithSphere (const GridLine& gridLine)
1294 IntAna_IntConicQuad linSphere(gridLine._line,_sphere);
1295 if ( linSphere.IsDone() && linSphere.NbPoints() > 0 )
1297 _w = linSphere.ParamOnConic(1);
1298 if ( linSphere.NbPoints() == 1 )
1299 _transition = Trans_TANGENT;
1301 _transition = _w < linSphere.ParamOnConic(2) ? _transIn : _transOut;
1302 if ( isParamOnLineOK( gridLine._length ))
1304 ElSLib::Parameters(_sphere, linSphere.Point(1) ,_u,_v);
1307 if ( linSphere.NbPoints() > 1 )
1309 _w = linSphere.ParamOnConic(2);
1310 if ( isParamOnLineOK( gridLine._length ))
1312 ElSLib::Parameters(_sphere, linSphere.Point(2) ,_u,_v);
1313 _transition = ( _transition == Trans_OUT ) ? Trans_IN : Trans_OUT;
1319 //================================================================================
1321 * Intersect a line with a torus
1323 void FaceLineIntersector::IntersectWithTorus (const GridLine& gridLine)
1325 IntAna_IntLinTorus linTorus(gridLine._line,_torus);
1326 if ( !linTorus.IsDone()) return;
1328 gp_Vec du, dv, norm;
1329 for ( int i = 1; i <= linTorus.NbPoints(); ++i )
1331 _w = linTorus.ParamOnLine( i );
1332 if ( !isParamOnLineOK( gridLine._length )) continue;
1333 linTorus.ParamOnTorus( i, _u,_v );
1336 ElSLib::D1( _u, _v, _torus, P, du, dv );
1338 double normSize = norm.Magnitude();
1339 double cos = norm.XYZ() * gridLine._line.Direction().XYZ();
1341 if ( cos < -Precision::Angular() )
1342 _transition = _transIn;
1343 else if ( cos > Precision::Angular() )
1344 _transition = _transOut;
1346 _transition = Trans_TANGENT;
1347 addIntPoint( /*toClassify=*/false);
1351 //================================================================================
1353 * Intersect a line with a non-analytical surface
1355 void FaceLineIntersector::IntersectWithSurface (const GridLine& gridLine)
1357 _surfaceInt->Perform( gridLine._line, 0.0, gridLine._length );
1358 if ( !_surfaceInt->IsDone() ) return;
1359 for ( int i = 1; i <= _surfaceInt->NbPnt(); ++i )
1361 _transition = Transition( _surfaceInt->Transition( i ) );
1362 _w = _surfaceInt->WParameter( i );
1363 addIntPoint(/*toClassify=*/false);
1366 //================================================================================
1368 * check if its face can be safely intersected in a thread
1370 bool FaceGridIntersector::IsThreadSafe(set< const Standard_Transient* >& noSafeTShapes) const
1375 TopLoc_Location loc;
1376 Handle(Geom_Surface) surf = BRep_Tool::Surface( _face, loc );
1377 Handle(Geom_RectangularTrimmedSurface) ts =
1378 Handle(Geom_RectangularTrimmedSurface)::DownCast( surf );
1379 while( !ts.IsNull() ) {
1380 surf = ts->BasisSurface();
1381 ts = Handle(Geom_RectangularTrimmedSurface)::DownCast(surf);
1383 if ( surf->IsKind( STANDARD_TYPE(Geom_BSplineSurface )) ||
1384 surf->IsKind( STANDARD_TYPE(Geom_BezierSurface )))
1385 if ( !noSafeTShapes.insert((const Standard_Transient*) _face.TShape() ).second )
1389 TopExp_Explorer exp( _face, TopAbs_EDGE );
1390 for ( ; exp.More(); exp.Next() )
1392 bool edgeIsSafe = true;
1393 const TopoDS_Edge& e = TopoDS::Edge( exp.Current() );
1396 Handle(Geom_Curve) c = BRep_Tool::Curve( e, loc, f, l);
1399 Handle(Geom_TrimmedCurve) tc = Handle(Geom_TrimmedCurve)::DownCast(c);
1400 while( !tc.IsNull() ) {
1401 c = tc->BasisCurve();
1402 tc = Handle(Geom_TrimmedCurve)::DownCast(c);
1404 if ( c->IsKind( STANDARD_TYPE(Geom_BSplineCurve )) ||
1405 c->IsKind( STANDARD_TYPE(Geom_BezierCurve )))
1412 Handle(Geom2d_Curve) c2 = BRep_Tool::CurveOnSurface( e, surf, loc, f, l);
1415 Handle(Geom2d_TrimmedCurve) tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
1416 while( !tc.IsNull() ) {
1417 c2 = tc->BasisCurve();
1418 tc = Handle(Geom2d_TrimmedCurve)::DownCast(c2);
1420 if ( c2->IsKind( STANDARD_TYPE(Geom2d_BSplineCurve )) ||
1421 c2->IsKind( STANDARD_TYPE(Geom2d_BezierCurve )))
1425 if ( !edgeIsSafe && !noSafeTShapes.insert((const Standard_Transient*) e.TShape() ).second )
1430 //================================================================================
1432 * \brief Creates topology of the hexahedron
1434 Hexahedron::Hexahedron(const double sizeThreshold, Grid* grid)
1435 : _grid( grid ), _sizeThreshold( sizeThreshold ), _nbFaceIntNodes(0)
1437 _polygons.reserve(100); // to avoid reallocation;
1439 //set nodes shift within grid->_nodes from the node 000
1440 size_t dx = _grid->NodeIndexDX();
1441 size_t dy = _grid->NodeIndexDY();
1442 size_t dz = _grid->NodeIndexDZ();
1444 size_t i100 = i000 + dx;
1445 size_t i010 = i000 + dy;
1446 size_t i110 = i010 + dx;
1447 size_t i001 = i000 + dz;
1448 size_t i101 = i100 + dz;
1449 size_t i011 = i010 + dz;
1450 size_t i111 = i110 + dz;
1451 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V000 )] = i000;
1452 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V100 )] = i100;
1453 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V010 )] = i010;
1454 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V110 )] = i110;
1455 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V001 )] = i001;
1456 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V101 )] = i101;
1457 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V011 )] = i011;
1458 _nodeShift[ SMESH_Block::ShapeIndex( SMESH_Block::ID_V111 )] = i111;
1460 vector< int > idVec;
1461 // set nodes to links
1462 for ( int linkID = SMESH_Block::ID_Ex00; linkID <= SMESH_Block::ID_E11z; ++linkID )
1464 SMESH_Block::GetEdgeVertexIDs( linkID, idVec );
1465 _Link& link = _hexLinks[ SMESH_Block::ShapeIndex( linkID )];
1466 link._nodes[0] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[0] )];
1467 link._nodes[1] = &_hexNodes[ SMESH_Block::ShapeIndex( idVec[1] )];
1470 // set links to faces
1471 int interlace[4] = { 0, 3, 1, 2 }; // to walk by links around a face: { u0, 1v, u1, 0v }
1472 for ( int faceID = SMESH_Block::ID_Fxy0; faceID <= SMESH_Block::ID_F1yz; ++faceID )
1474 SMESH_Block::GetFaceEdgesIDs( faceID, idVec );
1475 _Face& quad = _hexQuads[ SMESH_Block::ShapeIndex( faceID )];
1476 bool revFace = ( faceID == SMESH_Block::ID_Fxy0 ||
1477 faceID == SMESH_Block::ID_Fx1z ||
1478 faceID == SMESH_Block::ID_F0yz );
1479 quad._links.resize(4);
1480 vector<_OrientedLink>::iterator frwLinkIt = quad._links.begin();
1481 vector<_OrientedLink>::reverse_iterator revLinkIt = quad._links.rbegin();
1482 for ( int i = 0; i < 4; ++i )
1484 bool revLink = revFace;
1485 if ( i > 1 ) // reverse links u1 and v0
1487 _OrientedLink& link = revFace ? *revLinkIt++ : *frwLinkIt++;
1488 link = _OrientedLink( & _hexLinks[ SMESH_Block::ShapeIndex( idVec[interlace[i]] )],
1493 //================================================================================
1495 * \brief Copy constructor
1497 Hexahedron::Hexahedron( const Hexahedron& other )
1498 :_grid( other._grid ), _sizeThreshold( other._sizeThreshold ), _nbFaceIntNodes(0)
1500 _polygons.reserve(100); // to avoid reallocation;
1502 for ( int i = 0; i < 8; ++i )
1503 _nodeShift[i] = other._nodeShift[i];
1505 for ( int i = 0; i < 12; ++i )
1507 const _Link& srcLink = other._hexLinks[ i ];
1508 _Link& tgtLink = this->_hexLinks[ i ];
1509 tgtLink._nodes[0] = _hexNodes + ( srcLink._nodes[0] - other._hexNodes );
1510 tgtLink._nodes[1] = _hexNodes + ( srcLink._nodes[1] - other._hexNodes );
1513 for ( int i = 0; i < 6; ++i )
1515 const _Face& srcQuad = other._hexQuads[ i ];
1516 _Face& tgtQuad = this->_hexQuads[ i ];
1517 tgtQuad._links.resize(4);
1518 for ( int j = 0; j < 4; ++j )
1520 const _OrientedLink& srcLink = srcQuad._links[ j ];
1521 _OrientedLink& tgtLink = tgtQuad._links[ j ];
1522 tgtLink._reverse = srcLink._reverse;
1523 tgtLink._link = _hexLinks + ( srcLink._link - other._hexLinks );
1528 //================================================================================
1530 * \brief Initializes its data by given grid cell
1532 void Hexahedron::init( size_t i, size_t j, size_t k )
1534 _i = i; _j = j; _k = k;
1535 // set nodes of grid to nodes of the hexahedron and
1536 // count nodes at hexahedron corners located IN and ON geometry
1537 _nbCornerNodes = _nbBndNodes = 0;
1538 _origNodeInd = _grid->NodeIndex( i,j,k );
1539 for ( int iN = 0; iN < 8; ++iN )
1541 _hexNodes[iN]._node = _grid->_nodes [ _origNodeInd + _nodeShift[iN] ];
1542 _hexNodes[iN]._intPoint = _grid->_gridIntP[ _origNodeInd + _nodeShift[iN] ];
1543 _nbCornerNodes += bool( _hexNodes[iN]._node );
1544 _nbBndNodes += bool( _hexNodes[iN]._intPoint );
1547 _sideLength[0] = _grid->_coords[0][i+1] - _grid->_coords[0][i];
1548 _sideLength[1] = _grid->_coords[1][j+1] - _grid->_coords[1][j];
1549 _sideLength[2] = _grid->_coords[2][k+1] - _grid->_coords[2][k];
1554 if ( _nbFaceIntNodes + _eIntPoints.size() > 0 &&
1555 _nbFaceIntNodes + _nbCornerNodes + _eIntPoints.size() > 3)
1557 _intNodes.reserve( 3 * _nbBndNodes + _nbFaceIntNodes + _eIntPoints.size() );
1560 // create sub-links (_splits) by splitting links with _fIntPoints
1561 for ( int iLink = 0; iLink < 12; ++iLink )
1563 _Link& link = _hexLinks[ iLink ];
1564 link._fIntNodes.resize( link._fIntPoints.size() );
1565 for ( size_t i = 0; i < link._fIntPoints.size(); ++i )
1567 _intNodes.push_back( _Node( 0, link._fIntPoints[i] ));
1568 link._fIntNodes[ i ] = & _intNodes.back();
1571 link._splits.clear();
1572 split._nodes[ 0 ] = link._nodes[0];
1573 bool isOut = ( ! link._nodes[0]->Node() ); // is1stNodeOut( iLink );
1574 bool checkTransition;
1575 for ( size_t i = 0; i < link._fIntNodes.size(); ++i )
1577 if ( link._fIntNodes[i]->Node() ) // intersection non-coinsident 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 coinsident with a grid node
1589 checkTransition = ( link._nodes[0]->Node() );
1591 if ( checkTransition )
1593 switch ( link._fIntPoints[i]->_transition ) {
1594 case Trans_OUT: isOut = true; break;
1595 case Trans_IN : isOut = false; break;
1597 if ( !link._fIntNodes[i]->Node() && i == 0 )
1598 isOut = is1stNodeOut( link );
1600 ; // isOut remains the same
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 ] );
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 // --------------------------------
1756 vector< _OrientedLink > splits;
1757 vector<_Node*> chainNodes, usedEdgeNodes;
1758 _Face* coplanarPolyg;
1760 bool hasEdgeIntersections = !_eIntPoints.empty();
1762 for ( int iF = 0; iF < 6; ++iF ) // loop on 6 sides of a hexahedron
1764 _Face& quad = _hexQuads[ iF ] ;
1766 _polygons.resize( _polygons.size() + 1 );
1767 _Face* polygon = &_polygons.back();
1768 polygon->_polyLinks.reserve( 20 );
1771 for ( int iE = 0; iE < 4; ++iE ) // loop on 4 sides of a quadrangle
1772 for ( int iS = 0; iS < quad._links[ iE ].NbResultLinks(); ++iS )
1773 splits.push_back( quad._links[ iE ].ResultLink( iS ));
1775 // add splits of links to a polygon and add _polyLinks to make
1776 // polygon's boundary closed
1778 int nbSplits = splits.size();
1779 if ( nbSplits < 2 && quad._eIntNodes.empty() )
1783 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
1784 if ( quad._eIntNodes[ iP ]->IsUsedInFace( polygon ))
1785 quad._eIntNodes[ iP ]->_usedInFace = 0;
1787 int nbUsedEdgeNodes = 0;
1789 while ( nbSplits > 0 )
1792 while ( !splits[ iS ] )
1795 if ( !polygon->_links.empty() )
1797 _polygons.resize( _polygons.size() + 1 );
1798 polygon = &_polygons.back();
1799 polygon->_polyLinks.reserve( 20 );
1801 polygon->_links.push_back( splits[ iS ] );
1802 splits[ iS++ ]._link = 0;
1805 _Node* nFirst = polygon->_links.back().FirstNode();
1806 _Node *n1,*n2 = polygon->_links.back().LastNode();
1807 for ( ; nFirst != n2 && iS < splits.size(); ++iS )
1809 _OrientedLink& split = splits[ iS ];
1810 if ( !split ) continue;
1812 n1 = split.FirstNode();
1815 // try to connect to intersections with EDGEs
1816 if ( quad._eIntNodes.size() > nbUsedEdgeNodes &&
1817 findChain( n2, n1, quad, chainNodes ))
1819 for ( size_t i = 1; i < chainNodes.size(); ++i )
1821 polyLink._nodes[0] = chainNodes[i-1];
1822 polyLink._nodes[1] = chainNodes[i];
1823 polygon->_polyLinks.push_back( polyLink );
1824 polygon->_links.push_back( _OrientedLink( &polygon->_polyLinks.back() ));
1825 nbUsedEdgeNodes += ( polyLink._nodes[1]->IsUsedInFace( polygon ));
1827 if ( chainNodes.back() != n1 )
1829 n2 = chainNodes.back();
1834 // try to connect to a split ending on the same FACE
1837 _OrientedLink foundSplit;
1838 for ( int i = iS; i < splits.size() && !foundSplit; ++i )
1839 if (( foundSplit = splits[ i ]) &&
1840 ( n2->IsLinked( foundSplit.FirstNode()->_intPoint )))
1842 polyLink._nodes[0] = n2;
1843 polyLink._nodes[1] = foundSplit.FirstNode();
1844 polygon->_polyLinks.push_back( polyLink );
1845 polygon->_links.push_back( _OrientedLink( &polygon->_polyLinks.back() ));
1850 foundSplit._link = 0;
1854 n2 = foundSplit.FirstNode();
1859 if ( n2->IsLinked( nFirst->_intPoint ))
1861 polyLink._nodes[0] = n2;
1862 polyLink._nodes[1] = n1;
1863 polygon->_polyLinks.push_back( polyLink );
1864 polygon->_links.push_back( _OrientedLink( &polygon->_polyLinks.back() ));
1868 polygon->_links.push_back( split );
1871 n2 = polygon->_links.back().LastNode();
1875 if ( nFirst != n2 ) // close a polygon
1877 if ( !findChain( n2, nFirst, quad, chainNodes ))
1879 if ( !closePolygon( polygon, chainNodes ))
1880 chainNodes.push_back( nFirst );
1882 for ( size_t i = 1; i < chainNodes.size(); ++i )
1884 polyLink._nodes[0] = chainNodes[i-1];
1885 polyLink._nodes[1] = chainNodes[i];
1886 polygon->_polyLinks.push_back( polyLink );
1887 polygon->_links.push_back( _OrientedLink( &polygon->_polyLinks.back() ));
1888 nbUsedEdgeNodes += bool( polyLink._nodes[1]->IsUsedInFace( polygon ));
1892 if ( polygon->_links.size() < 3 && nbSplits > 0 )
1894 polygon->_polyLinks.clear();
1895 polygon->_links.clear();
1897 } // while ( nbSplits > 0 )
1899 // if ( quad._eIntNodes.size() > nbUsedEdgeNodes )
1901 // // make _vIntNodes from not used _eIntNodes
1902 // const double tol = 0.05 * Min( Min( _sideLength[0], _sideLength[1] ), _sideLength[0] );
1903 // for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
1905 // if ( quad._eIntNodes[ iP ]->IsUsedInFace() ) continue;
1906 // _Node* equalNode =
1907 // FindEqualNode( _vIntNodes, quad._eIntNodes[ iP ].EdgeIntPnt(), tol*tol );
1909 // equalNode->Add( quad._eIntNodes[ iP ].EdgeIntPnt() );
1911 // _vIntNodes.push_back( quad._eIntNodes[ iP ]);
1915 if ( polygon->_links.size() < 3 )
1917 _polygons.pop_back();
1918 //usedEdgeNodes.resize( usedEdgeNodes.size() - nbUsedEdgeNodes );
1920 } // loop on 6 hexahedron sides
1922 // Create polygons closing holes in a polyhedron
1923 // ----------------------------------------------
1925 // clear _usedInFace
1926 for ( size_t iN = 0; iN < _intNodes.size(); ++iN )
1927 _intNodes[ iN ]._usedInFace = 0;
1929 // add polygons to their links and mark used nodes
1930 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
1932 _Face& polygon = _polygons[ iP ];
1933 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
1935 polygon._links[ iL ].AddFace( &polygon );
1936 polygon._links[ iL ].FirstNode()->_usedInFace = &polygon;
1940 vector< _OrientedLink* > freeLinks;
1941 freeLinks.reserve(20);
1942 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
1944 _Face& polygon = _polygons[ iP ];
1945 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
1946 if ( polygon._links[ iL ].NbFaces() < 2 )
1948 freeLinks.push_back( & polygon._links[ iL ]);
1949 freeLinks.back()->FirstNode()->IsUsedInFace() == true;
1952 int nbFreeLinks = freeLinks.size();
1953 if ( nbFreeLinks > 0 && nbFreeLinks < 3 ) return;
1955 // put not used intersection nodes to _vIntNodes
1956 int nbVertexNodes = 0; // nb not used vertex nodes
1958 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
1959 nbVertexNodes += ( !_vIntNodes[ iN ]->IsUsedInFace() );
1961 const double tol = 1e-3 * Min( Min( _sideLength[0], _sideLength[1] ), _sideLength[0] );
1962 for ( size_t iN = _nbFaceIntNodes; iN < _intNodes.size(); ++iN )
1964 if ( _intNodes[ iN ].IsUsedInFace() ) continue;
1965 if ( dynamic_cast< const F_IntersectPoint* >( _intNodes[ iN ]._intPoint )) continue;
1967 FindEqualNode( _vIntNodes, _intNodes[ iN ].EdgeIntPnt(), tol*tol );
1968 if ( !equalNode /*|| equalNode->IsUsedInFace()*/ )
1970 _vIntNodes.push_back( &_intNodes[ iN ]);
1976 set<TGeomID> usedFaceIDs;
1977 TGeomID curFace = 0;
1978 const size_t nbQuadPolygons = _polygons.size();
1980 // create polygons by making closed chains of free links
1981 size_t iPolygon = _polygons.size();
1982 while ( nbFreeLinks > 0 )
1984 if ( iPolygon == _polygons.size() )
1985 _polygons.resize( _polygons.size() + 1 );
1986 _Face& polygon = _polygons[ iPolygon ];
1987 polygon._polyLinks.reserve( 20 );
1988 polygon._links.reserve( 20 );
1990 _OrientedLink* curLink = 0;
1992 if (( !hasEdgeIntersections ) ||
1993 ( nbFreeLinks < 4 && nbVertexNodes == 0 ))
1995 // get a remaining link to start from
1996 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
1997 if (( curLink = freeLinks[ iL ] ))
1998 freeLinks[ iL ] = 0;
1999 polygon._links.push_back( *curLink );
2003 // find all links connected to curLink
2004 curNode = curLink->FirstNode();
2006 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2007 if ( freeLinks[ iL ] && freeLinks[ iL ]->LastNode() == curNode )
2009 curLink = freeLinks[ iL ];
2010 freeLinks[ iL ] = 0;
2012 polygon._links.push_back( *curLink );
2014 } while ( curLink );
2016 else // there are intersections with EDGEs
2018 // get a remaining link to start from, one lying on minimal nb of FACEs
2020 vector< pair< TGeomID, int > > facesOfLink[3];
2021 pair< TGeomID, int > faceOfLink( -1, -1 );
2022 vector< TGeomID > faces;
2023 for ( size_t iL = 0; iL < freeLinks.size(); ++iL )
2024 if ( freeLinks[ iL ] )
2026 faces = freeLinks[ iL ]->GetNotUsedFace( usedFaceIDs );
2027 if ( faces.size() == 1 )
2029 faceOfLink = make_pair( faces[0], iL );
2030 if ( !freeLinks[ iL ]->HasEdgeNodes() )
2032 facesOfLink[0].push_back( faceOfLink );
2034 else if ( facesOfLink[0].empty() )
2036 faceOfLink = make_pair(( faces.empty() ? -1 : faces[0]), iL );
2037 facesOfLink[ 1 + faces.empty() ].push_back( faceOfLink );
2040 for ( int i = 0; faceOfLink.second < 0 && i < 3; ++i )
2041 if ( !facesOfLink[i].empty() )
2042 faceOfLink = facesOfLink[i][0];
2044 if ( faceOfLink.first < 0 ) // all faces used
2046 for ( size_t i = 0; i < facesOfLink[2].size() && faceOfLink.first < 1; ++i )
2048 curLink = freeLinks[ facesOfLink[2][i].second ];
2049 faceOfLink.first = curLink->FirstNode()->IsLinked( curLink->LastNode()->_intPoint );
2051 usedFaceIDs.clear();
2053 curFace = faceOfLink.first;
2054 curLink = freeLinks[ faceOfLink.second ];
2055 freeLinks[ faceOfLink.second ] = 0;
2057 usedFaceIDs.insert( curFace );
2058 polygon._links.push_back( *curLink );
2061 // find all links lying on a curFace
2064 // go forward from curLink
2065 curNode = curLink->LastNode();
2067 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2068 if ( freeLinks[ iL ] &&
2069 freeLinks[ iL ]->FirstNode() == curNode &&
2070 freeLinks[ iL ]->LastNode()->IsOnFace( curFace ))
2072 curLink = freeLinks[ iL ];
2073 freeLinks[ iL ] = 0;
2074 polygon._links.push_back( *curLink );
2077 } while ( curLink );
2079 std::reverse( polygon._links.begin(), polygon._links.end() );
2081 curLink = & polygon._links.back();
2084 // go backward from curLink
2085 curNode = curLink->FirstNode();
2087 for ( size_t iL = 0; iL < freeLinks.size() && !curLink; ++iL )
2088 if ( freeLinks[ iL ] &&
2089 freeLinks[ iL ]->LastNode() == curNode &&
2090 freeLinks[ iL ]->FirstNode()->IsOnFace( curFace ))
2092 curLink = freeLinks[ iL ];
2093 freeLinks[ iL ] = 0;
2094 polygon._links.push_back( *curLink );
2097 } while ( curLink );
2099 curNode = polygon._links.back().FirstNode();
2101 if ( polygon._links[0].LastNode() != curNode )
2103 if ( nbVertexNodes > 0 )
2105 // add links with _vIntNodes if not already used
2106 for ( size_t iN = 0; iN < _vIntNodes.size(); ++iN )
2107 if ( !_vIntNodes[ iN ]->IsUsedInFace() &&
2108 _vIntNodes[ iN ]->IsOnFace( curFace ))
2110 _vIntNodes[ iN ]->_usedInFace = &polygon;
2112 polyLink._nodes[0] = _vIntNodes[ iN ];
2113 polyLink._nodes[1] = curNode;
2114 polygon._polyLinks.push_back( polyLink );
2115 polygon._links.push_back( _OrientedLink( &polygon._polyLinks.back() ));
2116 freeLinks.push_back( &polygon._links.back() );
2118 curNode = _vIntNodes[ iN ];
2119 // TODO: to reorder _vIntNodes within polygon, if there are several ones
2122 // if ( polygon._links.size() > 1 )
2124 polyLink._nodes[0] = polygon._links[0].LastNode();
2125 polyLink._nodes[1] = curNode;
2126 polygon._polyLinks.push_back( polyLink );
2127 polygon._links.push_back( _OrientedLink( &polygon._polyLinks.back() ));
2128 freeLinks.push_back( &polygon._links.back() );
2132 } // if there are intersections with EDGEs
2134 if ( polygon._links.size() < 2 ||
2135 polygon._links[0].LastNode() != polygon._links.back().FirstNode() )
2136 return; // closed polygon not found -> invalid polyhedron
2138 if ( polygon._links.size() == 2 )
2140 if ( freeLinks.back() == &polygon._links.back() )
2142 freeLinks.pop_back();
2145 if ( polygon._links.front().NbFaces() > 0 )
2146 polygon._links.back().AddFace( polygon._links.front()._link->_faces[0] );
2147 if ( polygon._links.back().NbFaces() > 0 )
2148 polygon._links.front().AddFace( polygon._links.back()._link->_faces[0] );
2150 if ( iPolygon == _polygons.size()-1 )
2151 _polygons.pop_back();
2153 else // polygon._links.size() >= 2
2155 // add polygon to its links
2156 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
2158 polygon._links[ iL ].AddFace( &polygon );
2159 polygon._links[ iL ].Reverse();
2161 if ( hasEdgeIntersections && iPolygon == _polygons.size() - 1 )
2163 // check that a polygon does not lie in the plane of another polygon
2165 for ( size_t iL = 0; iL < polygon._links.size() && !coplanarPolyg; ++iL )
2167 if ( polygon._links[ iL ].NbFaces() < 2 )
2168 continue; // it's a just added free link
2169 // look for a polygon made on a hexa side and sharing
2170 // two or more haxa links
2172 coplanarPolyg = polygon._links[ iL ]._link->_faces[0];
2173 for ( iL2 = iL + 1; iL2 < polygon._links.size(); ++iL2 )
2174 if ( polygon._links[ iL2 ]._link->_faces[0] == coplanarPolyg &&
2175 !coplanarPolyg->isPolyLink( polygon._links[ iL2 ]) &&
2176 coplanarPolyg < & _polygons[ nbQuadPolygons ])
2178 if ( iL2 == polygon._links.size() )
2181 if ( coplanarPolyg ) // coplanar polygon found
2183 freeLinks.resize( freeLinks.size() - polygon._polyLinks.size() );
2184 nbFreeLinks -= polygon._polyLinks.size();
2186 // an artificial E_IntersectPoint used to mark nodes of coplanarPolyg
2187 // as lying on curFace while they are not at intersection with geometry
2188 E_IntersectPoint* ip = & _grid->_edgeIntP.back();
2189 ip->_faceIDs.resize(1);
2190 ip->_faceIDs[0] = curFace;
2192 // fill freeLinks with links not shared by coplanarPolyg and polygon
2193 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
2194 if ( polygon._links[ iL ]._link->_faces[1] &&
2195 polygon._links[ iL ]._link->_faces[0] != coplanarPolyg )
2197 _Face* p = polygon._links[ iL ]._link->_faces[0];
2198 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
2199 if ( p->_links[ iL2 ]._link == polygon._links[ iL ]._link )
2201 freeLinks.push_back( & p->_links[ iL2 ] );
2203 freeLinks.back()->RemoveFace( &polygon );
2207 for ( size_t iL = 0; iL < coplanarPolyg->_links.size(); ++iL )
2208 if ( coplanarPolyg->_links[ iL ]._link->_faces[1] &&
2209 coplanarPolyg->_links[ iL ]._link->_faces[1] != &polygon )
2211 _Face* p = coplanarPolyg->_links[ iL ]._link->_faces[0];
2212 if ( p == coplanarPolyg )
2213 p = coplanarPolyg->_links[ iL ]._link->_faces[1];
2214 for ( size_t iL2 = 0; iL2 < p->_links.size(); ++iL2 )
2215 if ( p->_links[ iL2 ]._link == coplanarPolyg->_links[ iL ]._link )
2217 // set links of coplanarPolyg in place of used freeLinks
2218 // to re-create coplanarPolyg next
2220 for ( ; iL3 < freeLinks.size() && freeLinks[ iL3 ]; ++iL3 );
2221 if ( iL3 < freeLinks.size() )
2222 freeLinks[ iL3 ] = ( & p->_links[ iL2 ] );
2224 freeLinks.push_back( & p->_links[ iL2 ] );
2226 freeLinks[ iL3 ]->RemoveFace( coplanarPolyg );
2227 // mark nodes of coplanarPolyg as lying on curFace
2228 for ( int iN = 0; iN < 2; ++iN )
2230 _Node* n = freeLinks[ iL3 ]->_link->_nodes[ iN ];
2231 if ( n->_intPoint ) n->_intPoint->Add( ip->_faceIDs );
2232 else n->_intPoint = ip;
2237 // set coplanarPolyg to be re-created next
2238 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
2239 if ( coplanarPolyg == & _polygons[ iP ] )
2242 _polygons[ iPolygon ]._links.clear();
2243 _polygons[ iPolygon ]._polyLinks.clear();
2246 if ( freeLinks.back() == &polygon._links.back() )
2248 freeLinks.pop_back();
2251 _polygons.pop_back();
2252 usedFaceIDs.erase( curFace );
2254 } // if ( coplanarPolyg )
2255 } // if ( hasEdgeIntersections ) - search for coplanarPolyg
2257 iPolygon = _polygons.size();
2259 } // end of case ( polygon._links.size() > 2 )
2260 } // while ( nbFreeLinks > 0 )
2262 if ( ! checkPolyhedronSize() )
2267 // create a classic cell if possible
2268 const int nbNodes = _nbCornerNodes + nbIntersections;
2269 bool isClassicElem = false;
2270 if ( nbNodes == 8 && _polygons.size() == 6 ) isClassicElem = addHexa();
2271 else if ( nbNodes == 4 && _polygons.size() == 4 ) isClassicElem = addTetra();
2272 else if ( nbNodes == 6 && _polygons.size() == 5 ) isClassicElem = addPenta();
2273 else if ( nbNodes == 5 && _polygons.size() == 5 ) isClassicElem = addPyra ();
2274 if ( !isClassicElem )
2276 _volumeDefs._nodes.clear();
2277 _volumeDefs._quantities.clear();
2279 for ( size_t iF = 0; iF < _polygons.size(); ++iF )
2281 const size_t nbLinks = _polygons[ iF ]._links.size();
2282 _volumeDefs._quantities.push_back( nbLinks );
2283 for ( size_t iL = 0; iL < nbLinks; ++iL )
2284 _volumeDefs._nodes.push_back( _polygons[ iF ]._links[ iL ].FirstNode() );
2288 //================================================================================
2290 * \brief Create elements in the mesh
2292 int Hexahedron::MakeElements(SMESH_MesherHelper& helper,
2293 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
2295 SMESHDS_Mesh* mesh = helper.GetMeshDS();
2297 size_t nbCells[3] = { _grid->_coords[0].size() - 1,
2298 _grid->_coords[1].size() - 1,
2299 _grid->_coords[2].size() - 1 };
2300 const size_t nbGridCells = nbCells[0] * nbCells[1] * nbCells[2];
2301 vector< Hexahedron* > intersectedHex( nbGridCells, 0 );
2304 // set intersection nodes from GridLine's to links of intersectedHex
2305 int i,j,k, iDirOther[3][2] = {{ 1,2 },{ 0,2 },{ 0,1 }};
2306 for ( int iDir = 0; iDir < 3; ++iDir )
2308 int dInd[4][3] = { {0,0,0}, {0,0,0}, {0,0,0}, {0,0,0} };
2309 dInd[1][ iDirOther[iDir][0] ] = -1;
2310 dInd[2][ iDirOther[iDir][1] ] = -1;
2311 dInd[3][ iDirOther[iDir][0] ] = -1; dInd[3][ iDirOther[iDir][1] ] = -1;
2312 // loop on GridLine's parallel to iDir
2313 LineIndexer lineInd = _grid->GetLineIndexer( iDir );
2314 for ( ; lineInd.More(); ++lineInd )
2316 GridLine& line = _grid->_lines[ iDir ][ lineInd.LineIndex() ];
2317 multiset< F_IntersectPoint >::const_iterator ip = line._intPoints.begin();
2318 for ( ; ip != line._intPoints.end(); ++ip )
2320 // if ( !ip->_node ) continue; // intersection at a grid node
2321 lineInd.SetIndexOnLine( ip->_indexOnLine );
2322 for ( int iL = 0; iL < 4; ++iL ) // loop on 4 cells sharing a link
2324 i = int(lineInd.I()) + dInd[iL][0];
2325 j = int(lineInd.J()) + dInd[iL][1];
2326 k = int(lineInd.K()) + dInd[iL][2];
2327 if ( i < 0 || i >= nbCells[0] ||
2328 j < 0 || j >= nbCells[1] ||
2329 k < 0 || k >= nbCells[2] ) continue;
2331 const size_t hexIndex = _grid->CellIndex( i,j,k );
2332 Hexahedron *& hex = intersectedHex[ hexIndex ];
2335 hex = new Hexahedron( *this );
2341 const int iLink = iL + iDir * 4;
2342 hex->_hexLinks[iLink]._fIntPoints.push_back( &(*ip) );
2343 hex->_nbFaceIntNodes += bool( ip->_node );
2349 // implement geom edges into the mesh
2350 addEdges( helper, intersectedHex, edge2faceIDsMap );
2352 // add not split hexadrons to the mesh
2354 vector<int> intHexInd( nbIntHex );
2356 for ( size_t i = 0; i < intersectedHex.size(); ++i )
2358 Hexahedron * & hex = intersectedHex[ i ];
2361 intHexInd[ nbIntHex++ ] = i;
2362 if ( hex->_nbFaceIntNodes > 0 || hex->_eIntPoints.size() > 0 )
2363 continue; // treat intersected hex later
2364 this->init( hex->_i, hex->_j, hex->_k );
2370 if (( _nbCornerNodes == 8 ) &&
2371 ( _nbBndNodes < _nbCornerNodes || !isInHole() ))
2373 // order of _hexNodes is defined by enum SMESH_Block::TShapeID
2374 SMDS_MeshElement* el =
2375 mesh->AddVolume( _hexNodes[0].Node(), _hexNodes[2].Node(),
2376 _hexNodes[3].Node(), _hexNodes[1].Node(),
2377 _hexNodes[4].Node(), _hexNodes[6].Node(),
2378 _hexNodes[7].Node(), _hexNodes[5].Node() );
2379 mesh->SetMeshElementOnShape( el, helper.GetSubShapeID() );
2384 intersectedHex[ i ] = 0;
2388 else if ( _nbCornerNodes > 3 && !hex )
2390 // all intersection of hex with geometry are at grid nodes
2391 hex = new Hexahedron( *this );
2395 intHexInd.push_back(0);
2396 intHexInd[ nbIntHex++ ] = i;
2400 // add elements resulted from hexadron intersection
2402 intHexInd.resize( nbIntHex );
2403 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, nbIntHex ),
2404 ParallelHexahedron( intersectedHex, intHexInd ),
2405 tbb::simple_partitioner()); // ComputeElements() is called here
2406 for ( size_t i = 0; i < intHexInd.size(); ++i )
2407 if ( Hexahedron * hex = intersectedHex[ intHexInd[ i ]] )
2408 nbAdded += hex->addElements( helper );
2410 for ( size_t i = 0; i < intHexInd.size(); ++i )
2411 if ( Hexahedron * hex = intersectedHex[ intHexInd[ i ]] )
2413 hex->ComputeElements();
2414 nbAdded += hex->addElements( helper );
2418 for ( size_t i = 0; i < intersectedHex.size(); ++i )
2419 if ( intersectedHex[ i ] )
2420 delete intersectedHex[ i ];
2425 //================================================================================
2427 * \brief Implements geom edges into the mesh
2429 void Hexahedron::addEdges(SMESH_MesherHelper& helper,
2430 vector< Hexahedron* >& hexes,
2431 const map< TGeomID, vector< TGeomID > >& edge2faceIDsMap)
2433 if ( edge2faceIDsMap.empty() ) return;
2435 // Prepare planes for intersecting with EDGEs
2438 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ ) // iDirZ gives normal direction to planes
2440 GridPlanes& planes = pln[ iDirZ ];
2441 int iDirX = ( iDirZ + 1 ) % 3;
2442 int iDirY = ( iDirZ + 2 ) % 3;
2443 planes._zNorm = ( _grid->_axes[ iDirX ] ^ _grid->_axes[ iDirY ] ).Normalized();
2444 planes._zProjs.resize ( _grid->_coords[ iDirZ ].size() );
2445 planes._zProjs [0] = 0;
2446 const double zFactor = _grid->_axes[ iDirZ ] * planes._zNorm;
2447 const vector< double > & u = _grid->_coords[ iDirZ ];
2448 for ( int i = 1; i < planes._zProjs.size(); ++i )
2450 planes._zProjs [i] = zFactor * ( u[i] - u[0] );
2454 const double deflection = _grid->_minCellSize / 20.;
2455 const double tol = _grid->_tol;
2456 E_IntersectPoint ip;
2458 // Intersect EDGEs with the planes
2459 map< TGeomID, vector< TGeomID > >::const_iterator e2fIt = edge2faceIDsMap.begin();
2460 for ( ; e2fIt != edge2faceIDsMap.end(); ++e2fIt )
2462 const TGeomID edgeID = e2fIt->first;
2463 const TopoDS_Edge & E = TopoDS::Edge( _grid->_shapes( edgeID ));
2464 BRepAdaptor_Curve curve( E );
2465 TopoDS_Vertex v1 = helper.IthVertex( 0, E, false );
2466 TopoDS_Vertex v2 = helper.IthVertex( 1, E, false );
2468 ip._faceIDs = e2fIt->second;
2469 ip._shapeID = edgeID;
2471 // discretize the EGDE
2472 GCPnts_UniformDeflection discret( curve, deflection, true );
2473 if ( !discret.IsDone() || discret.NbPoints() < 2 )
2476 // perform intersection
2477 for ( int iDirZ = 0; iDirZ < 3; ++iDirZ )
2479 GridPlanes& planes = pln[ iDirZ ];
2480 int iDirX = ( iDirZ + 1 ) % 3;
2481 int iDirY = ( iDirZ + 2 ) % 3;
2482 double xLen = _grid->_coords[ iDirX ].back() - _grid->_coords[ iDirX ][0];
2483 double yLen = _grid->_coords[ iDirY ].back() - _grid->_coords[ iDirY ][0];
2484 double zLen = _grid->_coords[ iDirZ ].back() - _grid->_coords[ iDirZ ][0];
2485 int dIJK[3], d000[3] = { 0,0,0 };
2486 double o[3] = { _grid->_coords[0][0],
2487 _grid->_coords[1][0],
2488 _grid->_coords[2][0] };
2490 // locate the 1st point of a segment within the grid
2491 gp_XYZ p1 = discret.Value( 1 ).XYZ();
2492 double u1 = discret.Parameter( 1 );
2493 double zProj1 = planes._zNorm * ( p1 - _grid->_origin );
2495 _grid->ComputeUVW( p1, ip._uvw );
2496 int iX1 = int(( ip._uvw[iDirX] - o[iDirX]) / xLen * (_grid->_coords[ iDirX ].size() - 1));
2497 int iY1 = int(( ip._uvw[iDirY] - o[iDirY]) / yLen * (_grid->_coords[ iDirY ].size() - 1));
2498 int iZ1 = int(( ip._uvw[iDirZ] - o[iDirZ]) / zLen * (_grid->_coords[ iDirZ ].size() - 1));
2499 locateValue( iX1, ip._uvw[iDirX], _grid->_coords[ iDirX ], dIJK[ iDirX ], tol );
2500 locateValue( iY1, ip._uvw[iDirY], _grid->_coords[ iDirY ], dIJK[ iDirY ], tol );
2501 locateValue( iZ1, ip._uvw[iDirZ], _grid->_coords[ iDirZ ], dIJK[ iDirZ ], tol );
2503 int ijk[3]; // grid index where a segment intersect a plane
2508 // add the 1st vertex point to a hexahedron
2512 ip._shapeID = _grid->_shapes.Add( v1 );
2513 _grid->_edgeIntP.push_back( ip );
2514 if ( !addIntersection( _grid->_edgeIntP.back(), hexes, ijk, d000 ))
2515 _grid->_edgeIntP.pop_back();
2516 ip._shapeID = edgeID;
2518 for ( int iP = 2; iP <= discret.NbPoints(); ++iP )
2520 // locate the 2nd point of a segment within the grid
2521 gp_XYZ p2 = discret.Value( iP ).XYZ();
2522 double u2 = discret.Parameter( iP );
2523 double zProj2 = planes._zNorm * ( p2 - _grid->_origin );
2525 if ( Abs( zProj2 - zProj1 ) <= std::numeric_limits<double>::min() )
2527 locateValue( iZ2, zProj2, planes._zProjs, dIJK[ iDirZ ], tol );
2529 // treat intersections with planes between 2 end points of a segment
2530 int dZ = ( iZ1 <= iZ2 ) ? +1 : -1;
2531 int iZ = iZ1 + ( iZ1 < iZ2 );
2532 for ( int i = 0, nb = Abs( iZ1 - iZ2 ); i < nb; ++i, iZ += dZ )
2534 ip._point = findIntPoint( u1, zProj1, u2, zProj2,
2535 planes._zProjs[ iZ ],
2536 curve, planes._zNorm, _grid->_origin );
2537 _grid->ComputeUVW( ip._point.XYZ(), ip._uvw );
2538 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
2539 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
2542 // add ip to hex "above" the plane
2543 _grid->_edgeIntP.push_back( ip );
2545 bool added = addIntersection(_grid->_edgeIntP.back(), hexes, ijk, dIJK);
2547 // add ip to hex "below" the plane
2548 ijk[ iDirZ ] = iZ-1;
2549 if ( !addIntersection( _grid->_edgeIntP.back(), hexes, ijk, dIJK ) &&
2551 _grid->_edgeIntP.pop_back();
2558 // add the 2nd vertex point to a hexahedron
2561 ip._shapeID = _grid->_shapes.Add( v2 );
2563 _grid->ComputeUVW( p1, ip._uvw );
2564 locateValue( ijk[iDirX], ip._uvw[iDirX], _grid->_coords[iDirX], dIJK[iDirX], tol );
2565 locateValue( ijk[iDirY], ip._uvw[iDirY], _grid->_coords[iDirY], dIJK[iDirY], tol );
2567 _grid->_edgeIntP.push_back( ip );
2568 if ( !addIntersection( _grid->_edgeIntP.back(), hexes, ijk, d000 ))
2569 _grid->_edgeIntP.pop_back();
2570 ip._shapeID = edgeID;
2572 } // loop on 3 grid directions
2575 // add an artificial E_IntersectPoint used in Hexahedron::ComputeElements()
2577 ip._faceIDs.clear();
2579 _grid->_edgeIntP.push_back( ip );
2582 //================================================================================
2584 * \brief Finds intersection of a curve with a plane
2585 * \param [in] u1 - parameter of one curve point
2586 * \param [in] proj1 - projection of the curve point to the plane normal
2587 * \param [in] u2 - parameter of another curve point
2588 * \param [in] proj2 - projection of the other curve point to the plane normal
2589 * \param [in] proj - projection of a point where the curve intersects the plane
2590 * \param [in] curve - the curve
2591 * \param [in] axis - the plane normal
2592 * \param [in] origin - the plane origin
2593 * \return gp_Pnt - the found intersection point
2595 gp_Pnt Hexahedron::findIntPoint( double u1, double proj1,
2596 double u2, double proj2,
2598 BRepAdaptor_Curve& curve,
2600 const gp_XYZ& origin)
2602 double r = (( proj - proj1 ) / ( proj2 - proj1 ));
2603 double u = u1 * ( 1 - r ) + u2 * r;
2604 gp_Pnt p = curve.Value( u );
2605 double newProj = axis * ( p.XYZ() - origin );
2606 if ( Abs( proj - newProj ) > _grid->_tol / 10. )
2609 return findIntPoint( u2, proj2, u, newProj, proj, curve, axis, origin );
2611 return findIntPoint( u1, proj2, u, newProj, proj, curve, axis, origin );
2616 //================================================================================
2618 * \brief Returns indices of a hexahedron sub-entities holding a point
2619 * \param [in] ip - intersection point
2620 * \param [out] facets - 0-3 facets holding a point
2621 * \param [out] sub - index of a vertex or an edge holding a point
2622 * \return int - number of facets holding a point
2624 int Hexahedron::getEntity( const E_IntersectPoint* ip, int* facets, int& sub )
2626 enum { X = 1, Y = 2, Z = 4 }; // == 001, 010, 100
2628 int vertex = 0, egdeMask = 0;
2630 if ( Abs( _grid->_coords[0][ _i ] - ip->_uvw[0] ) < _grid->_tol ) {
2631 facets[ nbFacets++ ] = SMESH_Block::ID_F0yz;
2634 else if ( Abs( _grid->_coords[0][ _i+1 ] - ip->_uvw[0] ) < _grid->_tol ) {
2635 facets[ nbFacets++ ] = SMESH_Block::ID_F1yz;
2639 if ( Abs( _grid->_coords[1][ _j ] - ip->_uvw[1] ) < _grid->_tol ) {
2640 facets[ nbFacets++ ] = SMESH_Block::ID_Fx0z;
2643 else if ( Abs( _grid->_coords[1][ _j+1 ] - ip->_uvw[1] ) < _grid->_tol ) {
2644 facets[ nbFacets++ ] = SMESH_Block::ID_Fx1z;
2648 if ( Abs( _grid->_coords[2][ _k ] - ip->_uvw[2] ) < _grid->_tol ) {
2649 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy0;
2652 else if ( Abs( _grid->_coords[2][ _k+1 ] - ip->_uvw[2] ) < _grid->_tol ) {
2653 facets[ nbFacets++ ] = SMESH_Block::ID_Fxy1;
2660 case 0: sub = 0; break;
2661 case 1: sub = facets[0]; break;
2663 const int edge [3][8] = {
2664 { SMESH_Block::ID_E00z, SMESH_Block::ID_E10z,
2665 SMESH_Block::ID_E01z, SMESH_Block::ID_E11z },
2666 { SMESH_Block::ID_E0y0, SMESH_Block::ID_E1y0, 0, 0,
2667 SMESH_Block::ID_E0y1, SMESH_Block::ID_E1y1 },
2668 { SMESH_Block::ID_Ex00, 0, SMESH_Block::ID_Ex10, 0,
2669 SMESH_Block::ID_Ex01, 0, SMESH_Block::ID_Ex11 }
2671 switch ( egdeMask ) {
2672 case X | Y: sub = edge[ 0 ][ vertex ]; break;
2673 case X | Z: sub = edge[ 1 ][ vertex ]; break;
2674 default: sub = edge[ 2 ][ vertex ];
2680 sub = vertex + SMESH_Block::ID_FirstV;
2685 //================================================================================
2687 * \brief Adds intersection with an EDGE
2689 bool Hexahedron::addIntersection( const E_IntersectPoint& ip,
2690 vector< Hexahedron* >& hexes,
2691 int ijk[], int dIJK[] )
2695 size_t hexIndex[4] = {
2696 _grid->CellIndex( ijk[0], ijk[1], ijk[2] ),
2697 dIJK[0] ? _grid->CellIndex( ijk[0]+dIJK[0], ijk[1], ijk[2] ) : -1,
2698 dIJK[1] ? _grid->CellIndex( ijk[0], ijk[1]+dIJK[1], ijk[2] ) : -1,
2699 dIJK[2] ? _grid->CellIndex( ijk[0], ijk[1], ijk[2]+dIJK[2] ) : -1
2701 for ( int i = 0; i < 4; ++i )
2703 if ( /*0 <= hexIndex[i] &&*/ hexIndex[i] < hexes.size() && hexes[ hexIndex[i] ] )
2705 Hexahedron* h = hexes[ hexIndex[i] ];
2706 // check if ip is really inside the hex
2708 if (( _grid->_coords[0][ h->_i ] - _grid->_tol > ip._uvw[0] ) ||
2709 ( _grid->_coords[0][ h->_i+1 ] + _grid->_tol < ip._uvw[0] ) ||
2710 ( _grid->_coords[1][ h->_j ] - _grid->_tol > ip._uvw[1] ) ||
2711 ( _grid->_coords[1][ h->_j+1 ] + _grid->_tol < ip._uvw[1] ) ||
2712 ( _grid->_coords[2][ h->_k ] - _grid->_tol > ip._uvw[2] ) ||
2713 ( _grid->_coords[2][ h->_k+1 ] + _grid->_tol < ip._uvw[2] ))
2714 throw SALOME_Exception("ip outside a hex");
2716 h->_eIntPoints.push_back( & ip );
2722 //================================================================================
2724 * \brief Finds nodes at a path from one node to another via intersections with EDGEs
2726 bool Hexahedron::findChain( _Node* n1,
2729 vector<_Node*>& chn )
2732 chn.push_back( n1 );
2733 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2734 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
2735 n1->IsLinked( quad._eIntNodes[ iP ]->_intPoint ) &&
2736 n2->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
2738 chn.push_back( quad._eIntNodes[ iP ]);
2739 chn.push_back( n2 );
2740 quad._eIntNodes[ iP ]->_usedInFace = &quad;
2747 for ( size_t iP = 0; iP < quad._eIntNodes.size(); ++iP )
2748 if ( !quad._eIntNodes[ iP ]->IsUsedInFace( &quad ) &&
2749 chn.back()->IsLinked( quad._eIntNodes[ iP ]->_intPoint ))
2751 chn.push_back( quad._eIntNodes[ iP ]);
2752 found = quad._eIntNodes[ iP ]->_usedInFace = &quad;
2755 } while ( found && ! chn.back()->IsLinked( n2->_intPoint ) );
2757 if ( chn.back() != n2 && chn.back()->IsLinked( n2->_intPoint ))
2758 chn.push_back( n2 );
2760 return chn.size() > 1;
2762 //================================================================================
2764 * \brief Try to heal a polygon whose ends are not connected
2766 bool Hexahedron::closePolygon( _Face* polygon, vector<_Node*>& chainNodes ) const
2768 int i = -1, nbLinks = polygon->_links.size();
2771 vector< _OrientedLink > newLinks;
2772 // find a node lying on the same FACE as the last one
2773 _Node* node = polygon->_links.back().LastNode();
2774 int avoidFace = node->IsLinked( polygon->_links.back().FirstNode()->_intPoint );
2775 for ( i = nbLinks - 2; i >= 0; --i )
2776 if ( node->IsLinked( polygon->_links[i].FirstNode()->_intPoint, avoidFace ))
2780 for ( ; i < nbLinks; ++i )
2781 newLinks.push_back( polygon->_links[i] );
2785 // find a node lying on the same FACE as the first one
2786 node = polygon->_links[0].FirstNode();
2787 avoidFace = node->IsLinked( polygon->_links[0].LastNode()->_intPoint );
2788 for ( i = 1; i < nbLinks; ++i )
2789 if ( node->IsLinked( polygon->_links[i].LastNode()->_intPoint, avoidFace ))
2792 for ( nbLinks = i + 1, i = 0; i < nbLinks; ++i )
2793 newLinks.push_back( polygon->_links[i] );
2795 if ( newLinks.size() > 1 )
2797 polygon->_links.swap( newLinks );
2799 chainNodes.push_back( polygon->_links.back().LastNode() );
2800 chainNodes.push_back( polygon->_links[0].FirstNode() );
2805 //================================================================================
2807 * \brief Checks transition at the 1st node of a link
2809 bool Hexahedron::is1stNodeOut( _Link& link /*int iLink*/ ) const
2811 // new version is for the case: tangent transition at the 1st node
2813 if ( link._fIntNodes.size() > 1 )
2815 // check transition at the next intersection
2816 switch ( link._fIntPoints[1]->_transition ) {
2817 case Trans_OUT: return false;
2818 case Trans_IN : return true;
2819 default: ; // tangent transition
2822 if ( !link._nodes[1]->Node() )
2825 gp_Pnt p1 = link._nodes[0]->Point();
2826 gp_Pnt p2 = link._nodes[1]->Point();
2827 gp_Pnt testPnt = 0.8 * p1.XYZ() + 0.2 * p2.XYZ();
2829 TGeomID faceID = link._fIntPoints[0]->_faceIDs[0];
2830 const TopoDS_Face& face = TopoDS::Face( _grid->_shapes( faceID ));
2831 TopLoc_Location loc;
2832 GeomAPI_ProjectPointOnSurf& proj =
2833 _grid->_helper->GetProjector( face, loc, 0.1*_grid->_tol );
2834 testPnt.Transform( loc );
2835 proj.Perform( testPnt );
2836 if ( proj.IsDone() &&
2837 proj.NbPoints() > 0 &&
2838 proj.LowerDistance() > _grid->_tol )
2840 Quantity_Parameter u,v;
2841 proj.LowerDistanceParameters( u,v );
2843 if ( GeomLib::NormEstim( BRep_Tool::Surface( face, loc ),
2848 if ( face.Orientation() == TopAbs_REVERSED )
2850 gp_Vec v( proj.NearestPoint(), testPnt );
2851 return v * normal > 0;
2856 //================================================================================
2858 * \brief Adds computed elements to the mesh
2860 int Hexahedron::addElements(SMESH_MesherHelper& helper)
2863 // add elements resulted from hexahedron intersection
2864 //for ( size_t i = 0; i < _volumeDefs.size(); ++i )
2866 vector< const SMDS_MeshNode* > nodes( _volumeDefs._nodes.size() );
2867 for ( size_t iN = 0; iN < nodes.size(); ++iN )
2868 if ( !( nodes[iN] = _volumeDefs._nodes[iN]->Node() ))
2870 if ( const E_IntersectPoint* eip = _volumeDefs._nodes[iN]->EdgeIntPnt() )
2871 nodes[iN] = _volumeDefs._nodes[iN]->_intPoint->_node =
2872 helper.AddNode( eip->_point.X(),
2876 throw SALOME_Exception("Bug: no node at intersection point");
2879 if ( !_volumeDefs._quantities.empty() )
2881 helper.AddPolyhedralVolume( nodes, _volumeDefs._quantities );
2885 switch ( nodes.size() )
2887 case 8: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],
2888 nodes[4],nodes[5],nodes[6],nodes[7] );
2890 case 4: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3] );
2892 case 6: helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3], nodes[4],nodes[5] );
2895 helper.AddVolume( nodes[0],nodes[1],nodes[2],nodes[3],nodes[4] );
2899 nbAdded += int ( _volumeDefs._nodes.size() > 0 );
2904 //================================================================================
2906 * \brief Return true if the element is in a hole
2908 bool Hexahedron::isInHole() const
2910 if ( !_vIntNodes.empty() )
2913 const int ijk[3] = { _i, _j, _k };
2914 F_IntersectPoint curIntPnt;
2916 // consider a cell to be in a hole if all links in any direction
2917 // comes OUT of geometry
2918 for ( int iDir = 0; iDir < 3; ++iDir )
2920 const vector<double>& coords = _grid->_coords[ iDir ];
2921 LineIndexer li = _grid->GetLineIndexer( iDir );
2922 li.SetIJK( _i,_j,_k );
2923 size_t lineIndex[4] = { li.LineIndex (),
2927 bool allLinksOut = true, hasLinks = false;
2928 for ( int iL = 0; iL < 4 && allLinksOut; ++iL ) // loop on 4 links parallel to iDir
2930 const _Link& link = _hexLinks[ iL + 4*iDir ];
2931 // check transition of the first node of a link
2932 const F_IntersectPoint* firstIntPnt = 0;
2933 if ( link._nodes[0]->Node() ) // 1st node is a hexa corner
2935 curIntPnt._paramOnLine = coords[ ijk[ iDir ]] - coords[0];
2936 const GridLine& line = _grid->_lines[ iDir ][ lineIndex[ iL ]];
2937 multiset< F_IntersectPoint >::const_iterator ip =
2938 line._intPoints.upper_bound( curIntPnt );
2940 firstIntPnt = &(*ip);
2942 else if ( !link._fIntPoints.empty() )
2944 firstIntPnt = link._fIntPoints[0];
2950 allLinksOut = ( firstIntPnt->_transition == Trans_OUT );
2953 if ( hasLinks && allLinksOut )
2959 //================================================================================
2961 * \brief Return true if a polyhedron passes _sizeThreshold criterion
2963 bool Hexahedron::checkPolyhedronSize() const
2966 for ( size_t iP = 0; iP < _polygons.size(); ++iP )
2968 const _Face& polygon = _polygons[iP];
2969 gp_XYZ area (0,0,0);
2970 gp_XYZ p1 = polygon._links[ 0 ].FirstNode()->Point().XYZ();
2971 for ( size_t iL = 0; iL < polygon._links.size(); ++iL )
2973 gp_XYZ p2 = polygon._links[ iL ].LastNode()->Point().XYZ();
2977 volume += p1 * area;
2981 double initVolume = _sideLength[0] * _sideLength[1] * _sideLength[2];
2983 return volume > initVolume / _sizeThreshold;
2985 //================================================================================
2987 * \brief Tries to create a hexahedron
2989 bool Hexahedron::addHexa()
2991 if ( _polygons[0]._links.size() != 4 ||
2992 _polygons[1]._links.size() != 4 ||
2993 _polygons[2]._links.size() != 4 ||
2994 _polygons[3]._links.size() != 4 ||
2995 _polygons[4]._links.size() != 4 ||
2996 _polygons[5]._links.size() != 4 )
3000 for ( int iL = 0; iL < 4; ++iL )
3003 nodes[iL] = _polygons[0]._links[iL].FirstNode();
3006 // find a top node above the base node
3007 _Link* link = _polygons[0]._links[iL]._link;
3008 if ( !link->_faces[0] || !link->_faces[1] )
3009 return debugDumpLink( link );
3010 // a quadrangle sharing <link> with _polygons[0]
3011 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[0] )];
3012 for ( int i = 0; i < 4; ++i )
3013 if ( quad->_links[i]._link == link )
3015 // 1st node of a link opposite to <link> in <quad>
3016 nodes[iL+4] = quad->_links[(i+2)%4].FirstNode();
3022 _volumeDefs.set( vector< _Node* >( nodes, nodes+8 ));
3026 //================================================================================
3028 * \brief Tries to create a tetrahedron
3030 bool Hexahedron::addTetra()
3033 nodes[0] = _polygons[0]._links[0].FirstNode();
3034 nodes[1] = _polygons[0]._links[1].FirstNode();
3035 nodes[2] = _polygons[0]._links[2].FirstNode();
3037 _Link* link = _polygons[0]._links[0]._link;
3038 if ( !link->_faces[0] || !link->_faces[1] )
3039 return debugDumpLink( link );
3041 // a triangle sharing <link> with _polygons[0]
3042 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[0] )];
3043 for ( int i = 0; i < 3; ++i )
3044 if ( tria->_links[i]._link == link )
3046 nodes[3] = tria->_links[(i+1)%3].LastNode();
3047 _volumeDefs.set( vector< _Node* >( nodes, nodes+4 ));
3053 //================================================================================
3055 * \brief Tries to create a pentahedron
3057 bool Hexahedron::addPenta()
3059 // find a base triangular face
3061 for ( int iF = 0; iF < 5 && iTri < 0; ++iF )
3062 if ( _polygons[ iF ]._links.size() == 3 )
3064 if ( iTri < 0 ) return false;
3069 for ( int iL = 0; iL < 3; ++iL )
3072 nodes[iL] = _polygons[ iTri ]._links[iL].FirstNode();
3075 // find a top node above the base node
3076 _Link* link = _polygons[ iTri ]._links[iL]._link;
3077 if ( !link->_faces[0] || !link->_faces[1] )
3078 return debugDumpLink( link );
3079 // a quadrangle sharing <link> with a base triangle
3080 _Face* quad = link->_faces[ bool( link->_faces[0] == & _polygons[ iTri ] )];
3081 if ( quad->_links.size() != 4 ) return false;
3082 for ( int i = 0; i < 4; ++i )
3083 if ( quad->_links[i]._link == link )
3085 // 1st node of a link opposite to <link> in <quad>
3086 nodes[iL+3] = quad->_links[(i+2)%4].FirstNode();
3092 _volumeDefs.set( vector< _Node* >( nodes, nodes+6 ));
3094 return ( nbN == 6 );
3096 //================================================================================
3098 * \brief Tries to create a pyramid
3100 bool Hexahedron::addPyra()
3102 // find a base quadrangle
3104 for ( int iF = 0; iF < 5 && iQuad < 0; ++iF )
3105 if ( _polygons[ iF ]._links.size() == 4 )
3107 if ( iQuad < 0 ) return false;
3111 nodes[0] = _polygons[iQuad]._links[0].FirstNode();
3112 nodes[1] = _polygons[iQuad]._links[1].FirstNode();
3113 nodes[2] = _polygons[iQuad]._links[2].FirstNode();
3114 nodes[3] = _polygons[iQuad]._links[3].FirstNode();
3116 _Link* link = _polygons[iQuad]._links[0]._link;
3117 if ( !link->_faces[0] || !link->_faces[1] )
3118 return debugDumpLink( link );
3120 // a triangle sharing <link> with a base quadrangle
3121 _Face* tria = link->_faces[ bool( link->_faces[0] == & _polygons[ iQuad ] )];
3122 if ( tria->_links.size() != 3 ) return false;
3123 for ( int i = 0; i < 3; ++i )
3124 if ( tria->_links[i]._link == link )
3126 nodes[4] = tria->_links[(i+1)%3].LastNode();
3127 _volumeDefs.set( vector< _Node* >( nodes, nodes+5 ));
3133 //================================================================================
3135 * \brief Dump a link and return \c false
3137 bool Hexahedron::debugDumpLink( Hexahedron::_Link* link )
3140 gp_Pnt p1 = link->_nodes[0]->Point(), p2 = link->_nodes[1]->Point();
3141 cout << "BUG: not shared link. IKJ = ( "<< _i << " " << _j << " " << _k << " )" << endl
3142 << "n1 (" << p1.X() << ", "<< p1.Y() << ", "<< p1.Z() << " )" << endl
3143 << "n2 (" << p2.X() << ", "<< p2.Y() << ", "<< p2.Z() << " )" << endl;
3148 //================================================================================
3150 * \brief computes exact bounding box with axes parallel to given ones
3152 //================================================================================
3154 void getExactBndBox( const vector< TopoDS_Shape >& faceVec,
3155 const double* axesDirs,
3159 TopoDS_Compound allFacesComp;
3160 b.MakeCompound( allFacesComp );
3161 for ( size_t iF = 0; iF < faceVec.size(); ++iF )
3162 b.Add( allFacesComp, faceVec[ iF ] );
3164 double sP[6]; // aXmin, aYmin, aZmin, aXmax, aYmax, aZmax
3165 shapeBox.Get(sP[0],sP[1],sP[2],sP[3],sP[4],sP[5]);
3167 for ( int i = 0; i < 6; ++i )
3168 farDist = Max( farDist, 10 * sP[i] );
3170 gp_XYZ axis[3] = { gp_XYZ( axesDirs[0], axesDirs[1], axesDirs[2] ),
3171 gp_XYZ( axesDirs[3], axesDirs[4], axesDirs[5] ),
3172 gp_XYZ( axesDirs[6], axesDirs[7], axesDirs[8] ) };
3173 axis[0].Normalize();
3174 axis[1].Normalize();
3175 axis[2].Normalize();
3177 gp_Mat basis( axis[0], axis[1], axis[2] );
3178 gp_Mat bi = basis.Inverted();
3181 for ( int iDir = 0; iDir < 3; ++iDir )
3183 gp_XYZ axis0 = axis[ iDir ];
3184 gp_XYZ axis1 = axis[ ( iDir + 1 ) % 3 ];
3185 gp_XYZ axis2 = axis[ ( iDir + 2 ) % 3 ];
3186 for ( int isMax = 0; isMax < 2; ++isMax )
3188 double shift = isMax ? farDist : -farDist;
3189 gp_XYZ orig = shift * axis0;
3190 gp_XYZ norm = axis1 ^ axis2;
3191 gp_Pln pln( orig, norm );
3192 norm = pln.Axis().Direction().XYZ();
3193 BRepBuilderAPI_MakeFace plane( pln, -farDist, farDist, -farDist, farDist );
3195 gp_Pnt& pAxis = isMax ? pMax : pMin;
3196 gp_Pnt pPlane, pFaces;
3197 double dist = GEOMUtils::GetMinDistance( plane, allFacesComp, pPlane, pFaces );
3202 for ( int i = 0; i < 2; ++i ) {
3203 corner.SetCoord( 1, sP[ i*3 ]);
3204 for ( int j = 0; j < 2; ++j ) {
3205 corner.SetCoord( 2, sP[ i*3 + 1 ]);
3206 for ( int k = 0; k < 2; ++k )
3208 corner.SetCoord( 3, sP[ i*3 + 2 ]);
3214 corner = isMax ? bb.CornerMax() : bb.CornerMin();
3215 pAxis.SetCoord( iDir+1, corner.Coord( iDir+1 ));
3219 gp_XYZ pf = pFaces.XYZ() * bi;
3220 pAxis.SetCoord( iDir+1, pf.Coord( iDir+1 ) );
3226 shapeBox.Add( pMin );
3227 shapeBox.Add( pMax );
3234 //=============================================================================
3236 * \brief Generates 3D structured Cartesian mesh in the internal part of
3237 * solid shapes and polyhedral volumes near the shape boundary.
3238 * \param theMesh - mesh to fill in
3239 * \param theShape - a compound of all SOLIDs to mesh
3240 * \retval bool - true in case of success
3242 //=============================================================================
3244 bool StdMeshers_Cartesian_3D::Compute(SMESH_Mesh & theMesh,
3245 const TopoDS_Shape & theShape)
3247 // The algorithm generates the mesh in following steps:
3249 // 1) Intersection of grid lines with the geometry boundary.
3250 // This step allows to find out if a given node of the initial grid is
3251 // inside or outside the geometry.
3253 // 2) For each cell of the grid, check how many of it's nodes are outside
3254 // of the geometry boundary. Depending on a result of this check
3255 // - skip a cell, if all it's nodes are outside
3256 // - skip a cell, if it is too small according to the size threshold
3257 // - add a hexahedron in the mesh, if all nodes are inside
3258 // - add a polyhedron in the mesh, if some nodes are inside and some outside
3260 _computeCanceled = false;
3262 SMESH_MesherHelper helper( theMesh );
3267 grid._helper = &helper;
3269 vector< TopoDS_Shape > faceVec;
3271 TopTools_MapOfShape faceMap;
3272 TopExp_Explorer fExp;
3273 for ( fExp.Init( theShape, TopAbs_FACE ); fExp.More(); fExp.Next() )
3274 if ( !faceMap.Add( fExp.Current() ))
3275 faceMap.Remove( fExp.Current() ); // remove a face shared by two solids
3277 for ( fExp.ReInit(); fExp.More(); fExp.Next() )
3278 if ( faceMap.Contains( fExp.Current() ))
3279 faceVec.push_back( fExp.Current() );
3281 vector<FaceGridIntersector> facesItersectors( faceVec.size() );
3282 map< TGeomID, vector< TGeomID > > edge2faceIDsMap;
3283 TopExp_Explorer eExp;
3285 for ( int i = 0; i < faceVec.size(); ++i )
3287 facesItersectors[i]._face = TopoDS::Face ( faceVec[i] );
3288 facesItersectors[i]._faceID = grid._shapes.Add( faceVec[i] );
3289 facesItersectors[i]._grid = &grid;
3290 shapeBox.Add( facesItersectors[i].GetFaceBndBox() );
3292 if ( _hyp->GetToAddEdges() )
3294 helper.SetSubShape( faceVec[i] );
3295 for ( eExp.Init( faceVec[i], TopAbs_EDGE ); eExp.More(); eExp.Next() )
3297 const TopoDS_Edge& edge = TopoDS::Edge( eExp.Current() );
3298 if ( !SMESH_Algo::isDegenerated( edge ) &&
3299 !helper.IsRealSeam( edge ))
3300 edge2faceIDsMap[ grid._shapes.Add( edge )].push_back( facesItersectors[i]._faceID );
3305 getExactBndBox( faceVec, _hyp->GetAxisDirs(), shapeBox );
3307 vector<double> xCoords, yCoords, zCoords;
3308 _hyp->GetCoordinates( xCoords, yCoords, zCoords, shapeBox );
3310 grid.SetCoordinates( xCoords, yCoords, zCoords, _hyp->GetAxisDirs(), shapeBox );
3312 if ( _computeCanceled ) return false;
3315 { // copy partner faces and curves of not thread-safe types
3316 set< const Standard_Transient* > tshapes;
3317 BRepBuilderAPI_Copy copier;
3318 for ( size_t i = 0; i < facesItersectors.size(); ++i )
3320 if ( !facesItersectors[i].IsThreadSafe(tshapes) )
3322 copier.Perform( facesItersectors[i]._face );
3323 facesItersectors[i]._face = TopoDS::Face( copier );
3327 // Intersection of grid lines with the geometry boundary.
3328 tbb::parallel_for ( tbb::blocked_range<size_t>( 0, facesItersectors.size() ),
3329 ParallelIntersector( facesItersectors ),
3330 tbb::simple_partitioner());
3332 for ( size_t i = 0; i < facesItersectors.size(); ++i )
3333 facesItersectors[i].Intersect();
3336 // put interesection points onto the GridLine's; this is done after intersection
3337 // to avoid contention of facesItersectors for writing into the same GridLine
3338 // in case of parallel work of facesItersectors
3339 for ( size_t i = 0; i < facesItersectors.size(); ++i )
3340 facesItersectors[i].StoreIntersections();
3342 TopExp_Explorer solidExp (theShape, TopAbs_SOLID);
3343 helper.SetSubShape( solidExp.Current() );
3344 helper.SetElementsOnShape( true );
3346 if ( _computeCanceled ) return false;
3348 // create nodes on the geometry
3349 grid.ComputeNodes(helper);
3351 if ( _computeCanceled ) return false;
3353 // create volume elements
3354 Hexahedron hex( _hyp->GetSizeThreshold(), &grid );
3355 int nbAdded = hex.MakeElements( helper, edge2faceIDsMap );
3357 SMESHDS_Mesh* meshDS = theMesh.GetMeshDS();
3360 // make all SOLIDs computed
3361 if ( SMESHDS_SubMesh* sm1 = meshDS->MeshElements( solidExp.Current()) )
3363 SMDS_ElemIteratorPtr volIt = sm1->GetElements();
3364 for ( ; solidExp.More() && volIt->more(); solidExp.Next() )
3366 const SMDS_MeshElement* vol = volIt->next();
3367 sm1->RemoveElement( vol, /*isElemDeleted=*/false );
3368 meshDS->SetMeshElementOnShape( vol, solidExp.Current() );
3371 // make other sub-shapes computed
3372 setSubmeshesComputed( theMesh, theShape );
3375 // remove free nodes
3376 if ( SMESHDS_SubMesh * smDS = meshDS->MeshElements( helper.GetSubShapeID() ))
3378 TIDSortedNodeSet nodesToRemove;
3379 // get intersection nodes
3380 for ( int iDir = 0; iDir < 3; ++iDir )
3382 vector< GridLine >& lines = grid._lines[ iDir ];
3383 for ( size_t i = 0; i < lines.size(); ++i )
3385 multiset< F_IntersectPoint >::iterator ip = lines[i]._intPoints.begin();
3386 for ( ; ip != lines[i]._intPoints.end(); ++ip )
3387 if ( ip->_node && ip->_node->NbInverseElements() == 0 )
3388 nodesToRemove.insert( nodesToRemove.end(), ip->_node );
3392 for ( size_t i = 0; i < grid._nodes.size(); ++i )
3393 if ( grid._nodes[i] && grid._nodes[i]->NbInverseElements() == 0 )
3394 nodesToRemove.insert( nodesToRemove.end(), grid._nodes[i] );
3397 TIDSortedNodeSet::iterator n = nodesToRemove.begin();
3398 for ( ; n != nodesToRemove.end(); ++n )
3399 meshDS->RemoveFreeNode( *n, smDS, /*fromGroups=*/false );
3405 // SMESH_ComputeError is not caught at SMESH_submesh level for an unknown reason
3406 catch ( SMESH_ComputeError& e)
3408 return error( SMESH_ComputeErrorPtr( new SMESH_ComputeError( e )));
3413 //=============================================================================
3417 //=============================================================================
3419 bool StdMeshers_Cartesian_3D::Evaluate(SMESH_Mesh & theMesh,
3420 const TopoDS_Shape & theShape,
3421 MapShapeNbElems& theResMap)
3424 // std::vector<int> aResVec(SMDSEntity_Last);
3425 // for(int i=SMDSEntity_Node; i<SMDSEntity_Last; i++) aResVec[i] = 0;
3426 // if(IsQuadratic) {
3427 // aResVec[SMDSEntity_Quad_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
3428 // int nb1d_face0_int = ( nb2d_face0*4 - nb1d ) / 2;
3429 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( 2*nb2d/nb1d - 1 ) - nb1d_face0_int * nb2d/nb1d;
3432 // aResVec[SMDSEntity_Node] = nb0d_face0 * ( nb2d/nb1d - 1 );
3433 // aResVec[SMDSEntity_Cartesian] = nb2d_face0 * ( nb2d/nb1d );
3435 // SMESH_subMesh * sm = aMesh.GetSubMesh(aShape);
3436 // aResMap.insert(std::make_pair(sm,aResVec));
3441 //=============================================================================
3445 * \brief Event listener setting/unsetting _alwaysComputed flag to
3446 * submeshes of inferior levels to prevent their computing
3448 struct _EventListener : public SMESH_subMeshEventListener
3452 _EventListener(const string& algoName):
3453 SMESH_subMeshEventListener(/*isDeletable=*/true,"StdMeshers_Cartesian_3D::_EventListener"),
3456 // --------------------------------------------------------------------------------
3457 // setting/unsetting _alwaysComputed flag to submeshes of inferior levels
3459 static void setAlwaysComputed( const bool isComputed,
3460 SMESH_subMesh* subMeshOfSolid)
3462 SMESH_subMeshIteratorPtr smIt =
3463 subMeshOfSolid->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3464 while ( smIt->more() )
3466 SMESH_subMesh* sm = smIt->next();
3467 sm->SetIsAlwaysComputed( isComputed );
3469 subMeshOfSolid->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3472 // --------------------------------------------------------------------------------
3473 // unsetting _alwaysComputed flag if "Cartesian_3D" was removed
3475 virtual void ProcessEvent(const int event,
3476 const int eventType,
3477 SMESH_subMesh* subMeshOfSolid,
3478 SMESH_subMeshEventListenerData* data,
3479 const SMESH_Hypothesis* hyp = 0)
3481 if ( eventType == SMESH_subMesh::COMPUTE_EVENT )
3483 setAlwaysComputed( subMeshOfSolid->GetComputeState() == SMESH_subMesh::COMPUTE_OK,
3488 SMESH_Algo* algo3D = subMeshOfSolid->GetAlgo();
3489 if ( !algo3D || _algoName != algo3D->GetName() )
3490 setAlwaysComputed( false, subMeshOfSolid );
3494 // --------------------------------------------------------------------------------
3495 // set the event listener
3497 static void SetOn( SMESH_subMesh* subMeshOfSolid, const string& algoName )
3499 subMeshOfSolid->SetEventListener( new _EventListener( algoName ),
3504 }; // struct _EventListener
3508 //================================================================================
3510 * \brief Sets event listener to submeshes if necessary
3511 * \param subMesh - submesh where algo is set
3512 * This method is called when a submesh gets HYP_OK algo_state.
3513 * After being set, event listener is notified on each event of a submesh.
3515 //================================================================================
3517 void StdMeshers_Cartesian_3D::SetEventListener(SMESH_subMesh* subMesh)
3519 _EventListener::SetOn( subMesh, GetName() );
3522 //================================================================================
3524 * \brief Set _alwaysComputed flag to submeshes of inferior levels to avoid their computing
3526 //================================================================================
3528 void StdMeshers_Cartesian_3D::setSubmeshesComputed(SMESH_Mesh& theMesh,
3529 const TopoDS_Shape& theShape)
3531 for ( TopExp_Explorer soExp( theShape, TopAbs_SOLID ); soExp.More(); soExp.Next() )
3532 _EventListener::setAlwaysComputed( true, theMesh.GetSubMesh( soExp.Current() ));