1 // Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_ViscousLayers.cxx
21 // Created : Wed Dec 1 15:15:34 2010
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers.hxx"
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_ControlsDef.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_Mesh.hxx"
39 #include "SMESH_MesherHelper.hxx"
40 #include "SMESH_ProxyMesh.hxx"
41 #include "SMESH_subMesh.hxx"
42 #include "SMESH_subMeshEventListener.hxx"
44 #include "utilities.h"
46 #include <BRepAdaptor_Curve2d.hxx>
47 #include <BRep_Tool.hxx>
48 #include <Bnd_B2d.hxx>
49 #include <Bnd_B3d.hxx>
51 #include <GCPnts_AbscissaPoint.hxx>
52 #include <Geom2d_Circle.hxx>
53 #include <Geom2d_Line.hxx>
54 #include <Geom2d_TrimmedCurve.hxx>
55 #include <GeomAdaptor_Curve.hxx>
56 #include <Geom_Circle.hxx>
57 #include <Geom_Curve.hxx>
58 #include <Geom_Line.hxx>
59 #include <Geom_TrimmedCurve.hxx>
60 #include <Precision.hxx>
61 #include <Standard_ErrorHandler.hxx>
62 #include <TColStd_Array1OfReal.hxx>
64 #include <TopExp_Explorer.hxx>
65 #include <TopTools_IndexedMapOfShape.hxx>
66 #include <TopTools_MapOfShape.hxx>
68 #include <TopoDS_Edge.hxx>
69 #include <TopoDS_Face.hxx>
70 #include <TopoDS_Vertex.hxx>
84 //================================================================================
89 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
92 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
93 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
95 struct _MeshOfSolid : public SMESH_ProxyMesh,
96 public SMESH_subMeshEventListenerData
100 _MeshOfSolid( SMESH_Mesh* mesh)
101 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
103 SMESH_ProxyMesh::setMesh( *mesh );
106 // returns submesh for a geom face
107 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
109 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
110 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
112 void setNode2Node(const SMDS_MeshNode* srcNode,
113 const SMDS_MeshNode* proxyNode,
114 const SMESH_ProxyMesh::SubMesh* subMesh)
116 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
119 //--------------------------------------------------------------------------------
121 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
122 * It is used to clear an inferior dim sub-meshes modified by viscous layers
124 class _SrinkShapeListener : SMESH_subMeshEventListener
126 _SrinkShapeListener()
127 : SMESH_subMeshEventListener(/*isDeletable=*/false,
128 "StdMeshers_ViscousLayers::_SrinkShapeListener") {}
129 static SMESH_subMeshEventListener* Get() { static _SrinkShapeListener l; return &l; }
131 virtual void ProcessEvent(const int event,
133 SMESH_subMesh* solidSM,
134 SMESH_subMeshEventListenerData* data,
135 const SMESH_Hypothesis* hyp)
137 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
139 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
142 static void ToClearSubMeshWithSolid( SMESH_subMesh* sm,
143 const TopoDS_Shape& solid)
145 SMESH_subMesh* solidSM = sm->GetFather()->GetSubMesh( solid );
146 SMESH_subMeshEventListenerData* data = solidSM->GetEventListenerData( Get());
149 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sm ) ==
150 data->mySubMeshes.end())
151 data->mySubMeshes.push_back( sm );
155 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sm );
156 sm->SetEventListener( Get(), data, /*whereToListenTo=*/solidSM );
160 //--------------------------------------------------------------------------------
162 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
163 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
164 * delete the data as soon as it has been used
166 class _ViscousListener : SMESH_subMeshEventListener
169 SMESH_subMeshEventListener(/*isDeletable=*/false,
170 "StdMeshers_ViscousLayers::_ViscousListener") {}
171 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
173 virtual void ProcessEvent(const int event,
175 SMESH_subMesh* subMesh,
176 SMESH_subMeshEventListenerData* data,
177 const SMESH_Hypothesis* hyp)
179 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
181 // delete SMESH_ProxyMesh containing temporary faces
182 subMesh->DeleteEventListener( this );
185 // Finds or creates proxy mesh of the solid
186 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
187 const TopoDS_Shape& solid,
190 if ( !mesh ) return 0;
191 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
192 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
193 if ( !data && toCreate )
195 data = new _MeshOfSolid(mesh);
196 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
197 sm->SetEventListener( Get(), data, sm );
201 // Removes proxy mesh of the solid
202 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
204 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
208 //--------------------------------------------------------------------------------
210 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
211 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
212 * The class is used to check validity of face or volumes around a smoothed node;
213 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
217 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
218 _Simplex(const SMDS_MeshNode* nPrev=0, const SMDS_MeshNode* nNext=0)
219 : _nPrev(nPrev), _nNext(nNext) {}
220 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
222 const double M[3][3] =
223 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
224 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
225 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
226 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
227 + M[0][1]*M[1][2]*M[2][0]
228 + M[0][2]*M[1][0]*M[2][1]
229 - M[0][0]*M[1][2]*M[2][1]
230 - M[0][1]*M[1][0]*M[2][2]
231 - M[0][2]*M[1][1]*M[2][0]);
232 return determinant > 1e-100;
234 bool IsForward(const gp_XY& tgtUV,
235 const SMDS_MeshNode* smoothedNode,
236 const TopoDS_Face& face,
237 SMESH_MesherHelper& helper,
238 const double refSign) const
240 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
241 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
242 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
244 return d*refSign > 1e-100;
246 bool IsNeighbour(const _Simplex& other) const
248 return _nPrev == other._nNext || _nNext == other._nPrev;
251 //--------------------------------------------------------------------------------
253 * Structure used to take into account surface curvature while smoothing
258 double _k; // factor to correct node smoothed position
260 static _Curvature* New( double avgNormProj, double avgDist )
263 if ( fabs( avgNormProj / avgDist ) > 1./200 )
266 c->_r = avgDist * avgDist / avgNormProj;
267 c->_k = avgDist * avgDist / c->_r / c->_r;
268 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
272 double lenDelta(double len) const { return _k * ( _r + len ); }
275 //--------------------------------------------------------------------------------
277 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
281 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
282 const SMDS_MeshNode* _nodes[2];
283 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
285 double _wgt[2]; // weights of _nodes
286 _LayerEdge* _edges[2];
288 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
291 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
293 std::swap( _nodes[0], _nodes[1] );
294 std::swap( _wgt[0], _wgt[1] );
297 //--------------------------------------------------------------------------------
299 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
300 * and a node of the most internal layer (_nodes.back())
304 vector< const SMDS_MeshNode*> _nodes;
306 gp_XYZ _normal; // to solid surface
307 vector<gp_XYZ> _pos; // points computed during inflation
308 double _len; // length achived with the last step
309 double _cosin; // of angle (_normal ^ surface)
310 double _lenFactor; // to compute _len taking _cosin into account
312 // face or edge w/o layer along or near which _LayerEdge is inflated
314 // simplices connected to the source node (_nodes[0]);
315 // used for smoothing and quality check of _LayerEdge's based on the FACE
316 vector<_Simplex> _simplices;
317 // data for smoothing of _LayerEdge's based on the EDGE
318 _2NearEdges* _2neibors;
320 _Curvature* _curvature;
321 // TODO:: detele _Curvature, _plnNorm
323 void SetNewLength( double len, SMESH_MesherHelper& helper );
324 bool SetNewLength2d( Handle(Geom_Surface)& surface,
325 const TopoDS_Face& F,
326 SMESH_MesherHelper& helper );
327 void SetDataByNeighbors( const SMDS_MeshNode* n1,
328 const SMDS_MeshNode* n2,
329 SMESH_MesherHelper& helper);
330 void InvalidateStep( int curStep );
331 bool Smooth(int& badNb);
332 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
333 const TopoDS_Face& F,
334 SMESH_MesherHelper& helper);
335 bool FindIntersection( SMESH_ElementSearcher& searcher,
337 const double& epsilon,
338 const SMDS_MeshElement** face = 0);
339 bool SegTriaInter( const gp_Ax1& lastSegment,
340 const SMDS_MeshNode* n0,
341 const SMDS_MeshNode* n1,
342 const SMDS_MeshNode* n2,
344 const double& epsilon) const;
345 gp_Ax1 LastSegment(double& segLen) const;
346 bool IsOnEdge() const { return _2neibors; }
347 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
348 void SetCosin( double cosin );
352 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
354 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
355 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
358 //--------------------------------------------------------------------------------
360 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
362 //--------------------------------------------------------------------------------
364 * \brief Data of a SOLID
369 const StdMeshers_ViscousLayers* _hyp;
370 _MeshOfSolid* _proxyMesh;
371 set<TGeomID> _reversedFaceIds;
373 double _stepSize, _stepSizeCoeff;
374 const SMDS_MeshNode* _stepSizeNodes[2];
377 // edges of _n2eMap. We keep same data in two containers because
378 // iteration over the map is 5 time longer than over the vector
379 vector< _LayerEdge* > _edges;
381 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
382 // layers and a FACE w/o layers
383 // value: the shape (FACE or EDGE) to shrink mesh on.
384 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
385 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
387 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
388 set< TGeomID > _noShrinkFaces;
390 // <EDGE to smooth on> to <it's curve>
391 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
393 // end indices in _edges of _LayerEdge on one shape to smooth
394 vector< int > _endEdgeToSmooth;
396 double _epsilon; // precision for SegTriaInter()
398 int _index; // for debug
400 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
401 const StdMeshers_ViscousLayers* h=0,
402 _MeshOfSolid* m=0) :_solid(s), _hyp(h), _proxyMesh(m) {}
405 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
408 Handle(Geom_Surface)& surface,
409 const TopoDS_Face& F,
410 SMESH_MesherHelper& helper);
412 //--------------------------------------------------------------------------------
414 * \brief Data of node on a shrinked FACE
418 const SMDS_MeshNode* _node;
419 //vector<const SMDS_MeshNode*> _nodesAround;
420 vector<_Simplex> _simplices; // for quality check
422 bool Smooth(int& badNb,
423 Handle(Geom_Surface)& surface,
424 SMESH_MesherHelper& helper,
425 const double refSign,
429 //--------------------------------------------------------------------------------
431 * \brief Builder of viscous layers
433 class _ViscousBuilder
438 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
439 const TopoDS_Shape& shape);
441 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
442 void RestoreListeners();
444 // computes SMESH_ProxyMesh::SubMesh::_n2n;
445 bool MakeN2NMap( _MeshOfSolid* pm );
449 bool findSolidsWithLayers();
450 bool findFacesWithLayers();
451 bool makeLayer(_SolidData& data);
452 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
453 SMESH_MesherHelper& helper, _SolidData& data);
454 bool findNeiborsOnEdge(const _LayerEdge* edge,
455 const SMDS_MeshNode*& n1,
456 const SMDS_MeshNode*& n2,
458 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
459 const set<TGeomID>& ingnoreShapes,
460 const _SolidData* dataToCheckOri = 0,
461 const bool toSort = false);
462 bool sortEdges( _SolidData& data,
463 vector< vector<_LayerEdge*> >& edgesByGeom);
464 void limitStepSize( _SolidData& data,
465 const SMDS_MeshElement* face,
467 void limitStepSize( _SolidData& data, const double minSize);
468 bool inflate(_SolidData& data);
469 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
470 bool smoothAnalyticEdge( _SolidData& data,
473 Handle(Geom_Surface)& surface,
474 const TopoDS_Face& F,
475 SMESH_MesherHelper& helper);
476 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
477 bool refine(_SolidData& data);
479 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
480 SMESH_MesherHelper& helper,
481 const SMESHDS_SubMesh* faceSubMesh );
482 void fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper);
483 bool addBoundaryElements();
485 bool error( const string& text, int solidID=-1 );
486 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
489 void makeGroupOfLE();
492 SMESH_ComputeErrorPtr _error;
494 vector< _SolidData > _sdVec;
495 set<TGeomID> _ignoreShapeIds;
498 //--------------------------------------------------------------------------------
500 * \brief Shrinker of nodes on the EDGE
504 vector<double> _initU;
505 vector<double> _normPar;
506 vector<const SMDS_MeshNode*> _nodes;
507 const _LayerEdge* _edges[2];
510 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
511 void Compute(bool set3D, SMESH_MesherHelper& helper);
512 void RestoreParams();
513 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
515 //--------------------------------------------------------------------------------
517 * \brief Class of temporary mesh face.
518 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
519 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
521 struct TmpMeshFace : public SMDS_MeshElement
523 vector<const SMDS_MeshNode* > _nn;
524 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
525 SMDS_MeshElement(id), _nn(nodes) {}
526 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
527 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
528 virtual vtkIdType GetVtkType() const { return -1; }
529 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
530 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const
531 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
533 //--------------------------------------------------------------------------------
535 * \brief Class of temporary mesh face storing _LayerEdge it's based on
537 struct TmpMeshFaceOnEdge : public TmpMeshFace
539 _LayerEdge *_le1, *_le2;
540 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
541 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
543 _nn[0]=_le1->_nodes[0];
544 _nn[1]=_le1->_nodes.back();
545 _nn[2]=_le2->_nodes.back();
546 _nn[3]=_le2->_nodes[0];
549 } // namespace VISCOUS
551 //================================================================================
552 // StdMeshers_ViscousLayers hypothesis
554 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
555 :SMESH_Hypothesis(hypId, studyId, gen),
556 _nbLayers(1), _thickness(1), _stretchFactor(1)
558 _name = StdMeshers_ViscousLayers::GetHypType();
559 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
560 } // --------------------------------------------------------------------------------
561 void StdMeshers_ViscousLayers::SetIgnoreFaces(const std::vector<int>& faceIds)
563 if ( faceIds != _ignoreFaceIds )
564 _ignoreFaceIds = faceIds, NotifySubMeshesHypothesisModification();
565 } // --------------------------------------------------------------------------------
566 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
568 if ( thickness != _thickness )
569 _thickness = thickness, NotifySubMeshesHypothesisModification();
570 } // --------------------------------------------------------------------------------
571 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
573 if ( _nbLayers != nb )
574 _nbLayers = nb, NotifySubMeshesHypothesisModification();
575 } // --------------------------------------------------------------------------------
576 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
578 if ( _stretchFactor != factor )
579 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
580 } // --------------------------------------------------------------------------------
582 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
583 const TopoDS_Shape& theShape,
584 const bool toMakeN2NMap) const
586 using namespace VISCOUS;
587 _ViscousBuilder bulder;
588 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
589 if ( err && !err->IsOK() )
590 return SMESH_ProxyMesh::Ptr();
592 vector<SMESH_ProxyMesh::Ptr> components;
593 TopExp_Explorer exp( theShape, TopAbs_SOLID );
594 for ( ; exp.More(); exp.Next() )
596 if ( _MeshOfSolid* pm =
597 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
599 if ( toMakeN2NMap && !pm->_n2nMapComputed )
600 if ( !bulder.MakeN2NMap( pm ))
601 return SMESH_ProxyMesh::Ptr();
602 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
603 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
605 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
607 switch ( components.size() )
611 case 1: return components[0];
613 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
615 return SMESH_ProxyMesh::Ptr();
616 } // --------------------------------------------------------------------------------
617 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
619 save << " " << _nbLayers
621 << " " << _stretchFactor
622 << " " << _ignoreFaceIds.size();
623 for ( unsigned i = 0; i < _ignoreFaceIds.size(); ++i )
624 save << " " << _ignoreFaceIds[i];
626 } // --------------------------------------------------------------------------------
627 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
630 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
631 while ( _ignoreFaceIds.size() < nbFaces && load >> faceID )
632 _ignoreFaceIds.push_back( faceID );
634 } // --------------------------------------------------------------------------------
635 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
636 const TopoDS_Shape& theShape)
641 // END StdMeshers_ViscousLayers hypothesis
642 //================================================================================
646 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
650 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
651 gp_Pnt p = BRep_Tool::Pnt( fromV );
652 double distF = p.SquareDistance( c->Value( f ));
653 double distL = p.SquareDistance( c->Value( l ));
654 c->D1(( distF < distL ? f : l), p, dir );
655 if ( distL < distF ) dir.Reverse();
658 //--------------------------------------------------------------------------------
659 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
660 SMESH_MesherHelper& helper)
663 double f,l; gp_Pnt p;
664 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
665 double u = helper.GetNodeU( E, atNode );
669 //--------------------------------------------------------------------------------
670 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
671 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
673 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
674 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
675 gp_Pnt p; gp_Vec du, dv, norm;
676 surface->D1( uv.X(),uv.Y(), p, du,dv );
680 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
681 double u = helper.GetNodeU( fromE, node, 0, &ok );
683 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
684 if ( o == TopAbs_REVERSED )
687 gp_Vec dir = norm ^ du;
689 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
690 helper.IsClosedEdge( fromE ))
692 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
693 else c->D1( f, p, dv );
694 if ( o == TopAbs_REVERSED )
696 gp_Vec dir2 = norm ^ dv;
697 dir = dir.Normalized() + dir2.Normalized();
701 //--------------------------------------------------------------------------------
702 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
703 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
704 bool& ok, double* cosin=0)
706 double f,l; TopLoc_Location loc;
707 vector< TopoDS_Edge > edges; // sharing a vertex
708 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
711 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
712 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
713 edges.push_back( *e );
716 if ( !( ok = ( edges.size() > 0 ))) return dir;
717 // get average dir of edges going fromV
719 for ( unsigned i = 0; i < edges.size(); ++i )
721 edgeDir = getEdgeDir( edges[i], fromV );
722 double size2 = edgeDir.SquareMagnitude();
723 if ( size2 > numeric_limits<double>::min() )
724 edgeDir /= sqrt( size2 );
727 dir += edgeDir.XYZ();
729 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
730 if ( edges.size() == 1 || dir.SquareModulus() < 1e-10)
732 else if ( dir * fromEdgeDir < 0 )
736 //dir /= edges.size();
738 double angle = edgeDir.Angle( dir );
739 *cosin = cos( angle );
744 //================================================================================
746 * \brief Returns true if a FACE is bound by a concave EDGE
748 //================================================================================
750 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
754 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
755 for ( ; eExp.More(); eExp.Next() )
757 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
758 if ( BRep_Tool::Degenerated( E )) continue;
759 // check if 2D curve is concave
760 BRepAdaptor_Curve2d curve( E, F );
761 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
762 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
763 curve.Intervals( intervals, GeomAbs_C2 );
764 bool isConvex = true;
765 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
767 double u1 = intervals( i );
768 double u2 = intervals( i+1 );
769 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
770 double cross = drv2 ^ drv1;
771 if ( E.Orientation() == TopAbs_REVERSED )
773 isConvex = ( cross < 1e-9 );
775 // check if concavity is strong enough to care about it
776 //const double maxAngle = 5 * Standard_PI180;
779 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
781 // map< double, const SMDS_MeshNode* > u2nodes;
782 // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
783 // /*ignoreMedium=*/true, u2nodes))
785 // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
786 // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
787 // double uPrev = u2n->first;
788 // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
790 // gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
791 // gp_Vec2d segmentDir( uvPrev, uv );
792 // curve.D1( uPrev, p, drv1 );
794 // if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
799 // uPrev = u2n->first;
805 //--------------------------------------------------------------------------------
806 // DEBUG. Dump intermediate node positions into a python script
811 const char* fname = "/tmp/viscous.py";
812 cout << "execfile('"<<fname<<"')"<<endl;
813 py = new ofstream(fname);
814 *py << "from smesh import *" << endl
815 << "meshSO = GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
816 << "mesh = Mesh( meshSO.GetObject() )"<<endl;
820 *py << "mesh.MakeGroup('Viscous Prisms',VOLUME,FT_ElemGeomType,'=',Geom_PENTA)"<<endl;
823 ~PyDump() { Finish(); }
825 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
826 #define dumpMove(n) { _dumpMove(n, __LINE__);}
827 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
828 void _dumpFunction(const string& fun, int ln)
829 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
830 void _dumpMove(const SMDS_MeshNode* n, int ln)
831 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
832 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
833 void _dumpCmd(const string& txt, int ln)
834 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
835 void dumpFunctionEnd()
836 { if (py) *py<< " return"<< endl; }
837 void dumpChangeNodes( const SMDS_MeshElement* f )
838 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
839 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
840 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
842 struct PyDump { void Finish() {} };
843 #define dumpFunction(f) f
846 #define dumpFunctionEnd()
847 #define dumpChangeNodes(f)
851 using namespace VISCOUS;
853 //================================================================================
855 * \brief Constructor of _ViscousBuilder
857 //================================================================================
859 _ViscousBuilder::_ViscousBuilder()
861 _error = SMESH_ComputeError::New(COMPERR_OK);
865 //================================================================================
867 * \brief Stores error description and returns false
869 //================================================================================
871 bool _ViscousBuilder::error(const string& text, int solidId )
873 _error->myName = COMPERR_ALGO_FAILED;
874 _error->myComment = string("Viscous layers builder: ") + text;
877 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
878 if ( !sm && !_sdVec.empty() )
879 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
880 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
882 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
883 if ( smError && smError->myAlgo )
884 _error->myAlgo = smError->myAlgo;
888 makeGroupOfLE(); // debug
893 //================================================================================
895 * \brief At study restoration, restore event listeners used to clear an inferior
896 * dim sub-mesh modified by viscous layers
898 //================================================================================
900 void _ViscousBuilder::RestoreListeners()
905 //================================================================================
907 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
909 //================================================================================
911 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
913 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
914 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
915 for ( ; fExp.More(); fExp.Next() )
917 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
918 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
920 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
922 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
925 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
926 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
928 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
929 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
930 while( prxIt->more() )
932 const SMDS_MeshElement* fSrc = srcIt->next();
933 const SMDS_MeshElement* fPrx = prxIt->next();
934 if ( fSrc->NbNodes() != fPrx->NbNodes())
935 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
936 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
937 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
940 pm->_n2nMapComputed = true;
944 //================================================================================
946 * \brief Does its job
948 //================================================================================
950 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
951 const TopoDS_Shape& theShape)
953 // TODO: set priority of solids during Gen::Compute()
957 // check if proxy mesh already computed
958 TopExp_Explorer exp( theShape, TopAbs_SOLID );
960 return error("No SOLID's in theShape"), _error;
962 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
963 return SMESH_ComputeErrorPtr(); // everything already computed
967 // TODO: ignore already computed SOLIDs
968 if ( !findSolidsWithLayers())
971 if ( !findFacesWithLayers() )
974 for ( unsigned i = 0; i < _sdVec.size(); ++i )
976 if ( ! makeLayer(_sdVec[i]) )
979 if ( ! inflate(_sdVec[i]) )
982 if ( ! refine(_sdVec[i]) )
988 addBoundaryElements();
990 makeGroupOfLE(); // debug
996 //================================================================================
998 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1000 //================================================================================
1002 bool _ViscousBuilder::findSolidsWithLayers()
1005 TopTools_IndexedMapOfShape allSolids;
1006 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1007 _sdVec.reserve( allSolids.Extent());
1009 SMESH_Gen* gen = _mesh->GetGen();
1010 for ( int i = 1; i <= allSolids.Extent(); ++i )
1012 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1013 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1014 if ( !algo ) continue;
1015 // TODO: check if algo is hidden
1016 const list <const SMESHDS_Hypothesis *> & allHyps =
1017 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1018 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1019 const StdMeshers_ViscousLayers* viscHyp = 0;
1020 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1021 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1024 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1027 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, proxyMesh ));
1028 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1031 if ( _sdVec.empty() )
1033 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1038 //================================================================================
1042 //================================================================================
1044 bool _ViscousBuilder::findFacesWithLayers()
1046 // collect all faces to ignore defined by hyp
1047 vector<TopoDS_Shape> ignoreFaces;
1048 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1050 vector<TGeomID> ids = _sdVec[i]._hyp->GetIgnoreFaces();
1051 for ( unsigned i = 0; i < ids.size(); ++i )
1053 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
1054 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1056 _ignoreShapeIds.insert( ids[i] );
1057 ignoreFaces.push_back( s );
1062 // ignore internal faces
1063 SMESH_MesherHelper helper( *_mesh );
1064 TopExp_Explorer exp;
1065 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1067 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1068 for ( ; exp.More(); exp.Next() )
1070 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1071 if ( helper.NbAncestors( exp.Current(), *_mesh, TopAbs_SOLID ) > 1 )
1073 _ignoreShapeIds.insert( faceInd );
1074 ignoreFaces.push_back( exp.Current() );
1075 if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face( exp.Current() ), getMeshDS()))
1076 _sdVec[i]._reversedFaceIds.insert( faceInd );
1081 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1082 TopTools_IndexedMapOfShape shapes;
1083 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1086 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1087 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1089 const TopoDS_Shape& edge = shapes(iE);
1090 // find 2 faces sharing an edge
1092 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1093 while ( fIt->more())
1095 const TopoDS_Shape* f = fIt->next();
1096 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1097 FF[ int( !FF[0].IsNull()) ] = *f;
1099 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1100 // check presence of layers on them
1102 for ( int j = 0; j < 2; ++j )
1103 ignore[j] = _ignoreShapeIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1104 if ( ignore[0] == ignore[1] ) continue; // nothing interesting
1105 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1107 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1108 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1111 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1112 // the algo of the SOLID sharing the FACE does not support it
1113 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1114 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1116 TopTools_MapOfShape noShrinkVertices;
1117 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1118 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1120 const TopoDS_Shape& fWOL = e2f->second;
1121 TGeomID edgeID = e2f->first;
1122 bool notShrinkFace = false;
1123 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1124 while ( soIt->more())
1126 const TopoDS_Shape* solid = soIt->next();
1127 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1128 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1129 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1130 notShrinkFace = true;
1131 for ( unsigned j = 0; j < _sdVec.size(); ++j )
1133 if ( _sdVec[j]._solid.IsSame( *solid ) )
1134 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1135 notShrinkFace = false;
1138 if ( notShrinkFace )
1140 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1141 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1142 noShrinkVertices.Add( vExp.Current() );
1145 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1146 // to the found not shrinked fWOL's
1147 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1148 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1150 TGeomID edgeID = e2f->first;
1151 TopoDS_Vertex VV[2];
1152 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1153 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1155 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1156 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1165 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1167 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1170 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1171 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1173 const TopoDS_Shape& vertex = shapes(iV);
1174 // find faces WOL sharing the vertex
1175 vector< TopoDS_Shape > facesWOL;
1176 int totalNbFaces = 0;
1177 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1178 while ( fIt->more())
1180 const TopoDS_Shape* f = fIt->next();
1181 const int fID = getMeshDS()->ShapeToIndex( *f );
1182 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1185 if ( _ignoreShapeIds.count ( fID ) && ! _sdVec[i]._noShrinkFaces.count( fID ))
1186 facesWOL.push_back( *f );
1189 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1190 continue; // no layers at this vertex or no WOL
1191 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1192 switch ( facesWOL.size() )
1196 helper.SetSubShape( facesWOL[0] );
1197 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1199 TopoDS_Shape seamEdge;
1200 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1201 while ( eIt->more() && seamEdge.IsNull() )
1203 const TopoDS_Shape* e = eIt->next();
1204 if ( helper.IsRealSeam( *e ) )
1207 if ( !seamEdge.IsNull() )
1209 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1213 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1218 // find an edge shared by 2 faces
1219 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1220 while ( eIt->more())
1222 const TopoDS_Shape* e = eIt->next();
1223 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1224 helper.IsSubShape( *e, facesWOL[1]))
1226 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1232 return error("Not yet supported case", _sdVec[i]._index);
1240 //================================================================================
1242 * \brief Create the inner surface of the viscous layer and prepare data for infation
1244 //================================================================================
1246 bool _ViscousBuilder::makeLayer(_SolidData& data)
1248 // get all sub-shapes to make layers on
1249 set<TGeomID> subIds, faceIds;
1250 subIds = data._noShrinkFaces;
1251 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1252 for ( ; exp.More(); exp.Next() )
1253 if ( ! _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1255 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1256 faceIds.insert( fSubM->GetId() );
1257 SMESH_subMeshIteratorPtr subIt =
1258 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1259 while ( subIt->more() )
1260 subIds.insert( subIt->next()->GetId() );
1263 // make a map to find new nodes on sub-shapes shared with other SOLID
1264 map< TGeomID, TNode2Edge* > s2neMap;
1265 map< TGeomID, TNode2Edge* >::iterator s2ne;
1266 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1267 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1269 TGeomID shapeInd = s2s->first;
1270 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1272 if ( _sdVec[i]._index == data._index ) continue;
1273 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1274 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1275 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1277 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1283 // Create temporary faces and _LayerEdge's
1285 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1287 data._stepSize = Precision::Infinite();
1288 data._stepSizeNodes[0] = 0;
1290 SMESH_MesherHelper helper( *_mesh );
1291 helper.SetSubShape( data._solid );
1292 helper.SetElementsOnShape(true);
1294 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1295 TNode2Edge::iterator n2e2;
1297 // collect _LayerEdge's of shapes they are based on
1298 const int nbShapes = getMeshDS()->MaxShapeIndex();
1299 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1301 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1303 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1304 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1306 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1307 SMESH_ProxyMesh::SubMesh* proxySub =
1308 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1310 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1311 while ( eIt->more() )
1313 const SMDS_MeshElement* face = eIt->next();
1314 newNodes.resize( face->NbCornerNodes() );
1315 double faceMaxCosin = -1;
1316 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1318 const SMDS_MeshNode* n = face->GetNode(i);
1319 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1320 if ( !(*n2e).second )
1323 _LayerEdge* edge = new _LayerEdge();
1325 edge->_nodes.push_back( n );
1326 const int shapeID = n->getshapeId();
1327 edgesByGeom[ shapeID ].push_back( edge );
1329 // set edge data or find already refined _LayerEdge and get data from it
1330 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1331 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1332 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1334 _LayerEdge* foundEdge = (*n2e2).second;
1335 edge->Copy( *foundEdge, helper );
1336 // location of the last node is modified but we can restore
1337 // it by node position on _sWOL stored by the node
1338 const_cast< SMDS_MeshNode* >
1339 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1343 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1344 if ( !setEdgeData( *edge, subIds, helper, data ))
1347 dumpMove(edge->_nodes.back());
1348 if ( edge->_cosin > 0.01 )
1350 if ( edge->_cosin > faceMaxCosin )
1351 faceMaxCosin = edge->_cosin;
1354 newNodes[ i ] = n2e->second->_nodes.back();
1356 // create a temporary face
1357 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1358 proxySub->AddElement( newFace );
1360 // compute inflation step size by min size of element on a convex surface
1361 if ( faceMaxCosin > 0.1 )
1362 limitStepSize( data, face, faceMaxCosin );
1363 } // loop on 2D elements on a FACE
1364 } // loop on FACEs of a SOLID
1366 data._epsilon = 1e-7;
1367 if ( data._stepSize < 1. )
1368 data._epsilon *= data._stepSize;
1370 // Put _LayerEdge's into a vector
1372 if ( !sortEdges( data, edgesByGeom ))
1375 // Set target nodes into _Simplex and _2NearEdges
1376 TNode2Edge::iterator n2e;
1377 for ( unsigned i = 0; i < data._edges.size(); ++i )
1379 if ( data._edges[i]->IsOnEdge())
1380 for ( int j = 0; j < 2; ++j )
1382 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1383 break; // _LayerEdge is shared by two _SolidData's
1384 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1385 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1386 return error("_LayerEdge not found by src node", data._index);
1387 n = (*n2e).second->_nodes.back();
1388 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1391 for ( unsigned j = 0; j < data._edges[i]->_simplices.size(); ++j )
1393 _Simplex& s = data._edges[i]->_simplices[j];
1394 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1395 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1403 //================================================================================
1405 * \brief Compute inflation step size by min size of element on a convex surface
1407 //================================================================================
1409 void _ViscousBuilder::limitStepSize( _SolidData& data,
1410 const SMDS_MeshElement* face,
1414 double minSize = 10 * data._stepSize;
1415 const int nbNodes = face->NbCornerNodes();
1416 for ( int i = 0; i < nbNodes; ++i )
1418 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1419 const SMDS_MeshNode* curN = face->GetNode( i );
1420 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1421 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1423 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1424 if ( dist < minSize )
1425 minSize = dist, iN = i;
1428 double newStep = 0.8 * minSize / cosin;
1429 if ( newStep < data._stepSize )
1431 data._stepSize = newStep;
1432 data._stepSizeCoeff = 0.8 / cosin;
1433 data._stepSizeNodes[0] = face->GetNode( iN );
1434 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1438 //================================================================================
1440 * \brief Compute inflation step size by min size of element on a convex surface
1442 //================================================================================
1444 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1446 if ( minSize < data._stepSize )
1448 data._stepSize = minSize;
1449 if ( data._stepSizeNodes[0] )
1452 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1453 data._stepSizeCoeff = data._stepSize / dist;
1458 //================================================================================
1460 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1462 //================================================================================
1464 bool _ViscousBuilder::sortEdges( _SolidData& data,
1465 vector< vector<_LayerEdge*> >& edgesByGeom)
1467 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1468 // boundry inclined at a sharp angle to the shape
1470 list< TGeomID > shapesToSmooth;
1472 SMESH_MesherHelper helper( *_mesh );
1475 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1477 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1478 if ( eS.empty() ) continue;
1479 TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1480 bool needSmooth = false;
1481 switch ( S.ShapeType() )
1485 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1486 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1488 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1489 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1490 if ( eV.empty() ) continue;
1491 double cosin = eV[0]->_cosin;
1493 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1497 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1498 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1500 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1501 eV[0]->_nodes[0], helper, ok);
1502 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1503 double angle = dir1.Angle( dir2 );
1504 cosin = cos( angle );
1506 needSmooth = ( cosin > 0.1 );
1512 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1514 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1515 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1516 if ( eE.empty() ) continue;
1517 if ( eE[0]->_sWOL.IsNull() )
1519 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1520 needSmooth = ( eE[i]->_cosin > 0.1 );
1524 const TopoDS_Face& F1 = TopoDS::Face( S );
1525 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1526 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1527 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1529 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1530 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1531 double angle = dir1.Angle( dir2 );
1532 double cosin = cos( angle );
1533 needSmooth = ( cosin > 0.1 );
1545 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1546 else shapesToSmooth.push_back ( iS );
1549 } // loop on edgesByGeom
1551 data._edges.reserve( data._n2eMap.size() );
1552 data._endEdgeToSmooth.clear();
1554 // first we put _LayerEdge's on shapes to smooth
1555 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1556 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1558 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1559 if ( eVec.empty() ) continue;
1560 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1561 data._endEdgeToSmooth.push_back( data._edges.size() );
1565 // then the rest _LayerEdge's
1566 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1568 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1569 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1576 //================================================================================
1578 * \brief Set data of _LayerEdge needed for smoothing
1579 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1581 //================================================================================
1583 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1584 const set<TGeomID>& subIds,
1585 SMESH_MesherHelper& helper,
1588 SMESH_MeshEditor editor(_mesh);
1590 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1591 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1595 edge._curvature = 0;
1597 // --------------------------
1598 // Compute _normal and _cosin
1599 // --------------------------
1602 edge._normal.SetCoord(0,0,0);
1604 int totalNbFaces = 0;
1606 gp_Vec du, dv, geomNorm;
1609 TGeomID shapeInd = node->getshapeId();
1610 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1611 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1612 TopoDS_Shape vertEdge;
1614 if ( onShrinkShape ) // one of faces the node is on has no layers
1616 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1617 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1619 // inflate from VERTEX along EDGE
1620 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1622 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1624 // inflate from VERTEX along FACE
1625 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1626 node, helper, normOK, &edge._cosin);
1630 // inflate from EDGE along FACE
1631 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1632 node, helper, normOK);
1635 else // layers are on all faces of SOLID the node is on
1637 // find indices of geom faces the node lies on
1638 set<TGeomID> faceIds;
1639 if ( posType == SMDS_TOP_FACE )
1641 faceIds.insert( node->getshapeId() );
1645 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1646 while ( fIt->more() )
1647 faceIds.insert( editor.FindShape(fIt->next()));
1650 set<TGeomID>::iterator id = faceIds.begin();
1652 for ( ; id != faceIds.end(); ++id )
1654 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1655 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1658 //nbLayerFaces += subIds.count( *id );
1659 F = TopoDS::Face( s );
1661 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1662 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1663 surface->D1( uv.X(),uv.Y(), p, du,dv );
1665 double size2 = geomNorm.SquareMagnitude();
1666 if ( size2 > numeric_limits<double>::min() )
1667 geomNorm /= sqrt( size2 );
1670 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1672 edge._normal += geomNorm.XYZ();
1674 if ( totalNbFaces == 0 )
1675 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1677 edge._normal /= totalNbFaces;
1682 edge._cosin = 0; break;
1684 case SMDS_TOP_EDGE: {
1685 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1686 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1687 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1688 edge._cosin = cos( angle );
1689 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1692 case SMDS_TOP_VERTEX: {
1693 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1694 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK);
1695 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1696 edge._cosin = cos( angle );
1697 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1701 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1705 double normSize = edge._normal.SquareModulus();
1706 if ( normSize < numeric_limits<double>::min() )
1707 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1709 edge._normal /= sqrt( normSize );
1711 // TODO: if ( !normOK ) then get normal by mesh faces
1713 // Set the rest data
1714 // --------------------
1715 if ( onShrinkShape )
1717 edge._sWOL = (*s2s).second;
1719 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1720 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1721 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1723 // set initial position which is parameters on _sWOL in this case
1724 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1726 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1727 edge._pos.push_back( gp_XYZ( u, 0, 0));
1728 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1732 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1733 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1734 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1739 edge._pos.push_back( SMESH_TNodeXYZ( node ));
1741 if ( posType == SMDS_TOP_FACE )
1743 getSimplices( node, edge._simplices, _ignoreShapeIds, &data );
1744 double avgNormProj = 0, avgLen = 0;
1745 for ( unsigned i = 0; i < edge._simplices.size(); ++i )
1747 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
1748 avgNormProj += edge._normal * vec;
1749 avgLen += vec.Modulus();
1751 avgNormProj /= edge._simplices.size();
1752 avgLen /= edge._simplices.size();
1753 edge._curvature = _Curvature::New( avgNormProj, avgLen );
1757 // Set neighbour nodes for a _LayerEdge based on EDGE
1759 if ( posType == SMDS_TOP_EDGE /*||
1760 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1762 edge._2neibors = new _2NearEdges;
1763 // target node instead of source ones will be set later
1764 if ( ! findNeiborsOnEdge( &edge,
1765 edge._2neibors->_nodes[0],
1766 edge._2neibors->_nodes[1],
1769 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1770 edge._2neibors->_nodes[1],
1774 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1779 //================================================================================
1781 * \brief Find 2 neigbor nodes of a node on EDGE
1783 //================================================================================
1785 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
1786 const SMDS_MeshNode*& n1,
1787 const SMDS_MeshNode*& n2,
1790 const SMDS_MeshNode* node = edge->_nodes[0];
1791 const int shapeInd = node->getshapeId();
1792 SMESHDS_SubMesh* edgeSM = 0;
1793 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
1796 edgeSM = getMeshDS()->MeshElements( shapeInd );
1797 if ( !edgeSM || edgeSM->NbElements() == 0 )
1798 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
1802 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
1803 while ( eIt->more() && !n2 )
1805 const SMDS_MeshElement* e = eIt->next();
1806 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
1807 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
1810 if (!edgeSM->Contains(e)) continue;
1814 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
1815 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
1817 ( iN++ ? n2 : n1 ) = nNeibor;
1820 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
1824 //================================================================================
1826 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
1828 //================================================================================
1830 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
1831 const SMDS_MeshNode* n2,
1832 SMESH_MesherHelper& helper)
1834 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1837 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
1838 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
1839 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
1843 double sumLen = vec1.Modulus() + vec2.Modulus();
1844 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
1845 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
1846 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
1847 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
1848 if ( _curvature ) delete _curvature;
1849 _curvature = _Curvature::New( avgNormProj, avgLen );
1851 // if ( _curvature )
1852 // cout << _nodes[0]->GetID()
1853 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
1854 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
1855 // << _curvature->lenDelta(0) << endl;
1860 if ( _sWOL.IsNull() )
1862 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
1863 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
1864 gp_XYZ plnNorm = dirE ^ _normal;
1865 double proj0 = plnNorm * vec1;
1866 double proj1 = plnNorm * vec2;
1867 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
1869 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
1870 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
1875 //================================================================================
1877 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
1878 * this and other _LayerEdge's are inflated along a FACE or an EDGE
1880 //================================================================================
1882 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
1884 _nodes = other._nodes;
1885 _normal = other._normal;
1887 _lenFactor = other._lenFactor;
1888 _cosin = other._cosin;
1889 _sWOL = other._sWOL;
1890 _2neibors = other._2neibors;
1891 _curvature = 0; std::swap( _curvature, other._curvature );
1892 _2neibors = 0; std::swap( _2neibors, other._2neibors );
1894 if ( _sWOL.ShapeType() == TopAbs_EDGE )
1896 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
1897 _pos.push_back( gp_XYZ( u, 0, 0));
1901 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
1902 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1906 //================================================================================
1908 * \brief Set _cosin and _lenFactor
1910 //================================================================================
1912 void _LayerEdge::SetCosin( double cosin )
1915 _lenFactor = ( _cosin > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
1918 //================================================================================
1920 * \brief Fills a vector<_Simplex >
1922 //================================================================================
1924 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
1925 vector<_Simplex>& simplices,
1926 const set<TGeomID>& ingnoreShapes,
1927 const _SolidData* dataToCheckOri,
1930 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1931 while ( fIt->more() )
1933 const SMDS_MeshElement* f = fIt->next();
1934 const TGeomID shapeInd = f->getshapeId();
1935 if ( ingnoreShapes.count( shapeInd )) continue;
1936 const int nbNodes = f->NbCornerNodes();
1937 int srcInd = f->GetNodeIndex( node );
1938 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
1939 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
1940 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
1941 std::swap( nPrev, nNext );
1942 simplices.push_back( _Simplex( nPrev, nNext ));
1947 vector<_Simplex> sortedSimplices( simplices.size() );
1948 sortedSimplices[0] = simplices[0];
1950 for ( size_t i = 1; i < simplices.size(); ++i )
1952 for ( size_t j = 1; j < simplices.size(); ++j )
1953 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
1955 sortedSimplices[i] = simplices[j];
1960 if ( nbFound == simplices.size() - 1 )
1961 simplices.swap( sortedSimplices );
1965 //================================================================================
1967 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
1969 //================================================================================
1971 void _ViscousBuilder::makeGroupOfLE()
1974 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
1976 if ( _sdVec[i]._edges.empty() ) continue;
1977 // string name = SMESH_Comment("_LayerEdge's_") << i;
1979 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
1980 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
1981 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
1983 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
1984 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1986 _LayerEdge* le = _sdVec[i]._edges[j];
1987 for ( unsigned iN = 1; iN < le->_nodes.size(); ++iN )
1988 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
1989 << ", " << le->_nodes[iN]->GetID() <<"])");
1990 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
1994 dumpFunction( SMESH_Comment("makeNormals") << i );
1995 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1997 _LayerEdge& edge = *_sdVec[i]._edges[j];
1998 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
1999 nXYZ += edge._normal * _sdVec[i]._stepSize;
2000 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2001 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2005 // name = SMESH_Comment("tmp_faces ") << i;
2006 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2007 // gDS = (SMESHDS_Group*)g->GetGroupDS();
2008 // SMESH_MeshEditor editor( _mesh );
2009 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2010 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2011 for ( ; fExp.More(); fExp.Next() )
2013 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2015 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2016 while ( fIt->more())
2018 const SMDS_MeshElement* e = fIt->next();
2019 SMESH_Comment cmd("mesh.AddFace([");
2020 for ( int j=0; j < e->NbCornerNodes(); ++j )
2021 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2023 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2024 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2033 //================================================================================
2035 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2037 //================================================================================
2039 bool _ViscousBuilder::inflate(_SolidData& data)
2041 SMESH_MesherHelper helper( *_mesh );
2043 // Limit inflation step size by geometry size found by itersecting
2044 // normals of _LayerEdge's with mesh faces
2045 double geomSize = Precision::Infinite(), intersecDist;
2046 SMESH_MeshEditor editor( _mesh );
2047 auto_ptr<SMESH_ElementSearcher> searcher
2048 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2049 for ( unsigned i = 0; i < data._edges.size(); ++i )
2051 if ( data._edges[i]->IsOnEdge() ) continue;
2052 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2053 if ( geomSize > intersecDist )
2054 geomSize = intersecDist;
2056 if ( data._stepSize > 0.3 * geomSize )
2057 limitStepSize( data, 0.3 * geomSize );
2059 const double tgtThick = data._hyp->GetTotalThickness();
2060 if ( data._stepSize > tgtThick )
2061 limitStepSize( data, tgtThick );
2063 if ( data._stepSize < 1. )
2064 data._epsilon = data._stepSize * 1e-7;
2067 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2070 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2071 int nbSteps = 0, nbRepeats = 0;
2072 while ( 1.01 * avgThick < tgtThick )
2074 // new target length
2075 curThick += data._stepSize;
2076 if ( curThick > tgtThick )
2078 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2082 // Elongate _LayerEdge's
2083 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2084 for ( unsigned i = 0; i < data._edges.size(); ++i )
2086 data._edges[i]->SetNewLength( curThick, helper );
2091 if ( !updateNormals( data, helper ) )
2094 // Improve and check quality
2095 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2099 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2100 for ( unsigned i = 0; i < data._edges.size(); ++i )
2102 data._edges[i]->InvalidateStep( nbSteps+1 );
2106 break; // no more inflating possible
2110 // Evaluate achieved thickness
2112 for ( unsigned i = 0; i < data._edges.size(); ++i )
2113 avgThick += data._edges[i]->_len;
2114 avgThick /= data._edges.size();
2116 cout << "-- Thickness " << avgThick << " reached" << endl;
2119 if ( distToIntersection < avgThick*1.5 )
2122 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2123 << avgThick << " ) * 1.5" << endl;
2128 limitStepSize( data, 0.25 * distToIntersection );
2129 if ( data._stepSizeNodes[0] )
2130 data._stepSize = data._stepSizeCoeff *
2131 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2135 return error("failed at the very first inflation step", data._index);
2140 //================================================================================
2142 * \brief Improve quality of layer inner surface and check intersection
2144 //================================================================================
2146 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2148 double & distToIntersection)
2150 if ( data._endEdgeToSmooth.empty() )
2151 return true; // no shapes needing smoothing
2153 bool moved, improved;
2155 SMESH_MesherHelper helper(*_mesh);
2156 Handle(Geom_Surface) surface;
2160 for ( unsigned iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2163 iEnd = data._endEdgeToSmooth[ iS ];
2165 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2166 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2168 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2169 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2170 helper.SetSubShape( F );
2171 surface = BRep_Tool::Surface( F );
2176 F.Nullify(); surface.Nullify();
2178 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2180 if ( data._edges[ iBeg ]->IsOnEdge() )
2182 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2184 // try a simple solution on an analytic EDGE
2185 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2191 for ( int i = iBeg; i < iEnd; ++i )
2193 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2195 dumpCmd( SMESH_Comment("# end step ")<<step);
2197 while ( moved && step++ < 5 );
2198 //cout << " NB STEPS: " << step << endl;
2205 int step = 0, badNb = 0; moved = true;
2206 while (( ++step <= 5 && moved ) || improved )
2208 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2209 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2210 int oldBadNb = badNb;
2213 for ( int i = iBeg; i < iEnd; ++i )
2214 moved |= data._edges[i]->Smooth(badNb);
2215 improved = ( badNb < oldBadNb );
2222 for ( int i = iBeg; i < iEnd; ++i )
2224 _LayerEdge* edge = data._edges[i];
2225 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2226 for ( unsigned j = 0; j < edge->_simplices.size(); ++j )
2227 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2229 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2230 << " "<< edge->_simplices[j]._nPrev->GetID()
2231 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2239 } // loop on shapes to smooth
2241 // Check if the last segments of _LayerEdge intersects 2D elements;
2242 // checked elements are either temporary faces or faces on surfaces w/o the layers
2244 SMESH_MeshEditor editor( _mesh );
2245 auto_ptr<SMESH_ElementSearcher> searcher
2246 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2248 distToIntersection = Precision::Infinite();
2250 const SMDS_MeshElement* intFace = 0;
2252 const SMDS_MeshElement* closestFace = 0;
2255 for ( unsigned i = 0; i < data._edges.size(); ++i )
2257 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2259 if ( distToIntersection > dist )
2261 distToIntersection = dist;
2264 closestFace = intFace;
2271 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2272 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2273 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2274 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2275 << ") distance = " << distToIntersection<< endl;
2282 //================================================================================
2284 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2285 * _LayerEdge's to be in a consequent order
2287 //================================================================================
2289 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2292 Handle(Geom_Surface)& surface,
2293 const TopoDS_Face& F,
2294 SMESH_MesherHelper& helper)
2296 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2298 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2300 if ( i2curve == _edge2curve.end() )
2302 // sort _LayerEdge's by position on the EDGE
2304 map< double, _LayerEdge* > u2edge;
2305 for ( int i = iFrom; i < iTo; ++i )
2306 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2308 ASSERT( u2edge.size() == iTo - iFrom );
2309 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2310 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2311 _edges[i] = u2e->second;
2313 // set _2neibors according to the new order
2314 for ( int i = iFrom; i < iTo-1; ++i )
2315 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2316 _edges[i]->_2neibors->reverse();
2317 if ( u2edge.size() > 1 &&
2318 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2319 _edges[iTo-1]->_2neibors->reverse();
2322 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2324 TopLoc_Location loc; double f,l;
2326 Handle(Geom_Line) line;
2327 Handle(Geom_Circle) circle;
2328 bool isLine, isCirc;
2329 if ( F.IsNull() ) // 3D case
2331 // check if the EDGE is a line
2332 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2333 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2334 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2336 line = Handle(Geom_Line)::DownCast( curve );
2337 circle = Handle(Geom_Circle)::DownCast( curve );
2338 isLine = (!line.IsNull());
2339 isCirc = (!circle.IsNull());
2341 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2344 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2345 while ( nIt->more() )
2346 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2347 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2349 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2350 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2351 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2352 for ( int i = 0; i < 3 && !isLine; ++i )
2353 isLine = ( size.Coord( i+1 ) <= lineTol );
2355 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2362 // check if the EDGE is a line
2363 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2364 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2365 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2367 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2368 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2369 isLine = (!line2d.IsNull());
2370 isCirc = (!circle2d.IsNull());
2372 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2375 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2376 while ( nIt->more() )
2377 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2378 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2380 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2381 for ( int i = 0; i < 2 && !isLine; ++i )
2382 isLine = ( size.Coord( i+1 ) <= lineTol );
2384 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2390 line = new Geom_Line( gp::OX() ); // only type does matter
2394 gp_Pnt2d p = circle2d->Location();
2395 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2396 circle = new Geom_Circle( ax, 1.); // only center position does matter
2400 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2408 return i2curve->second;
2411 //================================================================================
2413 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2415 //================================================================================
2417 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2420 Handle(Geom_Surface)& surface,
2421 const TopoDS_Face& F,
2422 SMESH_MesherHelper& helper)
2424 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2425 helper.GetMeshDS());
2426 TopoDS_Edge E = TopoDS::Edge( S );
2428 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2429 if ( curve.IsNull() ) return false;
2431 // compute a relative length of segments
2432 vector< double > len( iTo-iFrom+1 );
2434 double curLen, prevLen = len[0] = 1.0;
2435 for ( int i = iFrom; i < iTo; ++i )
2437 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2438 len[i-iFrom+1] = len[i-iFrom] + curLen;
2443 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2445 if ( F.IsNull() ) // 3D
2447 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2448 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2449 for ( int i = iFrom; i < iTo; ++i )
2451 double r = len[i-iFrom] / len.back();
2452 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2453 data._edges[i]->_pos.back() = newPos;
2454 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2455 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2456 dumpMove( tgtNode );
2461 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2462 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2463 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2464 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2466 int iPeriodic = helper.GetPeriodicIndex();
2467 if ( iPeriodic == 1 || iPeriodic == 2 )
2469 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2470 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2471 std::swap( uv0, uv1 );
2474 const gp_XY rangeUV = uv1 - uv0;
2475 for ( int i = iFrom; i < iTo; ++i )
2477 double r = len[i-iFrom] / len.back();
2478 gp_XY newUV = uv0 + r * rangeUV;
2479 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2481 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2482 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2483 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2484 dumpMove( tgtNode );
2486 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2487 pos->SetUParameter( newUV.X() );
2488 pos->SetVParameter( newUV.Y() );
2494 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2496 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2497 gp_Pnt center3D = circle->Location();
2499 if ( F.IsNull() ) // 3D
2501 return false; // TODO ???
2505 const gp_XY center( center3D.X(), center3D.Y() );
2507 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2508 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2509 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2510 gp_Vec2d vec0( center, uv0 );
2511 gp_Vec2d vecM( center, uvM);
2512 gp_Vec2d vec1( center, uv1 );
2513 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2514 double uMidl = vec0.Angle( vecM );
2515 if ( uLast < 0 ) uLast += 2.*M_PI; // 0.0 - 2*PI
2516 if ( uMidl < 0 ) uMidl += 2.*M_PI;
2517 const bool sense = ( uMidl < uLast );
2518 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2520 gp_Ax2d axis( center, vec0 );
2521 gp_Circ2d circ ( axis, radius, sense );
2522 for ( int i = iFrom; i < iTo; ++i )
2524 double newU = uLast * len[i-iFrom] / len.back();
2525 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2526 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2528 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2529 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2530 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2531 dumpMove( tgtNode );
2533 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2534 pos->SetUParameter( newUV.X() );
2535 pos->SetVParameter( newUV.Y() );
2544 //================================================================================
2546 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2547 * _LayerEdge's on neighbor EDGE's
2549 //================================================================================
2551 bool _ViscousBuilder::updateNormals( _SolidData& data,
2552 SMESH_MesherHelper& helper )
2554 // make temporary quadrangles got by extrusion of
2555 // mesh edges along _LayerEdge._normal's
2557 vector< const SMDS_MeshElement* > tmpFaces;
2559 set< SMESH_TLink > extrudedLinks; // contains target nodes
2560 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2562 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2563 for ( unsigned i = 0; i < data._edges.size(); ++i )
2565 _LayerEdge* edge = data._edges[i];
2566 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2567 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2568 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2570 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2571 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2572 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2573 if ( !link_isnew.second )
2575 extrudedLinks.erase( link_isnew.first );
2576 continue; // already extruded and will no more encounter
2578 // look for a _LayerEdge containg tgt2
2579 // _LayerEdge* neiborEdge = 0;
2580 // unsigned di = 0; // check _edges[i+di] and _edges[i-di]
2581 // while ( !neiborEdge && ++di <= data._edges.size() )
2583 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2584 // neiborEdge = data._edges[i+di];
2585 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2586 // neiborEdge = data._edges[i-di];
2588 // if ( !neiborEdge )
2589 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2590 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2592 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2593 tmpFaces.push_back( f );
2595 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2596 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2597 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2602 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2603 // Perform two loops on _LayerEdge on EDGE's:
2604 // 1) to find and fix intersection
2605 // 2) to check that no new intersection appears as result of 1)
2607 SMESH_MeshEditor editor( _mesh );
2608 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2610 auto_ptr<SMESH_ElementSearcher> searcher ( editor.GetElementSearcher( fIt ));
2612 // 1) Find intersections
2614 const SMDS_MeshElement* face;
2615 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2616 TLEdge2LEdgeSet edge2CloseEdge;
2618 const double eps = data._epsilon * data._epsilon;
2619 for ( unsigned i = 0; i < data._edges.size(); ++i )
2621 _LayerEdge* edge = data._edges[i];
2622 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2623 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2625 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2626 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2627 ee.insert( f->_le1 );
2628 ee.insert( f->_le2 );
2629 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
2630 edge2CloseEdge[ f->_le1 ].insert( edge );
2631 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
2632 edge2CloseEdge[ f->_le2 ].insert( edge );
2636 // Set _LayerEdge._normal
2638 if ( !edge2CloseEdge.empty() )
2640 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2642 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2643 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2645 _LayerEdge* edge1 = e2ee->first;
2646 _LayerEdge* edge2 = 0;
2647 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
2649 // find EDGEs the edges reside
2651 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2652 if ( S.ShapeType() != TopAbs_EDGE )
2653 continue; // TODO: find EDGE by VERTEX
2654 E1 = TopoDS::Edge( S );
2655 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
2656 while ( E2.IsNull() && eIt != ee.end())
2658 _LayerEdge* e2 = *eIt++;
2659 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2660 if ( S.ShapeType() == TopAbs_EDGE )
2661 E2 = TopoDS::Edge( S ), edge2 = e2;
2663 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2665 // find 3 FACEs sharing 2 EDGEs
2667 TopoDS_Face FF1[2], FF2[2];
2668 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2669 while ( fIt->more() && FF1[1].IsNull())
2671 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2672 if ( helper.IsSubShape( *F, data._solid))
2673 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2675 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2676 while ( fIt->more() && FF2[1].IsNull())
2678 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2679 if ( helper.IsSubShape( *F, data._solid))
2680 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2682 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2683 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2684 std::swap( FF1[0], FF1[1] );
2685 if ( FF2[0].IsSame( FF1[0]) )
2686 std::swap( FF2[0], FF2[1] );
2687 if ( FF1[0].IsNull() || FF2[0].IsNull() )
2690 // // get a new normal for edge1
2692 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2693 if ( edge1->_cosin < 0 )
2694 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2695 if ( edge2->_cosin < 0 )
2696 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2697 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2698 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2699 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2700 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2701 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2702 // newNorm.Normalize();
2704 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2705 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2706 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2707 newNorm.Normalize();
2709 edge1->_normal = newNorm.XYZ();
2711 // update data of edge1 depending on _normal
2712 const SMDS_MeshNode *n1, *n2;
2713 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2714 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2715 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2717 edge1->SetDataByNeighbors( n1, n2, helper );
2719 if ( edge1->_cosin < 0 )
2722 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2723 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2724 edge1->SetCosin( cos( angle ));
2726 // limit data._stepSize
2727 if ( edge1->_cosin > 0.1 )
2729 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2730 while ( fIt->more() )
2731 limitStepSize( data, fIt->next(), edge1->_cosin );
2733 // set new XYZ of target node
2734 edge1->InvalidateStep( 1 );
2736 edge1->SetNewLength( data._stepSize, helper );
2739 // Update normals and other dependent data of not intersecting _LayerEdge's
2740 // neighboring the intersecting ones
2742 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2744 _LayerEdge* edge1 = e2ee->first;
2745 if ( !edge1->_2neibors )
2747 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2749 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2750 if ( edge2CloseEdge.count ( neighbor ))
2751 continue; // j-th neighbor is also intersected
2752 _LayerEdge* prevEdge = edge1;
2753 const int nbSteps = 6;
2754 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2756 if ( !neighbor->_2neibors )
2757 break; // neighbor is on VERTEX
2759 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2760 if ( nextEdge == prevEdge )
2761 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2762 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2763 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
2764 double r = double(step-1)/nbSteps;
2765 if ( !nextEdge->_2neibors )
2768 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2769 newNorm.Normalize();
2771 neighbor->_normal = newNorm;
2772 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2773 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2775 neighbor->InvalidateStep( 1 );
2777 neighbor->SetNewLength( data._stepSize, helper );
2779 // goto the next neighbor
2780 prevEdge = neighbor;
2781 neighbor = nextEdge;
2787 // 2) Check absence of intersections
2790 for ( unsigned i = 0 ; i < tmpFaces.size(); ++i )
2796 //================================================================================
2798 * \brief Looks for intersection of it's last segment with faces
2799 * \param distance - returns shortest distance from the last node to intersection
2801 //================================================================================
2803 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
2805 const double& epsilon,
2806 const SMDS_MeshElement** face)
2808 vector< const SMDS_MeshElement* > suspectFaces;
2810 gp_Ax1 lastSegment = LastSegment(segLen);
2811 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2813 bool segmentIntersected = false;
2814 distance = Precision::Infinite();
2815 int iFace = -1; // intersected face
2816 for ( unsigned j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
2818 const SMDS_MeshElement* face = suspectFaces[j];
2819 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
2820 face->GetNodeIndex( _nodes[0] ) >= 0 )
2821 continue; // face sharing _LayerEdge node
2822 const int nbNodes = face->NbCornerNodes();
2823 bool intFound = false;
2825 SMDS_MeshElement::iterator nIt = face->begin_nodes();
2828 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
2832 const SMDS_MeshNode* tria[3];
2835 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
2838 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
2844 if ( dist < segLen*(1.01))
2845 segmentIntersected = true;
2846 if ( distance > dist )
2847 distance = dist, iFace = j;
2850 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
2851 // if ( distance && iFace > -1 )
2853 // // distance is used to limit size of inflation step which depends on
2854 // // whether the intersected face bears viscous layers or not
2855 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
2859 if ( segmentIntersected )
2862 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
2863 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
2864 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
2865 << ", intersection with face ("
2866 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2867 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
2868 << ") distance = " << distance - segLen<< endl;
2874 return segmentIntersected;
2877 //================================================================================
2879 * \brief Returns size and direction of the last segment
2881 //================================================================================
2883 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
2885 // find two non-coincident positions
2886 gp_XYZ orig = _pos.back();
2888 int iPrev = _pos.size() - 2;
2889 while ( iPrev >= 0 )
2891 dir = orig - _pos[iPrev];
2892 if ( dir.SquareModulus() > 1e-100 )
2902 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
2903 segDir.SetDirection( _normal );
2908 gp_Pnt pPrev = _pos[ iPrev ];
2909 if ( !_sWOL.IsNull() )
2911 TopLoc_Location loc;
2912 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2915 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2916 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
2920 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2921 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
2923 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
2925 segDir.SetLocation( pPrev );
2926 segDir.SetDirection( dir );
2927 segLen = dir.Modulus();
2933 //================================================================================
2935 * \brief Test intersection of the last segment with a given triangle
2936 * using Moller-Trumbore algorithm
2937 * Intersection is detected if distance to intersection is less than _LayerEdge._len
2939 //================================================================================
2941 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
2942 const SMDS_MeshNode* n0,
2943 const SMDS_MeshNode* n1,
2944 const SMDS_MeshNode* n2,
2946 const double& EPSILON) const
2948 //const double EPSILON = 1e-6;
2950 gp_XYZ orig = lastSegment.Location().XYZ();
2951 gp_XYZ dir = lastSegment.Direction().XYZ();
2953 SMESH_TNodeXYZ vert0( n0 );
2954 SMESH_TNodeXYZ vert1( n1 );
2955 SMESH_TNodeXYZ vert2( n2 );
2957 /* calculate distance from vert0 to ray origin */
2958 gp_XYZ tvec = orig - vert0;
2960 if ( tvec * dir > EPSILON )
2961 // intersected face is at back side of the temporary face this _LayerEdge belongs to
2964 gp_XYZ edge1 = vert1 - vert0;
2965 gp_XYZ edge2 = vert2 - vert0;
2967 /* begin calculating determinant - also used to calculate U parameter */
2968 gp_XYZ pvec = dir ^ edge2;
2970 /* if determinant is near zero, ray lies in plane of triangle */
2971 double det = edge1 * pvec;
2973 if (det > -EPSILON && det < EPSILON)
2975 double inv_det = 1.0 / det;
2977 /* calculate U parameter and test bounds */
2978 double u = ( tvec * pvec ) * inv_det;
2979 if (u < 0.0 || u > 1.0)
2982 /* prepare to test V parameter */
2983 gp_XYZ qvec = tvec ^ edge1;
2985 /* calculate V parameter and test bounds */
2986 double v = (dir * qvec) * inv_det;
2987 if ( v < 0.0 || u + v > 1.0 )
2990 /* calculate t, ray intersects triangle */
2991 t = (edge2 * qvec) * inv_det;
2993 // if (det < EPSILON)
2996 // /* calculate distance from vert0 to ray origin */
2997 // gp_XYZ tvec = orig - vert0;
2999 // /* calculate U parameter and test bounds */
3000 // double u = tvec * pvec;
3001 // if (u < 0.0 || u > det)
3004 // /* prepare to test V parameter */
3005 // gp_XYZ qvec = tvec ^ edge1;
3007 // /* calculate V parameter and test bounds */
3008 // double v = dir * qvec;
3009 // if (v < 0.0 || u + v > det)
3012 // /* calculate t, scale parameters, ray intersects triangle */
3013 // double t = edge2 * qvec;
3014 // double inv_det = 1.0 / det;
3022 //================================================================================
3024 * \brief Perform smooth of _LayerEdge's based on EDGE's
3025 * \retval bool - true if node has been moved
3027 //================================================================================
3029 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3030 const TopoDS_Face& F,
3031 SMESH_MesherHelper& helper)
3033 ASSERT( IsOnEdge() );
3035 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3036 SMESH_TNodeXYZ oldPos( tgtNode );
3037 double dist01, distNewOld;
3039 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3040 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3041 dist01 = p0.Distance( _2neibors->_nodes[1] );
3043 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3044 double lenDelta = 0;
3047 lenDelta = _curvature->lenDelta( _len );
3048 newPos.ChangeCoord() += _normal * lenDelta;
3051 distNewOld = newPos.Distance( oldPos );
3055 if ( _2neibors->_plnNorm )
3057 // put newPos on the plane defined by source node and _plnNorm
3058 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3059 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3060 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3062 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3063 _pos.back() = newPos.XYZ();
3067 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3068 gp_XY uv( Precision::Infinite(), 0 );
3069 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3070 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3072 newPos = surface->Value( uv.X(), uv.Y() );
3073 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3076 if ( _curvature && lenDelta < 0 )
3078 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3079 _len -= prevPos.Distance( oldPos );
3080 _len += prevPos.Distance( newPos );
3082 bool moved = distNewOld > dist01/50;
3084 dumpMove( tgtNode ); // debug
3089 //================================================================================
3091 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3092 * \retval bool - true if _tgtNode has been moved
3094 //================================================================================
3096 bool _LayerEdge::Smooth(int& badNb)
3098 if ( _simplices.size() < 2 )
3099 return false; // _LayerEdge inflated along EDGE or FACE
3101 // compute new position for the last _pos
3102 gp_XYZ newPos (0,0,0);
3103 for ( unsigned i = 0; i < _simplices.size(); ++i )
3104 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3105 newPos /= _simplices.size();
3108 newPos += _normal * _curvature->lenDelta( _len );
3110 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3111 // if ( _cosin < -0.1)
3113 // // Avoid decreasing length of edge on concave surface
3114 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3115 // gp_Vec newMove( prevPos, newPos );
3116 // newPos = _pos.back() + newMove.XYZ();
3118 // else if ( _cosin > 0.3 )
3120 // // Avoid increasing length of edge too much
3123 // count quality metrics (orientation) of tetras around _tgtNode
3125 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3126 for ( unsigned i = 0; i < _simplices.size(); ++i )
3127 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3130 for ( unsigned i = 0; i < _simplices.size(); ++i )
3131 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3133 if ( nbOkAfter < nbOkBefore )
3136 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3138 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3139 _len += prevPos.Distance(newPos);
3141 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3142 _pos.back() = newPos;
3144 badNb += _simplices.size() - nbOkAfter;
3151 //================================================================================
3153 * \brief Add a new segment to _LayerEdge during inflation
3155 //================================================================================
3157 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3159 if ( _len - len > -1e-6 )
3161 _pos.push_back( _pos.back() );
3165 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3166 SMESH_TNodeXYZ oldXYZ( n );
3167 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3168 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3170 _pos.push_back( nXYZ );
3172 if ( !_sWOL.IsNull() )
3175 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3177 double u = Precision::Infinite(); // to force projection w/o distance check
3178 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3179 _pos.back().SetCoord( u, 0, 0 );
3180 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3181 pos->SetUParameter( u );
3185 gp_XY uv( Precision::Infinite(), 0 );
3186 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3187 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3188 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3189 pos->SetUParameter( uv.X() );
3190 pos->SetVParameter( uv.Y() );
3192 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3194 dumpMove( n ); //debug
3197 //================================================================================
3199 * \brief Remove last inflation step
3201 //================================================================================
3203 void _LayerEdge::InvalidateStep( int curStep )
3205 if ( _pos.size() > curStep )
3207 _pos.resize( curStep );
3208 gp_Pnt nXYZ = _pos.back();
3209 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3210 if ( !_sWOL.IsNull() )
3212 TopLoc_Location loc;
3213 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3215 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3216 pos->SetUParameter( nXYZ.X() );
3218 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3219 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3223 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3224 pos->SetUParameter( nXYZ.X() );
3225 pos->SetVParameter( nXYZ.Y() );
3226 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3227 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3230 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3235 //================================================================================
3237 * \brief Create layers of prisms
3239 //================================================================================
3241 bool _ViscousBuilder::refine(_SolidData& data)
3243 SMESH_MesherHelper helper( *_mesh );
3244 helper.SetSubShape( data._solid );
3245 helper.SetElementsOnShape(false);
3247 Handle(Geom_Curve) curve;
3248 Handle(Geom_Surface) surface;
3249 TopoDS_Edge geomEdge;
3250 TopoDS_Face geomFace;
3251 TopLoc_Location loc;
3252 double f,l, u/*, distXYZ[4]*/;
3256 for ( unsigned i = 0; i < data._edges.size(); ++i )
3258 _LayerEdge& edge = *data._edges[i];
3260 // get accumulated length of segments
3261 vector< double > segLen( edge._pos.size() );
3263 for ( unsigned j = 1; j < edge._pos.size(); ++j )
3264 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3266 // allocate memory for new nodes if it is not yet refined
3267 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3268 if ( edge._nodes.size() == 2 )
3270 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3272 edge._nodes.back() = tgtNode;
3274 if ( !edge._sWOL.IsNull() )
3276 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3277 // restore position of the last node
3281 geomEdge = TopoDS::Edge( edge._sWOL );
3282 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3283 // double u = helper.GetNodeU( tgtNode );
3284 // p = curve->Value( u );
3288 geomFace = TopoDS::Face( edge._sWOL );
3289 surface = BRep_Tool::Surface( geomFace, loc );
3290 // gp_XY uv = helper.GetNodeUV( tgtNode );
3291 // p = surface->Value( uv.X(), uv.Y() );
3293 // p.Transform( loc );
3294 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3296 // calculate height of the first layer
3298 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3299 const double f = data._hyp->GetStretchFactor();
3300 const int N = data._hyp->GetNumberLayers();
3301 const double fPowN = pow( f, N );
3302 if ( fPowN - 1 <= numeric_limits<double>::min() )
3305 h0 = T * ( f - 1 )/( fPowN - 1 );
3307 const double zeroLen = std::numeric_limits<double>::min();
3309 // create intermediate nodes
3310 double hSum = 0, hi = h0/f;
3312 for ( unsigned iStep = 1; iStep < edge._nodes.size(); ++iStep )
3314 // compute an intermediate position
3317 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3319 int iPrevSeg = iSeg-1;
3320 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3322 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3323 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3325 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3326 if ( !edge._sWOL.IsNull() )
3328 // compute XYZ by parameters <pos>
3332 pos = curve->Value( u ).Transformed(loc);
3336 uv.SetCoord( pos.X(), pos.Y() );
3337 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3340 // create or update the node
3343 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3344 if ( !edge._sWOL.IsNull() )
3347 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3349 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3353 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3358 if ( !edge._sWOL.IsNull() )
3360 // make average pos from new and current parameters
3363 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3364 pos = curve->Value( u ).Transformed(loc);
3368 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3369 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3372 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3377 // TODO: make quadratic prisms and polyhedrons(?)
3379 helper.SetElementsOnShape(true);
3381 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3382 for ( ; exp.More(); exp.Next() )
3384 if ( _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3386 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3387 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3388 vector< vector<const SMDS_MeshNode*>* > nnVec;
3389 while ( fIt->more() )
3391 const SMDS_MeshElement* face = fIt->next();
3392 int nbNodes = face->NbCornerNodes();
3393 nnVec.resize( nbNodes );
3394 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3395 for ( int iN = 0; iN < nbNodes; ++iN )
3397 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3398 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3401 int nbZ = nnVec[0]->size();
3405 for ( int iZ = 1; iZ < nbZ; ++iZ )
3406 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3407 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3410 for ( int iZ = 1; iZ < nbZ; ++iZ )
3411 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3412 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3413 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3414 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3417 return error("Not supported type of element", data._index);
3424 //================================================================================
3426 * \brief Shrink 2D mesh on faces to let space for inflated layers
3428 //================================================================================
3430 bool _ViscousBuilder::shrink()
3432 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3433 // inflated along FACE or EDGE)
3434 map< TGeomID, _SolidData* > f2sdMap;
3435 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
3437 _SolidData& data = _sdVec[i];
3438 TopTools_MapOfShape FFMap;
3439 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3440 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3441 if ( s2s->second.ShapeType() == TopAbs_FACE )
3443 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3445 if ( FFMap.Add( (*s2s).second ))
3446 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3447 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3448 // by StdMeshers_QuadToTriaAdaptor
3449 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3451 SMESH_ProxyMesh::SubMesh* proxySub =
3452 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3453 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3454 while ( fIt->more() )
3455 proxySub->AddElement( fIt->next() );
3456 // as a result 3D algo will use elements from proxySub and not from smDS
3461 SMESH_MesherHelper helper( *_mesh );
3464 map< int, _Shrinker1D > e2shrMap;
3466 // loop on FACES to srink mesh on
3467 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3468 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3470 _SolidData& data = *f2sd->second;
3471 TNode2Edge& n2eMap = data._n2eMap;
3472 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3474 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3476 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3477 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3479 helper.SetSubShape(F);
3481 // ===========================
3482 // Prepare data for shrinking
3483 // ===========================
3485 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3486 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3487 vector < const SMDS_MeshNode* > smoothNodes;
3489 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3490 while ( nIt->more() )
3492 const SMDS_MeshNode* n = nIt->next();
3493 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3494 smoothNodes.push_back( n );
3497 // Find out face orientation
3499 const set<TGeomID> ignoreShapes;
3501 if ( !smoothNodes.empty() )
3503 vector<_Simplex> simplices;
3504 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3505 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3506 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3507 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3508 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3512 // Find _LayerEdge's inflated along F
3513 vector< _LayerEdge* > lEdges;
3515 SMESH_subMeshIteratorPtr subIt =
3516 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3517 while ( subIt->more() )
3519 SMESH_subMesh* sub = subIt->next();
3520 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3521 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3523 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3524 while ( nIt->more() )
3526 _LayerEdge* edge = n2eMap[ nIt->next() ];
3527 lEdges.push_back( edge );
3528 prepareEdgeToShrink( *edge, F, helper, smDS );
3533 // Replace source nodes by target nodes in mesh faces to shrink
3534 const SMDS_MeshNode* nodes[20];
3535 for ( unsigned i = 0; i < lEdges.size(); ++i )
3537 _LayerEdge& edge = *lEdges[i];
3538 const SMDS_MeshNode* srcNode = edge._nodes[0];
3539 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3540 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3541 while ( fIt->more() )
3543 const SMDS_MeshElement* f = fIt->next();
3544 if ( !smDS->Contains( f ))
3546 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3547 for ( int iN = 0; iN < f->NbNodes(); ++iN )
3549 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3550 nodes[iN] = ( n == srcNode ? tgtNode : n );
3552 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3556 // find out if a FACE is concave
3557 const bool isConcaveFace = isConcave( F, helper );
3559 // Create _SmoothNode's on face F
3560 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3562 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3563 for ( unsigned i = 0; i < smoothNodes.size(); ++i )
3565 const SMDS_MeshNode* n = smoothNodes[i];
3566 nodesToSmooth[ i ]._node = n;
3567 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3568 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, isConcaveFace );
3569 // fix up incorrect uv of nodes on the FACE
3570 helper.GetNodeUV( F, n, 0, &isOkUV);
3575 //if ( nodesToSmooth.empty() ) continue;
3577 // Find EDGE's to shrink
3578 set< _Shrinker1D* > eShri1D;
3580 for ( unsigned i = 0; i < lEdges.size(); ++i )
3582 _LayerEdge* edge = lEdges[i];
3583 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3585 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3586 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3587 eShri1D.insert( & srinker );
3588 srinker.AddEdge( edge, helper );
3589 // restore params of nodes on EGDE if the EDGE has been already
3590 // srinked while srinking another FACE
3591 srinker.RestoreParams();
3596 // ==================
3597 // Perform shrinking
3598 // ==================
3600 bool shrinked = true;
3601 int badNb, shriStep=0, smooStep=0;
3604 // Move boundary nodes (actually just set new UV)
3605 // -----------------------------------------------
3606 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep++ ); // debug
3608 for ( unsigned i = 0; i < lEdges.size(); ++i )
3610 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3614 // Move nodes on EDGE's
3615 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3616 for ( ; shr != eShri1D.end(); ++shr )
3617 (*shr)->Compute( /*set3D=*/false, helper );
3620 // -----------------
3621 int nbNoImpSteps = 0;
3624 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3626 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3628 int oldBadNb = badNb;
3631 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3633 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3634 /*isCentroidal=*/isConcaveFace,/*set3D=*/false );
3636 if ( badNb < oldBadNb )
3644 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3646 // No wrongly shaped faces remain; final smooth. Set node XYZ.
3647 // First, find out a needed quality of smoothing (high for quadrangles only)
3650 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
3651 if ( hasTria != hasQuad )
3653 highQuality = hasQuad;
3657 set<int> nbNodesSet;
3658 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3659 while ( fIt->more() && nbNodesSet.size() < 2 )
3660 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
3661 highQuality = ( *nbNodesSet.begin() == 4 );
3664 if ( !highQuality && isConcaveFace )
3665 fixBadFaces( F, helper ); // fix narrow faces by swaping diagonals
3666 for ( int st = highQuality ? 10 : 3; st; --st )
3668 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3669 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3670 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3671 /*isCentroidal=*/isConcaveFace,/*set3D=*/st==1 );
3674 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
3675 _SrinkShapeListener::ToClearSubMeshWithSolid( sm, data._solid );
3677 } // loop on FACES to srink mesh on
3680 // Replace source nodes by target nodes in shrinked mesh edges
3682 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3683 for ( ; e2shr != e2shrMap.end(); ++e2shr )
3684 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3689 //================================================================================
3691 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3693 //================================================================================
3695 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
3696 const TopoDS_Face& F,
3697 SMESH_MesherHelper& helper,
3698 const SMESHDS_SubMesh* faceSubMesh)
3700 const SMDS_MeshNode* srcNode = edge._nodes[0];
3701 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3705 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3707 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3708 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3709 gp_Vec2d uvDir( srcUV, tgtUV );
3710 double uvLen = uvDir.Magnitude();
3712 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3714 // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3715 vector<const SMDS_MeshElement*> faces;
3716 multimap< double, const SMDS_MeshNode* > proj2node;
3717 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3718 while ( fIt->more() )
3720 const SMDS_MeshElement* f = fIt->next();
3721 if ( faceSubMesh->Contains( f ))
3722 faces.push_back( f );
3724 for ( unsigned i = 0; i < faces.size(); ++i )
3726 const int nbNodes = faces[i]->NbCornerNodes();
3727 for ( int j = 0; j < nbNodes; ++j )
3729 const SMDS_MeshNode* n = faces[i]->GetNode(j);
3730 if ( n == srcNode ) continue;
3731 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3732 ( faces.size() > 1 || nbNodes > 3 ))
3734 gp_Pnt2d uv = helper.GetNodeUV( F, n );
3735 gp_Vec2d uvDirN( srcUV, uv );
3736 double proj = uvDirN * uvDir;
3737 proj2node.insert( make_pair( proj, n ));
3741 multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
3742 const double minProj = p2n->first;
3743 const double projThreshold = 1.1 * uvLen;
3744 if ( minProj > projThreshold )
3746 // tgtNode is located so that it does not make faces with wrong orientation
3749 edge._pos.resize(1);
3750 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
3752 // store most risky nodes in _simplices
3753 p2nEnd = proj2node.lower_bound( projThreshold );
3754 int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
3755 edge._simplices.resize( nbSimpl );
3756 for ( int i = 0; i < nbSimpl; ++i )
3758 edge._simplices[i]._nPrev = p2n->second;
3759 if ( ++p2n != p2nEnd )
3760 edge._simplices[i]._nNext = p2n->second;
3762 // set UV of source node to target node
3763 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3764 pos->SetUParameter( srcUV.X() );
3765 pos->SetVParameter( srcUV.Y() );
3767 else // _sWOL is TopAbs_EDGE
3769 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
3770 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
3771 if ( !edgeSM || edgeSM->NbElements() == 0 )
3772 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3774 const SMDS_MeshNode* n2 = 0;
3775 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3776 while ( eIt->more() && !n2 )
3778 const SMDS_MeshElement* e = eIt->next();
3779 if ( !edgeSM->Contains(e)) continue;
3780 n2 = e->GetNode( 0 );
3781 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
3784 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3786 double uSrc = helper.GetNodeU( E, srcNode, n2 );
3787 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
3788 double u2 = helper.GetNodeU( E, n2, srcNode );
3790 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
3792 // tgtNode is located so that it does not make faces with wrong orientation
3795 edge._pos.resize(1);
3796 edge._pos[0].SetCoord( U_TGT, uTgt );
3797 edge._pos[0].SetCoord( U_SRC, uSrc );
3798 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
3800 edge._simplices.resize( 1 );
3801 edge._simplices[0]._nPrev = n2;
3803 // set UV of source node to target node
3804 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3805 pos->SetUParameter( uSrc );
3809 //================================================================================
3811 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
3813 //================================================================================
3815 // Compute UV to follow during shrinking
3817 // const SMDS_MeshNode* srcNode = edge._nodes[0];
3818 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
3820 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3821 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3822 // gp_Vec2d uvDir( srcUV, tgtUV );
3823 // double uvLen = uvDir.Magnitude();
3826 // // Select shrinking step such that not to make faces with wrong orientation.
3827 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3828 // const double minStepSize = uvLen / 20;
3829 // double stepSize = uvLen;
3830 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3831 // while ( fIt->more() )
3833 // const SMDS_MeshElement* f = fIt->next();
3834 // if ( !faceSubMesh->Contains( f )) continue;
3835 // const int nbNodes = f->NbCornerNodes();
3836 // for ( int i = 0; i < nbNodes; ++i )
3838 // const SMDS_MeshNode* n = f->GetNode(i);
3839 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
3841 // gp_XY uv = helper.GetNodeUV( F, n );
3842 // gp_Vec2d uvDirN( srcUV, uv );
3843 // double proj = uvDirN * uvDir;
3844 // if ( proj < stepSize && proj > minStepSize )
3850 // const int nbSteps = ceil( uvLen / stepSize );
3851 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
3852 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
3853 // edge._pos.resize( nbSteps );
3854 // edge._pos[0] = tgtUV0;
3855 // for ( int i = 1; i < nbSteps; ++i )
3857 // double r = i / double( nbSteps );
3858 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
3863 //================================================================================
3865 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
3867 //================================================================================
3869 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper)
3871 SMESH::Controls::AspectRatio qualifier;
3872 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
3873 const double maxAspectRatio = 4.;
3875 // find bad triangles
3877 vector< const SMDS_MeshElement* > badTrias;
3878 vector< double > badAspects;
3879 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
3880 SMDS_ElemIteratorPtr fIt = sm->GetElements();
3881 while ( fIt->more() )
3883 const SMDS_MeshElement * f = fIt->next();
3884 if ( f->NbCornerNodes() != 3 ) continue;
3885 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = SMESH_TNodeXYZ( f->GetNode(iP));
3886 double aspect = qualifier.GetValue( points );
3887 if ( aspect > maxAspectRatio )
3889 badTrias.push_back( f );
3890 badAspects.push_back( aspect );
3893 if ( badTrias.empty() )
3896 // find couples of faces to swap diagonal
3898 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
3899 vector< T2Trias > triaCouples;
3901 TIDSortedElemSet involvedFaces, emptySet;
3902 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
3905 double aspRatio [3];
3908 involvedFaces.insert( badTrias[iTia] );
3909 for ( int iP = 0; iP < 3; ++iP )
3910 points(iP+1) = SMESH_TNodeXYZ( badTrias[iTia]->GetNode(iP));
3912 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
3913 int bestCouple = -1;
3914 for ( int iSide = 0; iSide < 3; ++iSide )
3916 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
3917 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
3918 trias [iSide].first = badTrias[iTia];
3919 trias [iSide].second = SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, involvedFaces,
3921 if ( ! trias[iSide].second || trias[iSide].second->NbCornerNodes() != 3 )
3924 // aspect ratio of an adjacent tria
3925 for ( int iP = 0; iP < 3; ++iP )
3926 points2(iP+1) = SMESH_TNodeXYZ( trias[iSide].second->GetNode(iP));
3927 double aspectInit = qualifier.GetValue( points2 );
3929 // arrange nodes as after diag-swaping
3930 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
3931 i3 = helper.WrapIndex( i1-1, 3 );
3933 i3 = helper.WrapIndex( i1+1, 3 );
3935 points1( 1+ iSide ) = points2( 1+ i3 );
3936 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
3938 // aspect ratio after diag-swaping
3939 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
3940 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
3943 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
3947 if ( bestCouple >= 0 )
3949 triaCouples.push_back( trias[bestCouple] );
3950 involvedFaces.insert ( trias[bestCouple].second );
3954 involvedFaces.erase( badTrias[iTia] );
3957 if ( triaCouples.empty() )
3962 SMESH_MeshEditor editor( helper.GetMesh() );
3963 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
3964 for ( size_t i = 0; i < triaCouples.size(); ++i )
3966 dumpChangeNodes( triaCouples[i].first );
3967 dumpChangeNodes( triaCouples[i].second );
3968 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
3972 // just for debug dump resulting triangles
3973 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID());
3974 for ( size_t i = 0; i < triaCouples.size(); ++i )
3976 dumpChangeNodes( triaCouples[i].first );
3977 dumpChangeNodes( triaCouples[i].second );
3981 //================================================================================
3983 * \brief Move target node to it's final position on the FACE during shrinking
3985 //================================================================================
3987 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
3988 const TopoDS_Face& F,
3989 SMESH_MesherHelper& helper )
3992 return false; // already at the target position
3994 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
3996 if ( _sWOL.ShapeType() == TopAbs_FACE )
3998 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
3999 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y());
4000 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4001 const double uvLen = tgtUV.Distance( curUV );
4003 // Select shrinking step such that not to make faces with wrong orientation.
4004 const double kSafe = 0.8;
4005 const double minStepSize = uvLen / 10;
4006 double stepSize = uvLen;
4007 for ( unsigned i = 0; i < _simplices.size(); ++i )
4009 const SMDS_MeshNode* nn[2] = { _simplices[i]._nPrev, _simplices[i]._nNext };
4010 for ( int j = 0; j < 2; ++j )
4011 if ( const SMDS_MeshNode* n = nn[j] )
4013 gp_XY uv = helper.GetNodeUV( F, n );
4014 gp_Vec2d uvDirN( curUV, uv );
4015 double proj = uvDirN * uvDir * kSafe;
4016 if ( proj < stepSize && proj > minStepSize )
4022 if ( stepSize == uvLen )
4029 newUV = curUV + uvDir.XY() * stepSize;
4032 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4033 pos->SetUParameter( newUV.X() );
4034 pos->SetVParameter( newUV.Y() );
4037 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4038 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4039 dumpMove( tgtNode );
4042 else // _sWOL is TopAbs_EDGE
4044 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4045 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4047 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4048 const double uSrc = _pos[0].Coord( U_SRC );
4049 const double lenTgt = _pos[0].Coord( LEN_TGT );
4051 double newU = _pos[0].Coord( U_TGT );
4052 if ( lenTgt < 0.99 * fabs( uSrc-u2 ))
4058 newU = 0.1 * uSrc + 0.9 * u2;
4060 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4061 pos->SetUParameter( newU );
4063 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4064 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4065 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4066 dumpMove( tgtNode );
4072 //================================================================================
4074 * \brief Perform smooth on the FACE
4075 * \retval bool - true if the node has been moved
4077 //================================================================================
4079 bool _SmoothNode::Smooth(int& badNb,
4080 Handle(Geom_Surface)& surface,
4081 SMESH_MesherHelper& helper,
4082 const double refSign,
4086 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4088 // get uv of surrounding nodes
4089 vector<gp_XY> uv( _simplices.size() );
4090 for ( size_t i = 0; i < _simplices.size(); ++i )
4091 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4093 // compute new UV for the node
4095 if ( isCentroidal && _simplices.size() > 3 )
4097 // average centers of diagonals wieghted with their reciprocal lengths
4098 if ( _simplices.size() == 4 )
4100 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4101 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4102 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4106 double sumWeight = 0;
4107 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4108 for ( int i = 0; i < nb; ++i )
4111 int iTo = i + _simplices.size() - 1;
4112 for ( int j = iFrom; j < iTo; ++j )
4114 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4115 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4117 newPos += w * ( uv[i]+uv[i2] );
4120 newPos /= 2 * sumWeight;
4126 isCentroidal = false;
4127 for ( size_t i = 0; i < _simplices.size(); ++i )
4129 newPos /= _simplices.size();
4132 // count quality metrics (orientation) of triangles around the node
4134 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4135 for ( unsigned i = 0; i < _simplices.size(); ++i )
4136 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4139 for ( unsigned i = 0; i < _simplices.size(); ++i )
4140 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4142 if ( nbOkAfter < nbOkBefore )
4144 // if ( isCentroidal )
4145 // return Smooth( badNb, surface, helper, refSign, !isCentroidal, set3D );
4146 badNb += _simplices.size() - nbOkBefore;
4150 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4151 pos->SetUParameter( newPos.X() );
4152 pos->SetVParameter( newPos.Y() );
4159 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4160 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4164 badNb += _simplices.size() - nbOkAfter;
4165 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4168 //================================================================================
4170 * \brief Delete _SolidData
4172 //================================================================================
4174 _SolidData::~_SolidData()
4176 for ( unsigned i = 0; i < _edges.size(); ++i )
4178 if ( _edges[i] && _edges[i]->_2neibors )
4179 delete _edges[i]->_2neibors;
4184 //================================================================================
4186 * \brief Add a _LayerEdge inflated along the EDGE
4188 //================================================================================
4190 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4193 if ( _nodes.empty() )
4195 _edges[0] = _edges[1] = 0;
4199 if ( e == _edges[0] || e == _edges[1] )
4201 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4202 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4203 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4204 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4207 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4209 BRep_Tool::Range( E, f,l );
4210 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4211 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4215 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4216 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4218 if ( _nodes.empty() )
4220 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4221 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4223 TopLoc_Location loc;
4224 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4225 GeomAdaptor_Curve aCurve(C, f,l);
4226 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4228 int nbExpectNodes = eSubMesh->NbNodes() - e->_nodes.size();
4229 _initU .reserve( nbExpectNodes );
4230 _normPar.reserve( nbExpectNodes );
4231 _nodes .reserve( nbExpectNodes );
4232 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4233 while ( nIt->more() )
4235 const SMDS_MeshNode* node = nIt->next();
4236 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4237 node == tgtNode0 || node == tgtNode1 )
4238 continue; // refinement nodes
4239 _nodes.push_back( node );
4240 _initU.push_back( helper.GetNodeU( E, node ));
4241 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4242 _normPar.push_back( len / totLen );
4247 // remove target node of the _LayerEdge from _nodes
4249 for ( unsigned i = 0; i < _nodes.size(); ++i )
4250 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4251 _nodes[i] = 0, nbFound++;
4252 if ( nbFound == _nodes.size() )
4257 //================================================================================
4259 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4261 //================================================================================
4263 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4265 if ( _done || _nodes.empty())
4267 const _LayerEdge* e = _edges[0];
4268 if ( !e ) e = _edges[1];
4271 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4272 ( !_edges[1] || _edges[1]->_pos.empty() ));
4274 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4276 if ( set3D || _done )
4278 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4279 GeomAdaptor_Curve aCurve(C, f,l);
4282 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4284 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4285 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4287 for ( unsigned i = 0; i < _nodes.size(); ++i )
4289 if ( !_nodes[i] ) continue;
4290 double len = totLen * _normPar[i];
4291 GCPnts_AbscissaPoint discret( aCurve, len, f );
4292 if ( !discret.IsDone() )
4293 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4294 double u = discret.Parameter();
4295 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4296 pos->SetUParameter( u );
4297 gp_Pnt p = C->Value( u );
4298 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4303 BRep_Tool::Range( E, f,l );
4305 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4307 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4309 for ( unsigned i = 0; i < _nodes.size(); ++i )
4311 if ( !_nodes[i] ) continue;
4312 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4313 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4314 pos->SetUParameter( u );
4319 //================================================================================
4321 * \brief Restore initial parameters of nodes on EDGE
4323 //================================================================================
4325 void _Shrinker1D::RestoreParams()
4328 for ( unsigned i = 0; i < _nodes.size(); ++i )
4330 if ( !_nodes[i] ) continue;
4331 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4332 pos->SetUParameter( _initU[i] );
4337 //================================================================================
4339 * \brief Replace source nodes by target nodes in shrinked mesh edges
4341 //================================================================================
4343 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4345 const SMDS_MeshNode* nodes[3];
4346 for ( int i = 0; i < 2; ++i )
4348 if ( !_edges[i] ) continue;
4350 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4351 if ( !eSubMesh ) return;
4352 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4353 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4354 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4355 while ( eIt->more() )
4357 const SMDS_MeshElement* e = eIt->next();
4358 if ( !eSubMesh->Contains( e ))
4360 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4361 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4363 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4364 nodes[iN] = ( n == srcNode ? tgtNode : n );
4366 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4371 //================================================================================
4373 * \brief Creates 2D and 1D elements on boundaries of new prisms
4375 //================================================================================
4377 bool _ViscousBuilder::addBoundaryElements()
4379 SMESH_MesherHelper helper( *_mesh );
4381 for ( unsigned i = 0; i < _sdVec.size(); ++i )
4383 _SolidData& data = _sdVec[i];
4384 TopTools_IndexedMapOfShape geomEdges;
4385 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4386 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4388 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4390 // Get _LayerEdge's based on E
4392 map< double, const SMDS_MeshNode* > u2nodes;
4393 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4396 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
4397 TNode2Edge & n2eMap = data._n2eMap;
4398 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4400 //check if 2D elements are needed on E
4401 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
4402 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
4403 ledges.push_back( n2e->second );
4405 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
4406 continue; // no layers on E
4407 ledges.push_back( n2eMap[ u2n->second ]);
4409 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
4410 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
4411 int nbSharedPyram = 0;
4412 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
4413 while ( vIt->more() )
4415 const SMDS_MeshElement* v = vIt->next();
4416 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
4418 if ( nbSharedPyram > 1 )
4419 continue; // not free border of the pyramid
4421 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
4422 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
4423 continue; // faces already created
4425 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
4426 ledges.push_back( n2eMap[ u2n->second ]);
4428 // Find out orientation and type of face to create
4430 bool reverse = false, isOnFace;
4432 map< TGeomID, TopoDS_Shape >::iterator e2f =
4433 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
4435 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
4437 F = e2f->second.Oriented( TopAbs_FORWARD );
4438 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
4439 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
4444 // find FACE with layers sharing E
4445 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
4446 while ( fIt->more() && F.IsNull() )
4448 const TopoDS_Shape* pF = fIt->next();
4449 if ( helper.IsSubShape( *pF, data._solid) &&
4450 !_ignoreShapeIds.count( e2f->first ))
4454 // Find the sub-mesh to add new faces
4455 SMESHDS_SubMesh* sm = 0;
4457 sm = getMeshDS()->MeshElements( F );
4459 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
4461 return error("error in addBoundaryElements()", data._index);
4464 const int dj1 = reverse ? 0 : 1;
4465 const int dj2 = reverse ? 1 : 0;
4466 for ( unsigned j = 1; j < ledges.size(); ++j )
4468 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
4469 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
4471 for ( unsigned z = 1; z < nn1.size(); ++z )
4472 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
4474 for ( unsigned z = 1; z < nn1.size(); ++z )
4475 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));