1 // Copyright (C) 2007-2011 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
19 // File : StdMeshers_ViscousLayers.cxx
20 // Created : Wed Dec 1 15:15:34 2010
21 // Author : Edward AGAPOV (eap)
23 #include "StdMeshers_ViscousLayers.hxx"
25 #include "SMDS_EdgePosition.hxx"
26 #include "SMDS_FaceOfNodes.hxx"
27 #include "SMDS_FacePosition.hxx"
28 #include "SMDS_MeshNode.hxx"
29 #include "SMDS_SetIterator.hxx"
30 #include "SMESHDS_Group.hxx"
31 #include "SMESHDS_Hypothesis.hxx"
32 #include "SMESH_Algo.hxx"
33 #include "SMESH_ComputeError.hxx"
34 #include "SMESH_ControlsDef.hxx"
35 #include "SMESH_Gen.hxx"
36 #include "SMESH_Group.hxx"
37 #include "SMESH_Mesh.hxx"
38 #include "SMESH_MesherHelper.hxx"
39 #include "SMESH_ProxyMesh.hxx"
40 #include "SMESH_subMesh.hxx"
41 #include "SMESH_subMeshEventListener.hxx"
43 #include "utilities.h"
45 #include <BRepAdaptor_Curve2d.hxx>
46 #include <BRep_Tool.hxx>
47 #include <Bnd_B2d.hxx>
48 #include <Bnd_B3d.hxx>
50 #include <GCPnts_AbscissaPoint.hxx>
51 #include <Geom2d_Circle.hxx>
52 #include <Geom2d_Line.hxx>
53 #include <Geom2d_TrimmedCurve.hxx>
54 #include <GeomAdaptor_Curve.hxx>
55 #include <Geom_Circle.hxx>
56 #include <Geom_Curve.hxx>
57 #include <Geom_Line.hxx>
58 #include <Geom_TrimmedCurve.hxx>
59 #include <Precision.hxx>
60 #include <Standard_ErrorHandler.hxx>
61 #include <TColStd_Array1OfReal.hxx>
63 #include <TopExp_Explorer.hxx>
64 #include <TopTools_IndexedMapOfShape.hxx>
65 #include <TopTools_MapOfShape.hxx>
67 #include <TopoDS_Edge.hxx>
68 #include <TopoDS_Face.hxx>
69 #include <TopoDS_Vertex.hxx>
83 //================================================================================
88 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
91 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
92 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
94 struct _MeshOfSolid : public SMESH_ProxyMesh,
95 public SMESH_subMeshEventListenerData
99 _MeshOfSolid( SMESH_Mesh* mesh)
100 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
102 SMESH_ProxyMesh::setMesh( *mesh );
105 // returns submesh for a geom face
106 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
108 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
109 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
111 void setNode2Node(const SMDS_MeshNode* srcNode,
112 const SMDS_MeshNode* proxyNode,
113 const SMESH_ProxyMesh::SubMesh* subMesh)
115 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
118 //--------------------------------------------------------------------------------
120 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
121 * It is used to clear an inferior dim sub-meshes modified by viscous layers
123 class _SrinkShapeListener : SMESH_subMeshEventListener
125 _SrinkShapeListener()
126 : SMESH_subMeshEventListener(/*isDeletable=*/false,
127 "StdMeshers_ViscousLayers::_SrinkShapeListener") {}
128 static SMESH_subMeshEventListener* Get() { static _SrinkShapeListener l; return &l; }
130 virtual void ProcessEvent(const int event,
132 SMESH_subMesh* solidSM,
133 SMESH_subMeshEventListenerData* data,
134 const SMESH_Hypothesis* hyp)
136 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
138 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
141 static void ToClearSubMeshWithSolid( SMESH_subMesh* sm,
142 const TopoDS_Shape& solid)
144 SMESH_subMesh* solidSM = sm->GetFather()->GetSubMesh( solid );
145 SMESH_subMeshEventListenerData* data = solidSM->GetEventListenerData( Get());
148 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sm ) ==
149 data->mySubMeshes.end())
150 data->mySubMeshes.push_back( sm );
154 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sm );
155 sm->SetEventListener( Get(), data, /*whereToListenTo=*/solidSM );
159 //--------------------------------------------------------------------------------
161 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
162 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
163 * delete the data as soon as it has been used
165 class _ViscousListener : SMESH_subMeshEventListener
168 SMESH_subMeshEventListener(/*isDeletable=*/false,
169 "StdMeshers_ViscousLayers::_ViscousListener") {}
170 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
172 virtual void ProcessEvent(const int event,
174 SMESH_subMesh* subMesh,
175 SMESH_subMeshEventListenerData* data,
176 const SMESH_Hypothesis* hyp)
178 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
180 // delete SMESH_ProxyMesh containing temporary faces
181 subMesh->DeleteEventListener( this );
184 // Finds or creates proxy mesh of the solid
185 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
186 const TopoDS_Shape& solid,
189 if ( !mesh ) return 0;
190 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
191 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
192 if ( !data && toCreate )
194 data = new _MeshOfSolid(mesh);
195 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
196 sm->SetEventListener( Get(), data, sm );
200 // Removes proxy mesh of the solid
201 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
203 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
207 //--------------------------------------------------------------------------------
209 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
210 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
211 * The class is used to check validity of face or volumes around a smoothed node;
212 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
216 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
217 _Simplex(const SMDS_MeshNode* nPrev=0, const SMDS_MeshNode* nNext=0)
218 : _nPrev(nPrev), _nNext(nNext) {}
219 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
221 const double M[3][3] =
222 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
223 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
224 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
225 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
226 + M[0][1]*M[1][2]*M[2][0]
227 + M[0][2]*M[1][0]*M[2][1]
228 - M[0][0]*M[1][2]*M[2][1]
229 - M[0][1]*M[1][0]*M[2][2]
230 - M[0][2]*M[1][1]*M[2][0]);
231 return determinant > 1e-100;
233 bool IsForward(const gp_XY& tgtUV,
234 const SMDS_MeshNode* smoothedNode,
235 const TopoDS_Face& face,
236 SMESH_MesherHelper& helper,
237 const double refSign) const
239 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
240 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
241 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
243 return d*refSign > 1e-100;
245 bool IsNeighbour(const _Simplex& other) const
247 return _nPrev == other._nNext || _nNext == other._nPrev;
250 //--------------------------------------------------------------------------------
252 * Structure used to take into account surface curvature while smoothing
257 double _k; // factor to correct node smoothed position
259 static _Curvature* New( double avgNormProj, double avgDist )
262 if ( fabs( avgNormProj / avgDist ) > 1./200 )
265 c->_r = avgDist * avgDist / avgNormProj;
266 c->_k = avgDist * avgDist / c->_r / c->_r;
267 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
271 double lenDelta(double len) const { return _k * ( _r + len ); }
274 //--------------------------------------------------------------------------------
276 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
280 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
281 const SMDS_MeshNode* _nodes[2];
282 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
284 double _wgt[2]; // weights of _nodes
285 _LayerEdge* _edges[2];
287 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
290 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
292 std::swap( _nodes[0], _nodes[1] );
293 std::swap( _wgt[0], _wgt[1] );
296 //--------------------------------------------------------------------------------
298 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
299 * and a node of the most internal layer (_nodes.back())
303 vector< const SMDS_MeshNode*> _nodes;
305 gp_XYZ _normal; // to solid surface
306 vector<gp_XYZ> _pos; // points computed during inflation
307 double _len; // length achived with the last step
308 double _cosin; // of angle (_normal ^ surface)
309 double _lenFactor; // to compute _len taking _cosin into account
311 // face or edge w/o layer along or near which _LayerEdge is inflated
313 // simplices connected to the source node (_nodes[0]);
314 // used for smoothing and quality check of _LayerEdge's based on the FACE
315 vector<_Simplex> _simplices;
316 // data for smoothing of _LayerEdge's based on the EDGE
317 _2NearEdges* _2neibors;
319 _Curvature* _curvature;
320 // TODO:: detele _Curvature, _plnNorm
322 void SetNewLength( double len, SMESH_MesherHelper& helper );
323 bool SetNewLength2d( Handle(Geom_Surface)& surface,
324 const TopoDS_Face& F,
325 SMESH_MesherHelper& helper );
326 void SetDataByNeighbors( const SMDS_MeshNode* n1,
327 const SMDS_MeshNode* n2,
328 SMESH_MesherHelper& helper);
329 void InvalidateStep( int curStep );
330 bool Smooth(int& badNb);
331 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
332 const TopoDS_Face& F,
333 SMESH_MesherHelper& helper);
334 bool FindIntersection( SMESH_ElementSearcher& searcher,
336 const double& epsilon,
337 const SMDS_MeshElement** face = 0);
338 bool SegTriaInter( const gp_Ax1& lastSegment,
339 const SMDS_MeshNode* n0,
340 const SMDS_MeshNode* n1,
341 const SMDS_MeshNode* n2,
343 const double& epsilon) const;
344 gp_Ax1 LastSegment(double& segLen) const;
345 bool IsOnEdge() const { return _2neibors; }
346 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
347 void SetCosin( double cosin );
351 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
353 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
354 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
357 //--------------------------------------------------------------------------------
359 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
361 //--------------------------------------------------------------------------------
363 * \brief Data of a SOLID
368 const StdMeshers_ViscousLayers* _hyp;
369 _MeshOfSolid* _proxyMesh;
370 set<TGeomID> _reversedFaceIds;
372 double _stepSize, _stepSizeCoeff;
373 const SMDS_MeshNode* _stepSizeNodes[2];
376 // edges of _n2eMap. We keep same data in two containers because
377 // iteration over the map is 5 time longer than over the vector
378 vector< _LayerEdge* > _edges;
380 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
381 // layers and a FACE w/o layers
382 // value: the shape (FACE or EDGE) to shrink mesh on.
383 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
384 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
386 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
387 set< TGeomID > _noShrinkFaces;
389 // <EDGE to smooth on> to <it's curve>
390 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
392 // end indices in _edges of _LayerEdge on one shape to smooth
393 vector< int > _endEdgeToSmooth;
395 double _epsilon; // precision for SegTriaInter()
397 int _index; // for debug
399 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
400 const StdMeshers_ViscousLayers* h=0,
401 _MeshOfSolid* m=0) :_solid(s), _hyp(h), _proxyMesh(m) {}
404 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
407 Handle(Geom_Surface)& surface,
408 const TopoDS_Face& F,
409 SMESH_MesherHelper& helper);
411 //--------------------------------------------------------------------------------
413 * \brief Data of node on a shrinked FACE
417 const SMDS_MeshNode* _node;
418 //vector<const SMDS_MeshNode*> _nodesAround;
419 vector<_Simplex> _simplices; // for quality check
421 bool Smooth(int& badNb,
422 Handle(Geom_Surface)& surface,
423 SMESH_MesherHelper& helper,
424 const double refSign,
428 //--------------------------------------------------------------------------------
430 * \brief Builder of viscous layers
432 class _ViscousBuilder
437 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
438 const TopoDS_Shape& shape);
440 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
441 void RestoreListeners();
443 // computes SMESH_ProxyMesh::SubMesh::_n2n;
444 bool MakeN2NMap( _MeshOfSolid* pm );
448 bool findSolidsWithLayers();
449 bool findFacesWithLayers();
450 bool makeLayer(_SolidData& data);
451 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
452 SMESH_MesherHelper& helper, _SolidData& data);
453 bool findNeiborsOnEdge(const _LayerEdge* edge,
454 const SMDS_MeshNode*& n1,
455 const SMDS_MeshNode*& n2,
457 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
458 const set<TGeomID>& ingnoreShapes,
459 const _SolidData* dataToCheckOri = 0,
460 const bool toSort = false);
461 bool sortEdges( _SolidData& data,
462 vector< vector<_LayerEdge*> >& edgesByGeom);
463 void limitStepSize( _SolidData& data,
464 const SMDS_MeshElement* face,
466 void limitStepSize( _SolidData& data, const double minSize);
467 bool inflate(_SolidData& data);
468 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
469 bool smoothAnalyticEdge( _SolidData& data,
472 Handle(Geom_Surface)& surface,
473 const TopoDS_Face& F,
474 SMESH_MesherHelper& helper);
475 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
476 bool refine(_SolidData& data);
478 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
479 SMESH_MesherHelper& helper,
480 const SMESHDS_SubMesh* faceSubMesh );
481 void fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper);
482 bool addBoundaryElements();
484 bool error( const string& text, int solidID=-1 );
485 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
488 void makeGroupOfLE();
491 SMESH_ComputeErrorPtr _error;
493 vector< _SolidData > _sdVec;
494 set<TGeomID> _ignoreShapeIds;
497 //--------------------------------------------------------------------------------
499 * \brief Shrinker of nodes on the EDGE
503 vector<double> _initU;
504 vector<double> _normPar;
505 vector<const SMDS_MeshNode*> _nodes;
506 const _LayerEdge* _edges[2];
509 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
510 void Compute(bool set3D, SMESH_MesherHelper& helper);
511 void RestoreParams();
512 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
514 //--------------------------------------------------------------------------------
516 * \brief Class of temporary mesh face.
517 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
518 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
520 struct TmpMeshFace : public SMDS_MeshElement
522 vector<const SMDS_MeshNode* > _nn;
523 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
524 SMDS_MeshElement(id), _nn(nodes) {}
525 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
526 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
527 virtual vtkIdType GetVtkType() const { return -1; }
528 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
529 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const
530 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
532 //--------------------------------------------------------------------------------
534 * \brief Class of temporary mesh face storing _LayerEdge it's based on
536 struct TmpMeshFaceOnEdge : public TmpMeshFace
538 _LayerEdge *_le1, *_le2;
539 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
540 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
542 _nn[0]=_le1->_nodes[0];
543 _nn[1]=_le1->_nodes.back();
544 _nn[2]=_le2->_nodes.back();
545 _nn[3]=_le2->_nodes[0];
548 } // namespace VISCOUS
550 //================================================================================
551 // StdMeshers_ViscousLayers hypothesis
553 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
554 :SMESH_Hypothesis(hypId, studyId, gen),
555 _nbLayers(1), _thickness(1), _stretchFactor(1)
557 _name = StdMeshers_ViscousLayers::GetHypType();
558 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
559 } // --------------------------------------------------------------------------------
560 void StdMeshers_ViscousLayers::SetIgnoreFaces(const std::vector<int>& faceIds)
562 if ( faceIds != _ignoreFaceIds )
563 _ignoreFaceIds = faceIds, NotifySubMeshesHypothesisModification();
564 } // --------------------------------------------------------------------------------
565 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
567 if ( thickness != _thickness )
568 _thickness = thickness, NotifySubMeshesHypothesisModification();
569 } // --------------------------------------------------------------------------------
570 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
572 if ( _nbLayers != nb )
573 _nbLayers = nb, NotifySubMeshesHypothesisModification();
574 } // --------------------------------------------------------------------------------
575 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
577 if ( _stretchFactor != factor )
578 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
579 } // --------------------------------------------------------------------------------
581 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
582 const TopoDS_Shape& theShape,
583 const bool toMakeN2NMap) const
585 using namespace VISCOUS;
586 _ViscousBuilder bulder;
587 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
588 if ( err && !err->IsOK() )
589 return SMESH_ProxyMesh::Ptr();
591 vector<SMESH_ProxyMesh::Ptr> components;
592 TopExp_Explorer exp( theShape, TopAbs_SOLID );
593 for ( ; exp.More(); exp.Next() )
595 if ( _MeshOfSolid* pm =
596 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
598 if ( toMakeN2NMap && !pm->_n2nMapComputed )
599 if ( !bulder.MakeN2NMap( pm ))
600 return SMESH_ProxyMesh::Ptr();
601 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
602 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
604 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
606 switch ( components.size() )
610 case 1: return components[0];
612 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
614 return SMESH_ProxyMesh::Ptr();
615 } // --------------------------------------------------------------------------------
616 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
618 save << " " << _nbLayers
620 << " " << _stretchFactor
621 << " " << _ignoreFaceIds.size();
622 for ( unsigned i = 0; i < _ignoreFaceIds.size(); ++i )
623 save << " " << _ignoreFaceIds[i];
625 } // --------------------------------------------------------------------------------
626 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
629 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
630 while ( _ignoreFaceIds.size() < nbFaces && load >> faceID )
631 _ignoreFaceIds.push_back( faceID );
633 } // --------------------------------------------------------------------------------
634 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
635 const TopoDS_Shape& theShape)
640 // END StdMeshers_ViscousLayers hypothesis
641 //================================================================================
645 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
649 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
650 gp_Pnt p = BRep_Tool::Pnt( fromV );
651 double distF = p.SquareDistance( c->Value( f ));
652 double distL = p.SquareDistance( c->Value( l ));
653 c->D1(( distF < distL ? f : l), p, dir );
654 if ( distL < distF ) dir.Reverse();
657 //--------------------------------------------------------------------------------
658 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
659 SMESH_MesherHelper& helper)
662 double f,l; gp_Pnt p;
663 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
664 double u = helper.GetNodeU( E, atNode );
668 //--------------------------------------------------------------------------------
669 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
670 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
672 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
673 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
674 gp_Pnt p; gp_Vec du, dv, norm;
675 surface->D1( uv.X(),uv.Y(), p, du,dv );
679 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
680 double u = helper.GetNodeU( fromE, node, 0, &ok );
682 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
683 if ( o == TopAbs_REVERSED )
686 gp_Vec dir = norm ^ du;
688 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
689 helper.IsClosedEdge( fromE ))
691 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
692 else c->D1( f, p, dv );
693 if ( o == TopAbs_REVERSED )
695 gp_Vec dir2 = norm ^ dv;
696 dir = dir.Normalized() + dir2.Normalized();
700 //--------------------------------------------------------------------------------
701 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
702 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
703 bool& ok, double* cosin=0)
705 double f,l; TopLoc_Location loc;
706 vector< TopoDS_Edge > edges; // sharing a vertex
707 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
710 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
711 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
712 edges.push_back( *e );
715 if ( !( ok = ( edges.size() > 0 ))) return dir;
716 // get average dir of edges going fromV
718 for ( unsigned i = 0; i < edges.size(); ++i )
720 edgeDir = getEdgeDir( edges[i], fromV );
721 double size2 = edgeDir.SquareMagnitude();
722 if ( size2 > numeric_limits<double>::min() )
723 edgeDir /= sqrt( size2 );
726 dir += edgeDir.XYZ();
728 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
729 if ( edges.size() == 1 || dir.SquareModulus() < 1e-10)
731 else if ( dir * fromEdgeDir < 0 )
735 //dir /= edges.size();
737 double angle = edgeDir.Angle( dir );
738 *cosin = cos( angle );
743 //================================================================================
745 * \brief Returns true if a FACE is bound by a concave EDGE
747 //================================================================================
749 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
753 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
754 for ( ; eExp.More(); eExp.Next() )
756 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
757 if ( BRep_Tool::Degenerated( E )) continue;
758 // check if 2D curve is concave
759 BRepAdaptor_Curve2d curve( E, F );
760 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
761 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
762 curve.Intervals( intervals, GeomAbs_C2 );
763 bool isConvex = true;
764 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
766 double u1 = intervals( i );
767 double u2 = intervals( i+1 );
768 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
769 double cross = drv2 ^ drv1;
770 if ( E.Orientation() == TopAbs_REVERSED )
772 isConvex = ( cross < 1e-9 );
774 // check if concavity is strong enough to care about it
775 //const double maxAngle = 5 * Standard_PI180;
778 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
780 // map< double, const SMDS_MeshNode* > u2nodes;
781 // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
782 // /*ignoreMedium=*/true, u2nodes))
784 // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
785 // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
786 // double uPrev = u2n->first;
787 // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
789 // gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
790 // gp_Vec2d segmentDir( uvPrev, uv );
791 // curve.D1( uPrev, p, drv1 );
793 // if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
798 // uPrev = u2n->first;
804 //--------------------------------------------------------------------------------
805 // DEBUG. Dump intermediate node positions into a python script
810 const char* fname = "/tmp/viscous.py";
811 cout << "execfile('"<<fname<<"')"<<endl;
812 py = new ofstream(fname);
813 *py << "from smesh import *" << endl
814 << "meshSO = GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
815 << "mesh = Mesh( meshSO.GetObject() )"<<endl;
819 *py << "mesh.MakeGroup('Viscous Prisms',VOLUME,FT_ElemGeomType,'=',Geom_PENTA)"<<endl;
822 ~PyDump() { Finish(); }
824 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
825 #define dumpMove(n) { _dumpMove(n, __LINE__);}
826 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
827 void _dumpFunction(const string& fun, int ln)
828 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
829 void _dumpMove(const SMDS_MeshNode* n, int ln)
830 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
831 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
832 void _dumpCmd(const string& txt, int ln)
833 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
834 void dumpFunctionEnd()
835 { if (py) *py<< " return"<< endl; }
836 void dumpChangeNodes( const SMDS_MeshElement* f )
837 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
838 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
839 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
841 struct PyDump { void Finish() {} };
842 #define dumpFunction(f) f
845 #define dumpFunctionEnd()
846 #define dumpChangeNodes(f)
850 using namespace VISCOUS;
852 //================================================================================
854 * \brief Constructor of _ViscousBuilder
856 //================================================================================
858 _ViscousBuilder::_ViscousBuilder()
860 _error = SMESH_ComputeError::New(COMPERR_OK);
864 //================================================================================
866 * \brief Stores error description and returns false
868 //================================================================================
870 bool _ViscousBuilder::error(const string& text, int solidId )
872 _error->myName = COMPERR_ALGO_FAILED;
873 _error->myComment = string("Viscous layers builder: ") + text;
876 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
877 if ( !sm && !_sdVec.empty() )
878 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
879 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
881 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
882 if ( smError && smError->myAlgo )
883 _error->myAlgo = smError->myAlgo;
887 makeGroupOfLE(); // debug
892 //================================================================================
894 * \brief At study restoration, restore event listeners used to clear an inferior
895 * dim sub-mesh modified by viscous layers
897 //================================================================================
899 void _ViscousBuilder::RestoreListeners()
904 //================================================================================
906 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
908 //================================================================================
910 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
912 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
913 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
914 for ( ; fExp.More(); fExp.Next() )
916 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
917 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
919 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
921 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
924 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
925 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
927 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
928 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
929 while( prxIt->more() )
931 const SMDS_MeshElement* fSrc = srcIt->next();
932 const SMDS_MeshElement* fPrx = prxIt->next();
933 if ( fSrc->NbNodes() != fPrx->NbNodes())
934 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
935 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
936 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
939 pm->_n2nMapComputed = true;
943 //================================================================================
945 * \brief Does its job
947 //================================================================================
949 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
950 const TopoDS_Shape& theShape)
952 // TODO: set priority of solids during Gen::Compute()
956 // check if proxy mesh already computed
957 TopExp_Explorer exp( theShape, TopAbs_SOLID );
959 return error("No SOLID's in theShape"), _error;
961 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
962 return SMESH_ComputeErrorPtr(); // everything already computed
966 // TODO: ignore already computed SOLIDs
967 if ( !findSolidsWithLayers())
970 if ( !findFacesWithLayers() )
973 for ( unsigned i = 0; i < _sdVec.size(); ++i )
975 if ( ! makeLayer(_sdVec[i]) )
978 if ( ! inflate(_sdVec[i]) )
981 if ( ! refine(_sdVec[i]) )
987 addBoundaryElements();
989 makeGroupOfLE(); // debug
995 //================================================================================
997 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
999 //================================================================================
1001 bool _ViscousBuilder::findSolidsWithLayers()
1004 TopTools_IndexedMapOfShape allSolids;
1005 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1006 _sdVec.reserve( allSolids.Extent());
1008 SMESH_Gen* gen = _mesh->GetGen();
1009 for ( int i = 1; i <= allSolids.Extent(); ++i )
1011 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1012 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1013 if ( !algo ) continue;
1014 // TODO: check if algo is hidden
1015 const list <const SMESHDS_Hypothesis *> & allHyps =
1016 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1017 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1018 const StdMeshers_ViscousLayers* viscHyp = 0;
1019 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1020 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1023 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1026 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, proxyMesh ));
1027 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1030 if ( _sdVec.empty() )
1032 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1037 //================================================================================
1041 //================================================================================
1043 bool _ViscousBuilder::findFacesWithLayers()
1045 // collect all faces to ignore defined by hyp
1046 vector<TopoDS_Shape> ignoreFaces;
1047 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1049 vector<TGeomID> ids = _sdVec[i]._hyp->GetIgnoreFaces();
1050 for ( unsigned i = 0; i < ids.size(); ++i )
1052 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
1053 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1055 _ignoreShapeIds.insert( ids[i] );
1056 ignoreFaces.push_back( s );
1061 // ignore internal faces
1062 SMESH_MesherHelper helper( *_mesh );
1063 TopExp_Explorer exp;
1064 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1066 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1067 for ( ; exp.More(); exp.Next() )
1069 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1070 if ( helper.NbAncestors( exp.Current(), *_mesh, TopAbs_SOLID ) > 1 )
1072 _ignoreShapeIds.insert( faceInd );
1073 ignoreFaces.push_back( exp.Current() );
1074 if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face( exp.Current() ), getMeshDS()))
1075 _sdVec[i]._reversedFaceIds.insert( faceInd );
1080 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1081 TopTools_IndexedMapOfShape shapes;
1082 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1085 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1086 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1088 const TopoDS_Shape& edge = shapes(iE);
1089 // find 2 faces sharing an edge
1091 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1092 while ( fIt->more())
1094 const TopoDS_Shape* f = fIt->next();
1095 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1096 FF[ int( !FF[0].IsNull()) ] = *f;
1098 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1099 // check presence of layers on them
1101 for ( int j = 0; j < 2; ++j )
1102 ignore[j] = _ignoreShapeIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1103 if ( ignore[0] == ignore[1] ) continue; // nothing interesting
1104 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1106 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1107 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1110 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1111 // the algo of the SOLID sharing the FACE does not support it
1112 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1113 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1115 TopTools_MapOfShape noShrinkVertices;
1116 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1117 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1119 const TopoDS_Shape& fWOL = e2f->second;
1120 TGeomID edgeID = e2f->first;
1121 bool notShrinkFace = false;
1122 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1123 while ( soIt->more())
1125 const TopoDS_Shape* solid = soIt->next();
1126 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1127 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1128 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1129 notShrinkFace = true;
1130 for ( unsigned j = 0; j < _sdVec.size(); ++j )
1132 if ( _sdVec[j]._solid.IsSame( *solid ) )
1133 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1134 notShrinkFace = false;
1137 if ( notShrinkFace )
1139 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1140 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1141 noShrinkVertices.Add( vExp.Current() );
1144 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1145 // to the found not shrinked fWOL's
1146 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1147 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1149 TGeomID edgeID = e2f->first;
1150 TopoDS_Vertex VV[2];
1151 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1152 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1154 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1155 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1164 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1166 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1169 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1170 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1172 const TopoDS_Shape& vertex = shapes(iV);
1173 // find faces WOL sharing the vertex
1174 vector< TopoDS_Shape > facesWOL;
1175 int totalNbFaces = 0;
1176 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1177 while ( fIt->more())
1179 const TopoDS_Shape* f = fIt->next();
1180 const int fID = getMeshDS()->ShapeToIndex( *f );
1181 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1184 if ( _ignoreShapeIds.count ( fID ) && ! _sdVec[i]._noShrinkFaces.count( fID ))
1185 facesWOL.push_back( *f );
1188 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1189 continue; // no layers at this vertex or no WOL
1190 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1191 switch ( facesWOL.size() )
1195 helper.SetSubShape( facesWOL[0] );
1196 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1198 TopoDS_Shape seamEdge;
1199 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1200 while ( eIt->more() && seamEdge.IsNull() )
1202 const TopoDS_Shape* e = eIt->next();
1203 if ( helper.IsRealSeam( *e ) )
1206 if ( !seamEdge.IsNull() )
1208 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1212 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1217 // find an edge shared by 2 faces
1218 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1219 while ( eIt->more())
1221 const TopoDS_Shape* e = eIt->next();
1222 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1223 helper.IsSubShape( *e, facesWOL[1]))
1225 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1231 return error("Not yet supported case", _sdVec[i]._index);
1239 //================================================================================
1241 * \brief Create the inner surface of the viscous layer and prepare data for infation
1243 //================================================================================
1245 bool _ViscousBuilder::makeLayer(_SolidData& data)
1247 // get all sub-shapes to make layers on
1248 set<TGeomID> subIds, faceIds;
1249 subIds = data._noShrinkFaces;
1250 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1251 for ( ; exp.More(); exp.Next() )
1252 if ( ! _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1254 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1255 faceIds.insert( fSubM->GetId() );
1256 SMESH_subMeshIteratorPtr subIt =
1257 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1258 while ( subIt->more() )
1259 subIds.insert( subIt->next()->GetId() );
1262 // make a map to find new nodes on sub-shapes shared with other SOLID
1263 map< TGeomID, TNode2Edge* > s2neMap;
1264 map< TGeomID, TNode2Edge* >::iterator s2ne;
1265 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1266 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1268 TGeomID shapeInd = s2s->first;
1269 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1271 if ( _sdVec[i]._index == data._index ) continue;
1272 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1273 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1274 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1276 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1282 // Create temporary faces and _LayerEdge's
1284 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1286 data._stepSize = Precision::Infinite();
1287 data._stepSizeNodes[0] = 0;
1289 SMESH_MesherHelper helper( *_mesh );
1290 helper.SetSubShape( data._solid );
1291 helper.SetElementsOnShape(true);
1293 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1294 TNode2Edge::iterator n2e2;
1296 // collect _LayerEdge's of shapes they are based on
1297 const int nbShapes = getMeshDS()->MaxShapeIndex();
1298 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1300 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1302 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1303 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1305 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1306 SMESH_ProxyMesh::SubMesh* proxySub =
1307 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1309 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1310 while ( eIt->more() )
1312 const SMDS_MeshElement* face = eIt->next();
1313 newNodes.resize( face->NbCornerNodes() );
1314 double faceMaxCosin = -1;
1315 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1317 const SMDS_MeshNode* n = face->GetNode(i);
1318 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1319 if ( !(*n2e).second )
1322 _LayerEdge* edge = new _LayerEdge();
1324 edge->_nodes.push_back( n );
1325 const int shapeID = n->getshapeId();
1326 edgesByGeom[ shapeID ].push_back( edge );
1328 // set edge data or find already refined _LayerEdge and get data from it
1329 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1330 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1331 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1333 _LayerEdge* foundEdge = (*n2e2).second;
1334 edge->Copy( *foundEdge, helper );
1335 // location of the last node is modified but we can restore
1336 // it by node position on _sWOL stored by the node
1337 const_cast< SMDS_MeshNode* >
1338 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1342 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1343 if ( !setEdgeData( *edge, subIds, helper, data ))
1346 dumpMove(edge->_nodes.back());
1347 if ( edge->_cosin > 0.01 )
1349 if ( edge->_cosin > faceMaxCosin )
1350 faceMaxCosin = edge->_cosin;
1353 newNodes[ i ] = n2e->second->_nodes.back();
1355 // create a temporary face
1356 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1357 proxySub->AddElement( newFace );
1359 // compute inflation step size by min size of element on a convex surface
1360 if ( faceMaxCosin > 0.1 )
1361 limitStepSize( data, face, faceMaxCosin );
1362 } // loop on 2D elements on a FACE
1363 } // loop on FACEs of a SOLID
1365 data._epsilon = 1e-7;
1366 if ( data._stepSize < 1. )
1367 data._epsilon *= data._stepSize;
1369 // Put _LayerEdge's into a vector
1371 if ( !sortEdges( data, edgesByGeom ))
1374 // Set target nodes into _Simplex and _2NearEdges
1375 TNode2Edge::iterator n2e;
1376 for ( unsigned i = 0; i < data._edges.size(); ++i )
1378 if ( data._edges[i]->IsOnEdge())
1379 for ( int j = 0; j < 2; ++j )
1381 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1382 break; // _LayerEdge is shared by two _SolidData's
1383 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1384 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1385 return error("_LayerEdge not found by src node", data._index);
1386 n = (*n2e).second->_nodes.back();
1387 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1390 for ( unsigned j = 0; j < data._edges[i]->_simplices.size(); ++j )
1392 _Simplex& s = data._edges[i]->_simplices[j];
1393 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1394 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1402 //================================================================================
1404 * \brief Compute inflation step size by min size of element on a convex surface
1406 //================================================================================
1408 void _ViscousBuilder::limitStepSize( _SolidData& data,
1409 const SMDS_MeshElement* face,
1413 double minSize = 10 * data._stepSize;
1414 const int nbNodes = face->NbCornerNodes();
1415 for ( int i = 0; i < nbNodes; ++i )
1417 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1418 const SMDS_MeshNode* curN = face->GetNode( i );
1419 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1420 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1422 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1423 if ( dist < minSize )
1424 minSize = dist, iN = i;
1427 double newStep = 0.8 * minSize / cosin;
1428 if ( newStep < data._stepSize )
1430 data._stepSize = newStep;
1431 data._stepSizeCoeff = 0.8 / cosin;
1432 data._stepSizeNodes[0] = face->GetNode( iN );
1433 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1437 //================================================================================
1439 * \brief Compute inflation step size by min size of element on a convex surface
1441 //================================================================================
1443 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1445 if ( minSize < data._stepSize )
1447 data._stepSize = minSize;
1448 if ( data._stepSizeNodes[0] )
1451 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1452 data._stepSizeCoeff = data._stepSize / dist;
1457 //================================================================================
1459 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1461 //================================================================================
1463 bool _ViscousBuilder::sortEdges( _SolidData& data,
1464 vector< vector<_LayerEdge*> >& edgesByGeom)
1466 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1467 // boundry inclined at a sharp angle to the shape
1469 list< TGeomID > shapesToSmooth;
1471 SMESH_MesherHelper helper( *_mesh );
1474 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1476 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1477 if ( eS.empty() ) continue;
1478 TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1479 bool needSmooth = false;
1480 switch ( S.ShapeType() )
1484 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1485 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1487 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1488 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1489 if ( eV.empty() ) continue;
1490 double cosin = eV[0]->_cosin;
1492 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1496 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1497 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1499 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1500 eV[0]->_nodes[0], helper, ok);
1501 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1502 double angle = dir1.Angle( dir2 );
1503 cosin = cos( angle );
1505 needSmooth = ( cosin > 0.1 );
1511 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1513 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1514 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1515 if ( eE.empty() ) continue;
1516 if ( eE[0]->_sWOL.IsNull() )
1518 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1519 needSmooth = ( eE[i]->_cosin > 0.1 );
1523 const TopoDS_Face& F1 = TopoDS::Face( S );
1524 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1525 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1526 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1528 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1529 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1530 double angle = dir1.Angle( dir2 );
1531 double cosin = cos( angle );
1532 needSmooth = ( cosin > 0.1 );
1544 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1545 else shapesToSmooth.push_back ( iS );
1548 } // loop on edgesByGeom
1550 data._edges.reserve( data._n2eMap.size() );
1551 data._endEdgeToSmooth.clear();
1553 // first we put _LayerEdge's on shapes to smooth
1554 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1555 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1557 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1558 if ( eVec.empty() ) continue;
1559 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1560 data._endEdgeToSmooth.push_back( data._edges.size() );
1564 // then the rest _LayerEdge's
1565 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1567 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1568 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1575 //================================================================================
1577 * \brief Set data of _LayerEdge needed for smoothing
1578 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1580 //================================================================================
1582 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1583 const set<TGeomID>& subIds,
1584 SMESH_MesherHelper& helper,
1587 SMESH_MeshEditor editor(_mesh);
1589 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1590 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1594 edge._curvature = 0;
1596 // --------------------------
1597 // Compute _normal and _cosin
1598 // --------------------------
1601 edge._normal.SetCoord(0,0,0);
1603 int totalNbFaces = 0;
1605 gp_Vec du, dv, geomNorm;
1608 TGeomID shapeInd = node->getshapeId();
1609 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1610 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1611 TopoDS_Shape vertEdge;
1613 if ( onShrinkShape ) // one of faces the node is on has no layers
1615 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1616 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1618 // inflate from VERTEX along EDGE
1619 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1621 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1623 // inflate from VERTEX along FACE
1624 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1625 node, helper, normOK, &edge._cosin);
1629 // inflate from EDGE along FACE
1630 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1631 node, helper, normOK);
1634 else // layers are on all faces of SOLID the node is on
1636 // find indices of geom faces the node lies on
1637 set<TGeomID> faceIds;
1638 if ( posType == SMDS_TOP_FACE )
1640 faceIds.insert( node->getshapeId() );
1644 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1645 while ( fIt->more() )
1646 faceIds.insert( editor.FindShape(fIt->next()));
1649 set<TGeomID>::iterator id = faceIds.begin();
1651 for ( ; id != faceIds.end(); ++id )
1653 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1654 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1657 //nbLayerFaces += subIds.count( *id );
1658 F = TopoDS::Face( s );
1660 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1661 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1662 surface->D1( uv.X(),uv.Y(), p, du,dv );
1664 double size2 = geomNorm.SquareMagnitude();
1665 if ( size2 > numeric_limits<double>::min() )
1666 geomNorm /= sqrt( size2 );
1669 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1671 edge._normal += geomNorm.XYZ();
1673 if ( totalNbFaces == 0 )
1674 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1676 edge._normal /= totalNbFaces;
1681 edge._cosin = 0; break;
1683 case SMDS_TOP_EDGE: {
1684 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1685 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1686 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1687 edge._cosin = cos( angle );
1688 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1691 case SMDS_TOP_VERTEX: {
1692 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1693 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK);
1694 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1695 edge._cosin = cos( angle );
1696 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1700 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1704 double normSize = edge._normal.SquareModulus();
1705 if ( normSize < numeric_limits<double>::min() )
1706 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1708 edge._normal /= sqrt( normSize );
1710 // TODO: if ( !normOK ) then get normal by mesh faces
1712 // Set the rest data
1713 // --------------------
1714 if ( onShrinkShape )
1716 edge._sWOL = (*s2s).second;
1718 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1719 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1720 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1722 // set initial position which is parameters on _sWOL in this case
1723 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1725 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1726 edge._pos.push_back( gp_XYZ( u, 0, 0));
1727 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1731 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1732 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1733 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1738 edge._pos.push_back( SMESH_TNodeXYZ( node ));
1740 if ( posType == SMDS_TOP_FACE )
1742 getSimplices( node, edge._simplices, _ignoreShapeIds, &data );
1743 double avgNormProj = 0, avgLen = 0;
1744 for ( unsigned i = 0; i < edge._simplices.size(); ++i )
1746 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
1747 avgNormProj += edge._normal * vec;
1748 avgLen += vec.Modulus();
1750 avgNormProj /= edge._simplices.size();
1751 avgLen /= edge._simplices.size();
1752 edge._curvature = _Curvature::New( avgNormProj, avgLen );
1756 // Set neighbour nodes for a _LayerEdge based on EDGE
1758 if ( posType == SMDS_TOP_EDGE /*||
1759 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1761 edge._2neibors = new _2NearEdges;
1762 // target node instead of source ones will be set later
1763 if ( ! findNeiborsOnEdge( &edge,
1764 edge._2neibors->_nodes[0],
1765 edge._2neibors->_nodes[1],
1768 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1769 edge._2neibors->_nodes[1],
1773 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1778 //================================================================================
1780 * \brief Find 2 neigbor nodes of a node on EDGE
1782 //================================================================================
1784 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
1785 const SMDS_MeshNode*& n1,
1786 const SMDS_MeshNode*& n2,
1789 const SMDS_MeshNode* node = edge->_nodes[0];
1790 const int shapeInd = node->getshapeId();
1791 SMESHDS_SubMesh* edgeSM = 0;
1792 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
1795 edgeSM = getMeshDS()->MeshElements( shapeInd );
1796 if ( !edgeSM || edgeSM->NbElements() == 0 )
1797 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
1801 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
1802 while ( eIt->more() && !n2 )
1804 const SMDS_MeshElement* e = eIt->next();
1805 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
1806 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
1809 if (!edgeSM->Contains(e)) continue;
1813 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
1814 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
1816 ( iN++ ? n2 : n1 ) = nNeibor;
1819 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
1823 //================================================================================
1825 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
1827 //================================================================================
1829 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
1830 const SMDS_MeshNode* n2,
1831 SMESH_MesherHelper& helper)
1833 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1836 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
1837 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
1838 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
1842 double sumLen = vec1.Modulus() + vec2.Modulus();
1843 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
1844 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
1845 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
1846 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
1847 if ( _curvature ) delete _curvature;
1848 _curvature = _Curvature::New( avgNormProj, avgLen );
1850 // if ( _curvature )
1851 // cout << _nodes[0]->GetID()
1852 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
1853 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
1854 // << _curvature->lenDelta(0) << endl;
1859 if ( _sWOL.IsNull() )
1861 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
1862 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
1863 gp_XYZ plnNorm = dirE ^ _normal;
1864 double proj0 = plnNorm * vec1;
1865 double proj1 = plnNorm * vec2;
1866 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
1868 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
1869 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
1874 //================================================================================
1876 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
1877 * this and other _LayerEdge's are inflated along a FACE or an EDGE
1879 //================================================================================
1881 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
1883 _nodes = other._nodes;
1884 _normal = other._normal;
1886 _lenFactor = other._lenFactor;
1887 _cosin = other._cosin;
1888 _sWOL = other._sWOL;
1889 _2neibors = other._2neibors;
1890 _curvature = 0; std::swap( _curvature, other._curvature );
1891 _2neibors = 0; std::swap( _2neibors, other._2neibors );
1893 if ( _sWOL.ShapeType() == TopAbs_EDGE )
1895 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
1896 _pos.push_back( gp_XYZ( u, 0, 0));
1900 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
1901 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1905 //================================================================================
1907 * \brief Set _cosin and _lenFactor
1909 //================================================================================
1911 void _LayerEdge::SetCosin( double cosin )
1914 _lenFactor = ( _cosin > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
1917 //================================================================================
1919 * \brief Fills a vector<_Simplex >
1921 //================================================================================
1923 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
1924 vector<_Simplex>& simplices,
1925 const set<TGeomID>& ingnoreShapes,
1926 const _SolidData* dataToCheckOri,
1929 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1930 while ( fIt->more() )
1932 const SMDS_MeshElement* f = fIt->next();
1933 const TGeomID shapeInd = f->getshapeId();
1934 if ( ingnoreShapes.count( shapeInd )) continue;
1935 const int nbNodes = f->NbCornerNodes();
1936 int srcInd = f->GetNodeIndex( node );
1937 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
1938 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
1939 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
1940 std::swap( nPrev, nNext );
1941 simplices.push_back( _Simplex( nPrev, nNext ));
1946 vector<_Simplex> sortedSimplices( simplices.size() );
1947 sortedSimplices[0] = simplices[0];
1949 for ( size_t i = 1; i < simplices.size(); ++i )
1951 for ( size_t j = 1; j < simplices.size(); ++j )
1952 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
1954 sortedSimplices[i] = simplices[j];
1959 if ( nbFound == simplices.size() - 1 )
1960 simplices.swap( sortedSimplices );
1964 //================================================================================
1966 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
1968 //================================================================================
1970 void _ViscousBuilder::makeGroupOfLE()
1973 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
1975 if ( _sdVec[i]._edges.empty() ) continue;
1976 // string name = SMESH_Comment("_LayerEdge's_") << i;
1978 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
1979 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
1980 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
1982 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
1983 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1985 _LayerEdge* le = _sdVec[i]._edges[j];
1986 for ( unsigned iN = 1; iN < le->_nodes.size(); ++iN )
1987 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
1988 << ", " << le->_nodes[iN]->GetID() <<"])");
1989 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
1993 dumpFunction( SMESH_Comment("makeNormals") << i );
1994 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1996 _LayerEdge& edge = *_sdVec[i]._edges[j];
1997 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
1998 nXYZ += edge._normal * _sdVec[i]._stepSize;
1999 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2000 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2004 // name = SMESH_Comment("tmp_faces ") << i;
2005 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2006 // gDS = (SMESHDS_Group*)g->GetGroupDS();
2007 // SMESH_MeshEditor editor( _mesh );
2008 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2009 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2010 for ( ; fExp.More(); fExp.Next() )
2012 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2014 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2015 while ( fIt->more())
2017 const SMDS_MeshElement* e = fIt->next();
2018 SMESH_Comment cmd("mesh.AddFace([");
2019 for ( int j=0; j < e->NbCornerNodes(); ++j )
2020 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2022 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2023 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2032 //================================================================================
2034 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2036 //================================================================================
2038 bool _ViscousBuilder::inflate(_SolidData& data)
2040 SMESH_MesherHelper helper( *_mesh );
2042 // Limit inflation step size by geometry size found by itersecting
2043 // normals of _LayerEdge's with mesh faces
2044 double geomSize = Precision::Infinite(), intersecDist;
2045 SMESH_MeshEditor editor( _mesh );
2046 auto_ptr<SMESH_ElementSearcher> searcher
2047 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2048 for ( unsigned i = 0; i < data._edges.size(); ++i )
2050 if ( data._edges[i]->IsOnEdge() ) continue;
2051 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2052 if ( geomSize > intersecDist )
2053 geomSize = intersecDist;
2055 if ( data._stepSize > 0.3 * geomSize )
2056 limitStepSize( data, 0.3 * geomSize );
2058 const double tgtThick = data._hyp->GetTotalThickness();
2059 if ( data._stepSize > tgtThick )
2060 limitStepSize( data, tgtThick );
2062 if ( data._stepSize < 1. )
2063 data._epsilon = data._stepSize * 1e-7;
2066 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2069 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2070 int nbSteps = 0, nbRepeats = 0;
2071 while ( 1.01 * avgThick < tgtThick )
2073 // new target length
2074 curThick += data._stepSize;
2075 if ( curThick > tgtThick )
2077 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2081 // Elongate _LayerEdge's
2082 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2083 for ( unsigned i = 0; i < data._edges.size(); ++i )
2085 data._edges[i]->SetNewLength( curThick, helper );
2090 if ( !updateNormals( data, helper ) )
2093 // Improve and check quality
2094 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2098 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2099 for ( unsigned i = 0; i < data._edges.size(); ++i )
2101 data._edges[i]->InvalidateStep( nbSteps+1 );
2105 break; // no more inflating possible
2109 // Evaluate achieved thickness
2111 for ( unsigned i = 0; i < data._edges.size(); ++i )
2112 avgThick += data._edges[i]->_len;
2113 avgThick /= data._edges.size();
2115 cout << "-- Thickness " << avgThick << " reached" << endl;
2118 if ( distToIntersection < avgThick*1.5 )
2121 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2122 << avgThick << " ) * 1.5" << endl;
2127 limitStepSize( data, 0.25 * distToIntersection );
2128 if ( data._stepSizeNodes[0] )
2129 data._stepSize = data._stepSizeCoeff *
2130 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2134 return error("failed at the very first inflation step", data._index);
2139 //================================================================================
2141 * \brief Improve quality of layer inner surface and check intersection
2143 //================================================================================
2145 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2147 double & distToIntersection)
2149 if ( data._endEdgeToSmooth.empty() )
2150 return true; // no shapes needing smoothing
2152 bool moved, improved;
2154 SMESH_MesherHelper helper(*_mesh);
2155 Handle(Geom_Surface) surface;
2159 for ( unsigned iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2162 iEnd = data._endEdgeToSmooth[ iS ];
2164 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2165 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2167 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2168 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2169 helper.SetSubShape( F );
2170 surface = BRep_Tool::Surface( F );
2175 F.Nullify(); surface.Nullify();
2177 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2179 if ( data._edges[ iBeg ]->IsOnEdge() )
2181 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2183 // try a simple solution on an analytic EDGE
2184 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2190 for ( int i = iBeg; i < iEnd; ++i )
2192 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2194 dumpCmd( SMESH_Comment("# end step ")<<step);
2196 while ( moved && step++ < 5 );
2197 //cout << " NB STEPS: " << step << endl;
2204 int step = 0, badNb = 0; moved = true;
2205 while (( ++step <= 5 && moved ) || improved )
2207 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2208 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2209 int oldBadNb = badNb;
2212 for ( int i = iBeg; i < iEnd; ++i )
2213 moved |= data._edges[i]->Smooth(badNb);
2214 improved = ( badNb < oldBadNb );
2221 for ( int i = iBeg; i < iEnd; ++i )
2223 _LayerEdge* edge = data._edges[i];
2224 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2225 for ( unsigned j = 0; j < edge->_simplices.size(); ++j )
2226 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2228 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2229 << " "<< edge->_simplices[j]._nPrev->GetID()
2230 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2238 } // loop on shapes to smooth
2240 // Check if the last segments of _LayerEdge intersects 2D elements;
2241 // checked elements are either temporary faces or faces on surfaces w/o the layers
2243 SMESH_MeshEditor editor( _mesh );
2244 auto_ptr<SMESH_ElementSearcher> searcher
2245 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2247 distToIntersection = Precision::Infinite();
2249 const SMDS_MeshElement* intFace = 0;
2251 const SMDS_MeshElement* closestFace = 0;
2254 for ( unsigned i = 0; i < data._edges.size(); ++i )
2256 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2258 if ( distToIntersection > dist )
2260 distToIntersection = dist;
2263 closestFace = intFace;
2270 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2271 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2272 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2273 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2274 << ") distance = " << distToIntersection<< endl;
2281 //================================================================================
2283 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2284 * _LayerEdge's to be in a consequent order
2286 //================================================================================
2288 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2291 Handle(Geom_Surface)& surface,
2292 const TopoDS_Face& F,
2293 SMESH_MesherHelper& helper)
2295 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2297 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2299 if ( i2curve == _edge2curve.end() )
2301 // sort _LayerEdge's by position on the EDGE
2303 map< double, _LayerEdge* > u2edge;
2304 for ( int i = iFrom; i < iTo; ++i )
2305 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2307 ASSERT( u2edge.size() == iTo - iFrom );
2308 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2309 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2310 _edges[i] = u2e->second;
2312 // set _2neibors according to the new order
2313 for ( int i = iFrom; i < iTo-1; ++i )
2314 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2315 _edges[i]->_2neibors->reverse();
2316 if ( u2edge.size() > 1 &&
2317 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2318 _edges[iTo-1]->_2neibors->reverse();
2321 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2323 TopLoc_Location loc; double f,l;
2325 Handle(Geom_Line) line;
2326 Handle(Geom_Circle) circle;
2327 bool isLine, isCirc;
2328 if ( F.IsNull() ) // 3D case
2330 // check if the EDGE is a line
2331 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2332 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2333 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2335 line = Handle(Geom_Line)::DownCast( curve );
2336 circle = Handle(Geom_Circle)::DownCast( curve );
2337 isLine = (!line.IsNull());
2338 isCirc = (!circle.IsNull());
2340 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2343 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2344 while ( nIt->more() )
2345 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2346 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2348 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2349 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2350 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2351 for ( int i = 0; i < 3 && !isLine; ++i )
2352 isLine = ( size.Coord( i+1 ) <= lineTol );
2354 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2361 // check if the EDGE is a line
2362 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2363 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2364 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2366 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2367 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2368 isLine = (!line2d.IsNull());
2369 isCirc = (!circle2d.IsNull());
2371 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2374 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2375 while ( nIt->more() )
2376 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2377 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2379 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2380 for ( int i = 0; i < 2 && !isLine; ++i )
2381 isLine = ( size.Coord( i+1 ) <= lineTol );
2383 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2389 line = new Geom_Line( gp::OX() ); // only type does matter
2393 gp_Pnt2d p = circle2d->Location();
2394 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2395 circle = new Geom_Circle( ax, 1.); // only center position does matter
2399 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2407 return i2curve->second;
2410 //================================================================================
2412 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2414 //================================================================================
2416 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2419 Handle(Geom_Surface)& surface,
2420 const TopoDS_Face& F,
2421 SMESH_MesherHelper& helper)
2423 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2424 helper.GetMeshDS());
2425 TopoDS_Edge E = TopoDS::Edge( S );
2427 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2428 if ( curve.IsNull() ) return false;
2430 // compute a relative length of segments
2431 vector< double > len( iTo-iFrom+1 );
2433 double curLen, prevLen = len[0] = 1.0;
2434 for ( int i = iFrom; i < iTo; ++i )
2436 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2437 len[i-iFrom+1] = len[i-iFrom] + curLen;
2442 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2444 if ( F.IsNull() ) // 3D
2446 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2447 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2448 for ( int i = iFrom; i < iTo; ++i )
2450 double r = len[i-iFrom] / len.back();
2451 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2452 data._edges[i]->_pos.back() = newPos;
2453 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2454 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2455 dumpMove( tgtNode );
2460 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2461 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2462 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2463 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2465 int iPeriodic = helper.GetPeriodicIndex();
2466 if ( iPeriodic == 1 || iPeriodic == 2 )
2468 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2469 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2470 std::swap( uv0, uv1 );
2473 const gp_XY rangeUV = uv1 - uv0;
2474 for ( int i = iFrom; i < iTo; ++i )
2476 double r = len[i-iFrom] / len.back();
2477 gp_XY newUV = uv0 + r * rangeUV;
2478 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2480 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2481 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2482 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2483 dumpMove( tgtNode );
2485 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2486 pos->SetUParameter( newUV.X() );
2487 pos->SetVParameter( newUV.Y() );
2493 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2495 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2496 gp_Pnt center3D = circle->Location();
2498 if ( F.IsNull() ) // 3D
2500 return false; // TODO ???
2504 const gp_XY center( center3D.X(), center3D.Y() );
2506 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2507 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2508 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2509 gp_Vec2d vec0( center, uv0 );
2510 gp_Vec2d vecM( center, uvM);
2511 gp_Vec2d vec1( center, uv1 );
2512 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2513 double uMidl = vec0.Angle( vecM );
2514 if ( uLast < 0 ) uLast += 2.*M_PI; // 0.0 - 2*PI
2515 if ( uMidl < 0 ) uMidl += 2.*M_PI;
2516 const bool sense = ( uMidl < uLast );
2517 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2519 gp_Ax2d axis( center, vec0 );
2520 gp_Circ2d circ ( axis, radius, sense );
2521 for ( int i = iFrom; i < iTo; ++i )
2523 double newU = uLast * len[i-iFrom] / len.back();
2524 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2525 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2527 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2528 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2529 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2530 dumpMove( tgtNode );
2532 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2533 pos->SetUParameter( newUV.X() );
2534 pos->SetVParameter( newUV.Y() );
2543 //================================================================================
2545 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2546 * _LayerEdge's on neighbor EDGE's
2548 //================================================================================
2550 bool _ViscousBuilder::updateNormals( _SolidData& data,
2551 SMESH_MesherHelper& helper )
2553 // make temporary quadrangles got by extrusion of
2554 // mesh edges along _LayerEdge._normal's
2556 vector< const SMDS_MeshElement* > tmpFaces;
2558 set< SMESH_TLink > extrudedLinks; // contains target nodes
2559 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2561 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2562 for ( unsigned i = 0; i < data._edges.size(); ++i )
2564 _LayerEdge* edge = data._edges[i];
2565 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2566 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2567 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2569 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2570 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2571 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2572 if ( !link_isnew.second )
2574 extrudedLinks.erase( link_isnew.first );
2575 continue; // already extruded and will no more encounter
2577 // look for a _LayerEdge containg tgt2
2578 // _LayerEdge* neiborEdge = 0;
2579 // unsigned di = 0; // check _edges[i+di] and _edges[i-di]
2580 // while ( !neiborEdge && ++di <= data._edges.size() )
2582 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2583 // neiborEdge = data._edges[i+di];
2584 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2585 // neiborEdge = data._edges[i-di];
2587 // if ( !neiborEdge )
2588 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2589 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2591 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2592 tmpFaces.push_back( f );
2594 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2595 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2596 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2601 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2602 // Perform two loops on _LayerEdge on EDGE's:
2603 // 1) to find and fix intersection
2604 // 2) to check that no new intersection appears as result of 1)
2606 SMESH_MeshEditor editor( _mesh );
2607 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2609 auto_ptr<SMESH_ElementSearcher> searcher ( editor.GetElementSearcher( fIt ));
2611 // 1) Find intersections
2613 const SMDS_MeshElement* face;
2614 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2615 TLEdge2LEdgeSet edge2CloseEdge;
2617 const double eps = data._epsilon * data._epsilon;
2618 for ( unsigned i = 0; i < data._edges.size(); ++i )
2620 _LayerEdge* edge = data._edges[i];
2621 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2622 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2624 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2625 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2626 ee.insert( f->_le1 );
2627 ee.insert( f->_le2 );
2628 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
2629 edge2CloseEdge[ f->_le1 ].insert( edge );
2630 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
2631 edge2CloseEdge[ f->_le2 ].insert( edge );
2635 // Set _LayerEdge._normal
2637 if ( !edge2CloseEdge.empty() )
2639 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2641 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2642 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2644 _LayerEdge* edge1 = e2ee->first;
2645 _LayerEdge* edge2 = 0;
2646 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
2648 // find EDGEs the edges reside
2650 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2651 if ( S.ShapeType() != TopAbs_EDGE )
2652 continue; // TODO: find EDGE by VERTEX
2653 E1 = TopoDS::Edge( S );
2654 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
2655 while ( E2.IsNull() && eIt != ee.end())
2657 _LayerEdge* e2 = *eIt++;
2658 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2659 if ( S.ShapeType() == TopAbs_EDGE )
2660 E2 = TopoDS::Edge( S ), edge2 = e2;
2662 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2664 // find 3 FACEs sharing 2 EDGEs
2666 TopoDS_Face FF1[2], FF2[2];
2667 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2668 while ( fIt->more() && FF1[1].IsNull())
2670 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2671 if ( helper.IsSubShape( *F, data._solid))
2672 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2674 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2675 while ( fIt->more() && FF2[1].IsNull())
2677 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2678 if ( helper.IsSubShape( *F, data._solid))
2679 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2681 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2682 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2683 std::swap( FF1[0], FF1[1] );
2684 if ( FF2[0].IsSame( FF1[0]) )
2685 std::swap( FF2[0], FF2[1] );
2686 if ( FF1[0].IsNull() || FF2[0].IsNull() )
2689 // // get a new normal for edge1
2691 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2692 if ( edge1->_cosin < 0 )
2693 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2694 if ( edge2->_cosin < 0 )
2695 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2696 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2697 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2698 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2699 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2700 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2701 // newNorm.Normalize();
2703 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2704 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2705 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2706 newNorm.Normalize();
2708 edge1->_normal = newNorm.XYZ();
2710 // update data of edge1 depending on _normal
2711 const SMDS_MeshNode *n1, *n2;
2712 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2713 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2714 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2716 edge1->SetDataByNeighbors( n1, n2, helper );
2718 if ( edge1->_cosin < 0 )
2721 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2722 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2723 edge1->SetCosin( cos( angle ));
2725 // limit data._stepSize
2726 if ( edge1->_cosin > 0.1 )
2728 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2729 while ( fIt->more() )
2730 limitStepSize( data, fIt->next(), edge1->_cosin );
2732 // set new XYZ of target node
2733 edge1->InvalidateStep( 1 );
2735 edge1->SetNewLength( data._stepSize, helper );
2738 // Update normals and other dependent data of not intersecting _LayerEdge's
2739 // neighboring the intersecting ones
2741 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2743 _LayerEdge* edge1 = e2ee->first;
2744 if ( !edge1->_2neibors )
2746 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2748 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2749 if ( edge2CloseEdge.count ( neighbor ))
2750 continue; // j-th neighbor is also intersected
2751 _LayerEdge* prevEdge = edge1;
2752 const int nbSteps = 6;
2753 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2755 if ( !neighbor->_2neibors )
2756 break; // neighbor is on VERTEX
2758 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2759 if ( nextEdge == prevEdge )
2760 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2761 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2762 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
2763 double r = double(step-1)/nbSteps;
2764 if ( !nextEdge->_2neibors )
2767 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2768 newNorm.Normalize();
2770 neighbor->_normal = newNorm;
2771 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2772 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2774 neighbor->InvalidateStep( 1 );
2776 neighbor->SetNewLength( data._stepSize, helper );
2778 // goto the next neighbor
2779 prevEdge = neighbor;
2780 neighbor = nextEdge;
2786 // 2) Check absence of intersections
2789 for ( unsigned i = 0 ; i < tmpFaces.size(); ++i )
2795 //================================================================================
2797 * \brief Looks for intersection of it's last segment with faces
2798 * \param distance - returns shortest distance from the last node to intersection
2800 //================================================================================
2802 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
2804 const double& epsilon,
2805 const SMDS_MeshElement** face)
2807 vector< const SMDS_MeshElement* > suspectFaces;
2809 gp_Ax1 lastSegment = LastSegment(segLen);
2810 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2812 bool segmentIntersected = false;
2813 distance = Precision::Infinite();
2814 int iFace = -1; // intersected face
2815 for ( unsigned j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
2817 const SMDS_MeshElement* face = suspectFaces[j];
2818 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
2819 face->GetNodeIndex( _nodes[0] ) >= 0 )
2820 continue; // face sharing _LayerEdge node
2821 const int nbNodes = face->NbCornerNodes();
2822 bool intFound = false;
2824 SMDS_MeshElement::iterator nIt = face->begin_nodes();
2827 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
2831 const SMDS_MeshNode* tria[3];
2834 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
2837 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
2843 if ( dist < segLen*(1.01))
2844 segmentIntersected = true;
2845 if ( distance > dist )
2846 distance = dist, iFace = j;
2849 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
2850 // if ( distance && iFace > -1 )
2852 // // distance is used to limit size of inflation step which depends on
2853 // // whether the intersected face bears viscous layers or not
2854 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
2858 if ( segmentIntersected )
2861 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
2862 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
2863 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
2864 << ", intersection with face ("
2865 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2866 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
2867 << ") distance = " << distance - segLen<< endl;
2873 return segmentIntersected;
2876 //================================================================================
2878 * \brief Returns size and direction of the last segment
2880 //================================================================================
2882 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
2884 // find two non-coincident positions
2885 gp_XYZ orig = _pos.back();
2887 int iPrev = _pos.size() - 2;
2888 while ( iPrev >= 0 )
2890 dir = orig - _pos[iPrev];
2891 if ( dir.SquareModulus() > 1e-100 )
2901 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
2902 segDir.SetDirection( _normal );
2907 gp_Pnt pPrev = _pos[ iPrev ];
2908 if ( !_sWOL.IsNull() )
2910 TopLoc_Location loc;
2911 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2914 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2915 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
2919 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2920 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
2922 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
2924 segDir.SetLocation( pPrev );
2925 segDir.SetDirection( dir );
2926 segLen = dir.Modulus();
2932 //================================================================================
2934 * \brief Test intersection of the last segment with a given triangle
2935 * using Moller-Trumbore algorithm
2936 * Intersection is detected if distance to intersection is less than _LayerEdge._len
2938 //================================================================================
2940 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
2941 const SMDS_MeshNode* n0,
2942 const SMDS_MeshNode* n1,
2943 const SMDS_MeshNode* n2,
2945 const double& EPSILON) const
2947 //const double EPSILON = 1e-6;
2949 gp_XYZ orig = lastSegment.Location().XYZ();
2950 gp_XYZ dir = lastSegment.Direction().XYZ();
2952 SMESH_TNodeXYZ vert0( n0 );
2953 SMESH_TNodeXYZ vert1( n1 );
2954 SMESH_TNodeXYZ vert2( n2 );
2956 /* calculate distance from vert0 to ray origin */
2957 gp_XYZ tvec = orig - vert0;
2959 if ( tvec * dir > EPSILON )
2960 // intersected face is at back side of the temporary face this _LayerEdge belongs to
2963 gp_XYZ edge1 = vert1 - vert0;
2964 gp_XYZ edge2 = vert2 - vert0;
2966 /* begin calculating determinant - also used to calculate U parameter */
2967 gp_XYZ pvec = dir ^ edge2;
2969 /* if determinant is near zero, ray lies in plane of triangle */
2970 double det = edge1 * pvec;
2972 if (det > -EPSILON && det < EPSILON)
2974 double inv_det = 1.0 / det;
2976 /* calculate U parameter and test bounds */
2977 double u = ( tvec * pvec ) * inv_det;
2978 if (u < 0.0 || u > 1.0)
2981 /* prepare to test V parameter */
2982 gp_XYZ qvec = tvec ^ edge1;
2984 /* calculate V parameter and test bounds */
2985 double v = (dir * qvec) * inv_det;
2986 if ( v < 0.0 || u + v > 1.0 )
2989 /* calculate t, ray intersects triangle */
2990 t = (edge2 * qvec) * inv_det;
2992 // if (det < EPSILON)
2995 // /* calculate distance from vert0 to ray origin */
2996 // gp_XYZ tvec = orig - vert0;
2998 // /* calculate U parameter and test bounds */
2999 // double u = tvec * pvec;
3000 // if (u < 0.0 || u > det)
3003 // /* prepare to test V parameter */
3004 // gp_XYZ qvec = tvec ^ edge1;
3006 // /* calculate V parameter and test bounds */
3007 // double v = dir * qvec;
3008 // if (v < 0.0 || u + v > det)
3011 // /* calculate t, scale parameters, ray intersects triangle */
3012 // double t = edge2 * qvec;
3013 // double inv_det = 1.0 / det;
3021 //================================================================================
3023 * \brief Perform smooth of _LayerEdge's based on EDGE's
3024 * \retval bool - true if node has been moved
3026 //================================================================================
3028 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3029 const TopoDS_Face& F,
3030 SMESH_MesherHelper& helper)
3032 ASSERT( IsOnEdge() );
3034 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3035 SMESH_TNodeXYZ oldPos( tgtNode );
3036 double dist01, distNewOld;
3038 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3039 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3040 dist01 = p0.Distance( _2neibors->_nodes[1] );
3042 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3043 double lenDelta = 0;
3046 lenDelta = _curvature->lenDelta( _len );
3047 newPos.ChangeCoord() += _normal * lenDelta;
3050 distNewOld = newPos.Distance( oldPos );
3054 if ( _2neibors->_plnNorm )
3056 // put newPos on the plane defined by source node and _plnNorm
3057 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3058 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3059 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3061 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3062 _pos.back() = newPos.XYZ();
3066 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3067 gp_XY uv( Precision::Infinite(), 0 );
3068 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3069 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3071 newPos = surface->Value( uv.X(), uv.Y() );
3072 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3075 if ( _curvature && lenDelta < 0 )
3077 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3078 _len -= prevPos.Distance( oldPos );
3079 _len += prevPos.Distance( newPos );
3081 bool moved = distNewOld > dist01/50;
3083 dumpMove( tgtNode ); // debug
3088 //================================================================================
3090 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3091 * \retval bool - true if _tgtNode has been moved
3093 //================================================================================
3095 bool _LayerEdge::Smooth(int& badNb)
3097 if ( _simplices.size() < 2 )
3098 return false; // _LayerEdge inflated along EDGE or FACE
3100 // compute new position for the last _pos
3101 gp_XYZ newPos (0,0,0);
3102 for ( unsigned i = 0; i < _simplices.size(); ++i )
3103 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3104 newPos /= _simplices.size();
3107 newPos += _normal * _curvature->lenDelta( _len );
3109 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3110 // if ( _cosin < -0.1)
3112 // // Avoid decreasing length of edge on concave surface
3113 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3114 // gp_Vec newMove( prevPos, newPos );
3115 // newPos = _pos.back() + newMove.XYZ();
3117 // else if ( _cosin > 0.3 )
3119 // // Avoid increasing length of edge too much
3122 // count quality metrics (orientation) of tetras around _tgtNode
3124 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3125 for ( unsigned i = 0; i < _simplices.size(); ++i )
3126 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3129 for ( unsigned i = 0; i < _simplices.size(); ++i )
3130 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3132 if ( nbOkAfter < nbOkBefore )
3135 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3137 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3138 _len += prevPos.Distance(newPos);
3140 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3141 _pos.back() = newPos;
3143 badNb += _simplices.size() - nbOkAfter;
3150 //================================================================================
3152 * \brief Add a new segment to _LayerEdge during inflation
3154 //================================================================================
3156 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3158 if ( _len - len > -1e-6 )
3160 _pos.push_back( _pos.back() );
3164 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3165 SMESH_TNodeXYZ oldXYZ( n );
3166 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3167 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3169 _pos.push_back( nXYZ );
3171 if ( !_sWOL.IsNull() )
3174 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3176 double u = Precision::Infinite(); // to force projection w/o distance check
3177 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3178 _pos.back().SetCoord( u, 0, 0 );
3179 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3180 pos->SetUParameter( u );
3184 gp_XY uv( Precision::Infinite(), 0 );
3185 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3186 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3187 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3188 pos->SetUParameter( uv.X() );
3189 pos->SetVParameter( uv.Y() );
3191 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3193 dumpMove( n ); //debug
3196 //================================================================================
3198 * \brief Remove last inflation step
3200 //================================================================================
3202 void _LayerEdge::InvalidateStep( int curStep )
3204 if ( _pos.size() > curStep )
3206 _pos.resize( curStep );
3207 gp_Pnt nXYZ = _pos.back();
3208 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3209 if ( !_sWOL.IsNull() )
3211 TopLoc_Location loc;
3212 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3214 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3215 pos->SetUParameter( nXYZ.X() );
3217 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3218 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3222 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3223 pos->SetUParameter( nXYZ.X() );
3224 pos->SetVParameter( nXYZ.Y() );
3225 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3226 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3229 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3234 //================================================================================
3236 * \brief Create layers of prisms
3238 //================================================================================
3240 bool _ViscousBuilder::refine(_SolidData& data)
3242 SMESH_MesherHelper helper( *_mesh );
3243 helper.SetSubShape( data._solid );
3244 helper.SetElementsOnShape(false);
3246 Handle(Geom_Curve) curve;
3247 Handle(Geom_Surface) surface;
3248 TopoDS_Edge geomEdge;
3249 TopoDS_Face geomFace;
3250 TopLoc_Location loc;
3251 double f,l, u/*, distXYZ[4]*/;
3255 for ( unsigned i = 0; i < data._edges.size(); ++i )
3257 _LayerEdge& edge = *data._edges[i];
3259 // get accumulated length of segments
3260 vector< double > segLen( edge._pos.size() );
3262 for ( unsigned j = 1; j < edge._pos.size(); ++j )
3263 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3265 // allocate memory for new nodes if it is not yet refined
3266 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3267 if ( edge._nodes.size() == 2 )
3269 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3271 edge._nodes.back() = tgtNode;
3273 if ( !edge._sWOL.IsNull() )
3275 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3276 // restore position of the last node
3280 geomEdge = TopoDS::Edge( edge._sWOL );
3281 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3282 // double u = helper.GetNodeU( tgtNode );
3283 // p = curve->Value( u );
3287 geomFace = TopoDS::Face( edge._sWOL );
3288 surface = BRep_Tool::Surface( geomFace, loc );
3289 // gp_XY uv = helper.GetNodeUV( tgtNode );
3290 // p = surface->Value( uv.X(), uv.Y() );
3292 // p.Transform( loc );
3293 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3295 // calculate height of the first layer
3297 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3298 const double f = data._hyp->GetStretchFactor();
3299 const int N = data._hyp->GetNumberLayers();
3300 const double fPowN = pow( f, N );
3301 if ( fPowN - 1 <= numeric_limits<double>::min() )
3304 h0 = T * ( f - 1 )/( fPowN - 1 );
3306 const double zeroLen = std::numeric_limits<double>::min();
3308 // create intermediate nodes
3309 double hSum = 0, hi = h0/f;
3311 for ( unsigned iStep = 1; iStep < edge._nodes.size(); ++iStep )
3313 // compute an intermediate position
3316 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3318 int iPrevSeg = iSeg-1;
3319 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3321 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3322 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3324 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3325 if ( !edge._sWOL.IsNull() )
3327 // compute XYZ by parameters <pos>
3331 pos = curve->Value( u ).Transformed(loc);
3335 uv.SetCoord( pos.X(), pos.Y() );
3336 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3339 // create or update the node
3342 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3343 if ( !edge._sWOL.IsNull() )
3346 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3348 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3352 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3357 if ( !edge._sWOL.IsNull() )
3359 // make average pos from new and current parameters
3362 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3363 pos = curve->Value( u ).Transformed(loc);
3367 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3368 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3371 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3376 // TODO: make quadratic prisms and polyhedrons(?)
3378 helper.SetElementsOnShape(true);
3380 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3381 for ( ; exp.More(); exp.Next() )
3383 if ( _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3385 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3386 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3387 vector< vector<const SMDS_MeshNode*>* > nnVec;
3388 while ( fIt->more() )
3390 const SMDS_MeshElement* face = fIt->next();
3391 int nbNodes = face->NbCornerNodes();
3392 nnVec.resize( nbNodes );
3393 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3394 for ( int iN = 0; iN < nbNodes; ++iN )
3396 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3397 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3400 int nbZ = nnVec[0]->size();
3404 for ( int iZ = 1; iZ < nbZ; ++iZ )
3405 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3406 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3409 for ( int iZ = 1; iZ < nbZ; ++iZ )
3410 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3411 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3412 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3413 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3416 return error("Not supported type of element", data._index);
3423 //================================================================================
3425 * \brief Shrink 2D mesh on faces to let space for inflated layers
3427 //================================================================================
3429 bool _ViscousBuilder::shrink()
3431 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3432 // inflated along FACE or EDGE)
3433 map< TGeomID, _SolidData* > f2sdMap;
3434 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
3436 _SolidData& data = _sdVec[i];
3437 TopTools_MapOfShape FFMap;
3438 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3439 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3440 if ( s2s->second.ShapeType() == TopAbs_FACE )
3442 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3444 if ( FFMap.Add( (*s2s).second ))
3445 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3446 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3447 // by StdMeshers_QuadToTriaAdaptor
3448 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3450 SMESH_ProxyMesh::SubMesh* proxySub =
3451 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3452 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3453 while ( fIt->more() )
3454 proxySub->AddElement( fIt->next() );
3455 // as a result 3D algo will use elements from proxySub and not from smDS
3460 SMESH_MesherHelper helper( *_mesh );
3463 map< int, _Shrinker1D > e2shrMap;
3465 // loop on FACES to srink mesh on
3466 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3467 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3469 _SolidData& data = *f2sd->second;
3470 TNode2Edge& n2eMap = data._n2eMap;
3471 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3473 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3475 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3476 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3478 helper.SetSubShape(F);
3480 // ===========================
3481 // Prepare data for shrinking
3482 // ===========================
3484 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3485 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3486 vector < const SMDS_MeshNode* > smoothNodes;
3488 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3489 while ( nIt->more() )
3491 const SMDS_MeshNode* n = nIt->next();
3492 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3493 smoothNodes.push_back( n );
3496 // Find out face orientation
3498 const set<TGeomID> ignoreShapes;
3500 if ( !smoothNodes.empty() )
3502 vector<_Simplex> simplices;
3503 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3504 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3505 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3506 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3507 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3511 // Find _LayerEdge's inflated along F
3512 vector< _LayerEdge* > lEdges;
3514 SMESH_subMeshIteratorPtr subIt =
3515 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3516 while ( subIt->more() )
3518 SMESH_subMesh* sub = subIt->next();
3519 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3520 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3522 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3523 while ( nIt->more() )
3525 _LayerEdge* edge = n2eMap[ nIt->next() ];
3526 lEdges.push_back( edge );
3527 prepareEdgeToShrink( *edge, F, helper, smDS );
3532 // Replace source nodes by target nodes in mesh faces to shrink
3533 const SMDS_MeshNode* nodes[20];
3534 for ( unsigned i = 0; i < lEdges.size(); ++i )
3536 _LayerEdge& edge = *lEdges[i];
3537 const SMDS_MeshNode* srcNode = edge._nodes[0];
3538 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3539 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3540 while ( fIt->more() )
3542 const SMDS_MeshElement* f = fIt->next();
3543 if ( !smDS->Contains( f ))
3545 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3546 for ( int iN = 0; iN < f->NbNodes(); ++iN )
3548 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3549 nodes[iN] = ( n == srcNode ? tgtNode : n );
3551 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3555 // find out if a FACE is concave
3556 const bool isConcaveFace = isConcave( F, helper );
3558 // Create _SmoothNode's on face F
3559 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3561 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3562 for ( unsigned i = 0; i < smoothNodes.size(); ++i )
3564 const SMDS_MeshNode* n = smoothNodes[i];
3565 nodesToSmooth[ i ]._node = n;
3566 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3567 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, isConcaveFace );
3568 // fix up incorrect uv of nodes on the FACE
3569 helper.GetNodeUV( F, n, 0, &isOkUV);
3574 //if ( nodesToSmooth.empty() ) continue;
3576 // Find EDGE's to shrink
3577 set< _Shrinker1D* > eShri1D;
3579 for ( unsigned i = 0; i < lEdges.size(); ++i )
3581 _LayerEdge* edge = lEdges[i];
3582 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3584 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3585 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3586 eShri1D.insert( & srinker );
3587 srinker.AddEdge( edge, helper );
3588 // restore params of nodes on EGDE if the EDGE has been already
3589 // srinked while srinking another FACE
3590 srinker.RestoreParams();
3595 // ==================
3596 // Perform shrinking
3597 // ==================
3599 bool shrinked = true;
3600 int badNb, shriStep=0, smooStep=0;
3603 // Move boundary nodes (actually just set new UV)
3604 // -----------------------------------------------
3605 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep++ ); // debug
3607 for ( unsigned i = 0; i < lEdges.size(); ++i )
3609 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3613 // Move nodes on EDGE's
3614 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3615 for ( ; shr != eShri1D.end(); ++shr )
3616 (*shr)->Compute( /*set3D=*/false, helper );
3619 // -----------------
3620 int nbNoImpSteps = 0;
3623 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3625 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3627 int oldBadNb = badNb;
3630 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3632 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3633 /*isCentroidal=*/isConcaveFace,/*set3D=*/false );
3635 if ( badNb < oldBadNb )
3643 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3645 // No wrongly shaped faces remain; final smooth. Set node XYZ.
3646 // First, find out a needed quality of smoothing (high for quadrangles only)
3649 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
3650 if ( hasTria != hasQuad )
3652 highQuality = hasQuad;
3656 set<int> nbNodesSet;
3657 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3658 while ( fIt->more() && nbNodesSet.size() < 2 )
3659 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
3660 highQuality = ( *nbNodesSet.begin() == 4 );
3663 if ( !highQuality && isConcaveFace )
3664 fixBadFaces( F, helper ); // fix narrow faces by swaping diagonals
3665 for ( int st = highQuality ? 10 : 3; st; --st )
3667 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3668 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3669 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3670 /*isCentroidal=*/isConcaveFace,/*set3D=*/st==1 );
3673 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
3674 _SrinkShapeListener::ToClearSubMeshWithSolid( sm, data._solid );
3676 } // loop on FACES to srink mesh on
3679 // Replace source nodes by target nodes in shrinked mesh edges
3681 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3682 for ( ; e2shr != e2shrMap.end(); ++e2shr )
3683 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3688 //================================================================================
3690 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3692 //================================================================================
3694 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
3695 const TopoDS_Face& F,
3696 SMESH_MesherHelper& helper,
3697 const SMESHDS_SubMesh* faceSubMesh)
3699 const SMDS_MeshNode* srcNode = edge._nodes[0];
3700 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3704 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3706 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3707 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3708 gp_Vec2d uvDir( srcUV, tgtUV );
3709 double uvLen = uvDir.Magnitude();
3711 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3713 // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3714 vector<const SMDS_MeshElement*> faces;
3715 multimap< double, const SMDS_MeshNode* > proj2node;
3716 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3717 while ( fIt->more() )
3719 const SMDS_MeshElement* f = fIt->next();
3720 if ( faceSubMesh->Contains( f ))
3721 faces.push_back( f );
3723 for ( unsigned i = 0; i < faces.size(); ++i )
3725 const int nbNodes = faces[i]->NbCornerNodes();
3726 for ( int j = 0; j < nbNodes; ++j )
3728 const SMDS_MeshNode* n = faces[i]->GetNode(j);
3729 if ( n == srcNode ) continue;
3730 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3731 ( faces.size() > 1 || nbNodes > 3 ))
3733 gp_Pnt2d uv = helper.GetNodeUV( F, n );
3734 gp_Vec2d uvDirN( srcUV, uv );
3735 double proj = uvDirN * uvDir;
3736 proj2node.insert( make_pair( proj, n ));
3740 multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
3741 const double minProj = p2n->first;
3742 const double projThreshold = 1.1 * uvLen;
3743 if ( minProj > projThreshold )
3745 // tgtNode is located so that it does not make faces with wrong orientation
3748 edge._pos.resize(1);
3749 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
3751 // store most risky nodes in _simplices
3752 p2nEnd = proj2node.lower_bound( projThreshold );
3753 int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
3754 edge._simplices.resize( nbSimpl );
3755 for ( int i = 0; i < nbSimpl; ++i )
3757 edge._simplices[i]._nPrev = p2n->second;
3758 if ( ++p2n != p2nEnd )
3759 edge._simplices[i]._nNext = p2n->second;
3761 // set UV of source node to target node
3762 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3763 pos->SetUParameter( srcUV.X() );
3764 pos->SetVParameter( srcUV.Y() );
3766 else // _sWOL is TopAbs_EDGE
3768 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
3769 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
3770 if ( !edgeSM || edgeSM->NbElements() == 0 )
3771 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3773 const SMDS_MeshNode* n2 = 0;
3774 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3775 while ( eIt->more() && !n2 )
3777 const SMDS_MeshElement* e = eIt->next();
3778 if ( !edgeSM->Contains(e)) continue;
3779 n2 = e->GetNode( 0 );
3780 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
3783 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3785 double uSrc = helper.GetNodeU( E, srcNode, n2 );
3786 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
3787 double u2 = helper.GetNodeU( E, n2, srcNode );
3789 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
3791 // tgtNode is located so that it does not make faces with wrong orientation
3794 edge._pos.resize(1);
3795 edge._pos[0].SetCoord( U_TGT, uTgt );
3796 edge._pos[0].SetCoord( U_SRC, uSrc );
3797 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
3799 edge._simplices.resize( 1 );
3800 edge._simplices[0]._nPrev = n2;
3802 // set UV of source node to target node
3803 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3804 pos->SetUParameter( uSrc );
3808 //================================================================================
3810 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
3812 //================================================================================
3814 // Compute UV to follow during shrinking
3816 // const SMDS_MeshNode* srcNode = edge._nodes[0];
3817 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
3819 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3820 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3821 // gp_Vec2d uvDir( srcUV, tgtUV );
3822 // double uvLen = uvDir.Magnitude();
3825 // // Select shrinking step such that not to make faces with wrong orientation.
3826 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3827 // const double minStepSize = uvLen / 20;
3828 // double stepSize = uvLen;
3829 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3830 // while ( fIt->more() )
3832 // const SMDS_MeshElement* f = fIt->next();
3833 // if ( !faceSubMesh->Contains( f )) continue;
3834 // const int nbNodes = f->NbCornerNodes();
3835 // for ( int i = 0; i < nbNodes; ++i )
3837 // const SMDS_MeshNode* n = f->GetNode(i);
3838 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
3840 // gp_XY uv = helper.GetNodeUV( F, n );
3841 // gp_Vec2d uvDirN( srcUV, uv );
3842 // double proj = uvDirN * uvDir;
3843 // if ( proj < stepSize && proj > minStepSize )
3849 // const int nbSteps = ceil( uvLen / stepSize );
3850 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
3851 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
3852 // edge._pos.resize( nbSteps );
3853 // edge._pos[0] = tgtUV0;
3854 // for ( int i = 1; i < nbSteps; ++i )
3856 // double r = i / double( nbSteps );
3857 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
3862 //================================================================================
3864 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
3866 //================================================================================
3868 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper)
3870 SMESH::Controls::AspectRatio qualifier;
3871 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
3872 const double maxAspectRatio = 4.;
3874 // find bad triangles
3876 vector< const SMDS_MeshElement* > badTrias;
3877 vector< double > badAspects;
3878 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
3879 SMDS_ElemIteratorPtr fIt = sm->GetElements();
3880 while ( fIt->more() )
3882 const SMDS_MeshElement * f = fIt->next();
3883 if ( f->NbCornerNodes() != 3 ) continue;
3884 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = SMESH_TNodeXYZ( f->GetNode(iP));
3885 double aspect = qualifier.GetValue( points );
3886 if ( aspect > maxAspectRatio )
3888 badTrias.push_back( f );
3889 badAspects.push_back( aspect );
3892 if ( badTrias.empty() )
3895 // find couples of faces to swap diagonal
3897 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
3898 vector< T2Trias > triaCouples;
3900 TIDSortedElemSet involvedFaces, emptySet;
3901 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
3904 double aspRatio [3];
3907 involvedFaces.insert( badTrias[iTia] );
3908 for ( int iP = 0; iP < 3; ++iP )
3909 points(iP+1) = SMESH_TNodeXYZ( badTrias[iTia]->GetNode(iP));
3911 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
3912 int bestCouple = -1;
3913 for ( int iSide = 0; iSide < 3; ++iSide )
3915 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
3916 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
3917 trias [iSide].first = badTrias[iTia];
3918 trias [iSide].second = SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, involvedFaces,
3920 if ( ! trias[iSide].second || trias[iSide].second->NbCornerNodes() != 3 )
3923 // aspect ratio of an adjacent tria
3924 for ( int iP = 0; iP < 3; ++iP )
3925 points2(iP+1) = SMESH_TNodeXYZ( trias[iSide].second->GetNode(iP));
3926 double aspectInit = qualifier.GetValue( points2 );
3928 // arrange nodes as after diag-swaping
3929 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
3930 i3 = helper.WrapIndex( i1-1, 3 );
3932 i3 = helper.WrapIndex( i1+1, 3 );
3934 points1( 1+ iSide ) = points2( 1+ i3 );
3935 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
3937 // aspect ratio after diag-swaping
3938 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
3939 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
3942 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
3946 if ( bestCouple >= 0 )
3948 triaCouples.push_back( trias[bestCouple] );
3949 involvedFaces.insert ( trias[bestCouple].second );
3953 involvedFaces.erase( badTrias[iTia] );
3956 if ( triaCouples.empty() )
3961 SMESH_MeshEditor editor( helper.GetMesh() );
3962 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
3963 for ( size_t i = 0; i < triaCouples.size(); ++i )
3965 dumpChangeNodes( triaCouples[i].first );
3966 dumpChangeNodes( triaCouples[i].second );
3967 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
3971 // just for debug dump resulting triangles
3972 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID());
3973 for ( size_t i = 0; i < triaCouples.size(); ++i )
3975 dumpChangeNodes( triaCouples[i].first );
3976 dumpChangeNodes( triaCouples[i].second );
3980 //================================================================================
3982 * \brief Move target node to it's final position on the FACE during shrinking
3984 //================================================================================
3986 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
3987 const TopoDS_Face& F,
3988 SMESH_MesherHelper& helper )
3991 return false; // already at the target position
3993 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
3995 if ( _sWOL.ShapeType() == TopAbs_FACE )
3997 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
3998 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y());
3999 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4000 const double uvLen = tgtUV.Distance( curUV );
4002 // Select shrinking step such that not to make faces with wrong orientation.
4003 const double kSafe = 0.8;
4004 const double minStepSize = uvLen / 10;
4005 double stepSize = uvLen;
4006 for ( unsigned i = 0; i < _simplices.size(); ++i )
4008 const SMDS_MeshNode* nn[2] = { _simplices[i]._nPrev, _simplices[i]._nNext };
4009 for ( int j = 0; j < 2; ++j )
4010 if ( const SMDS_MeshNode* n = nn[j] )
4012 gp_XY uv = helper.GetNodeUV( F, n );
4013 gp_Vec2d uvDirN( curUV, uv );
4014 double proj = uvDirN * uvDir * kSafe;
4015 if ( proj < stepSize && proj > minStepSize )
4021 if ( stepSize == uvLen )
4028 newUV = curUV + uvDir.XY() * stepSize;
4031 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4032 pos->SetUParameter( newUV.X() );
4033 pos->SetVParameter( newUV.Y() );
4036 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4037 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4038 dumpMove( tgtNode );
4041 else // _sWOL is TopAbs_EDGE
4043 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4044 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4046 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4047 const double uSrc = _pos[0].Coord( U_SRC );
4048 const double lenTgt = _pos[0].Coord( LEN_TGT );
4050 double newU = _pos[0].Coord( U_TGT );
4051 if ( lenTgt < 0.99 * fabs( uSrc-u2 ))
4057 newU = 0.1 * uSrc + 0.9 * u2;
4059 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4060 pos->SetUParameter( newU );
4062 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4063 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4064 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4065 dumpMove( tgtNode );
4071 //================================================================================
4073 * \brief Perform smooth on the FACE
4074 * \retval bool - true if the node has been moved
4076 //================================================================================
4078 bool _SmoothNode::Smooth(int& badNb,
4079 Handle(Geom_Surface)& surface,
4080 SMESH_MesherHelper& helper,
4081 const double refSign,
4085 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4087 // get uv of surrounding nodes
4088 vector<gp_XY> uv( _simplices.size() );
4089 for ( size_t i = 0; i < _simplices.size(); ++i )
4090 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4092 // compute new UV for the node
4094 if ( isCentroidal && _simplices.size() > 3 )
4096 // average centers of diagonals wieghted with their reciprocal lengths
4097 if ( _simplices.size() == 4 )
4099 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4100 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4101 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4105 double sumWeight = 0;
4106 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4107 for ( int i = 0; i < nb; ++i )
4110 int iTo = i + _simplices.size() - 1;
4111 for ( int j = iFrom; j < iTo; ++j )
4113 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4114 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4116 newPos += w * ( uv[i]+uv[i2] );
4119 newPos /= 2 * sumWeight;
4125 isCentroidal = false;
4126 for ( size_t i = 0; i < _simplices.size(); ++i )
4128 newPos /= _simplices.size();
4131 // count quality metrics (orientation) of triangles around the node
4133 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4134 for ( unsigned i = 0; i < _simplices.size(); ++i )
4135 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4138 for ( unsigned i = 0; i < _simplices.size(); ++i )
4139 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4141 if ( nbOkAfter < nbOkBefore )
4143 // if ( isCentroidal )
4144 // return Smooth( badNb, surface, helper, refSign, !isCentroidal, set3D );
4145 badNb += _simplices.size() - nbOkBefore;
4149 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4150 pos->SetUParameter( newPos.X() );
4151 pos->SetVParameter( newPos.Y() );
4158 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4159 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4163 badNb += _simplices.size() - nbOkAfter;
4164 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4167 //================================================================================
4169 * \brief Delete _SolidData
4171 //================================================================================
4173 _SolidData::~_SolidData()
4175 for ( unsigned i = 0; i < _edges.size(); ++i )
4177 if ( _edges[i] && _edges[i]->_2neibors )
4178 delete _edges[i]->_2neibors;
4183 //================================================================================
4185 * \brief Add a _LayerEdge inflated along the EDGE
4187 //================================================================================
4189 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4192 if ( _nodes.empty() )
4194 _edges[0] = _edges[1] = 0;
4198 if ( e == _edges[0] || e == _edges[1] )
4200 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4201 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4202 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4203 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4206 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4208 BRep_Tool::Range( E, f,l );
4209 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4210 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4214 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4215 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4217 if ( _nodes.empty() )
4219 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4220 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4222 TopLoc_Location loc;
4223 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4224 GeomAdaptor_Curve aCurve(C, f,l);
4225 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4227 int nbExpectNodes = eSubMesh->NbNodes() - e->_nodes.size();
4228 _initU .reserve( nbExpectNodes );
4229 _normPar.reserve( nbExpectNodes );
4230 _nodes .reserve( nbExpectNodes );
4231 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4232 while ( nIt->more() )
4234 const SMDS_MeshNode* node = nIt->next();
4235 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4236 node == tgtNode0 || node == tgtNode1 )
4237 continue; // refinement nodes
4238 _nodes.push_back( node );
4239 _initU.push_back( helper.GetNodeU( E, node ));
4240 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4241 _normPar.push_back( len / totLen );
4246 // remove target node of the _LayerEdge from _nodes
4248 for ( unsigned i = 0; i < _nodes.size(); ++i )
4249 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4250 _nodes[i] = 0, nbFound++;
4251 if ( nbFound == _nodes.size() )
4256 //================================================================================
4258 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4260 //================================================================================
4262 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4264 if ( _done || _nodes.empty())
4266 const _LayerEdge* e = _edges[0];
4267 if ( !e ) e = _edges[1];
4270 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4271 ( !_edges[1] || _edges[1]->_pos.empty() ));
4273 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4275 if ( set3D || _done )
4277 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4278 GeomAdaptor_Curve aCurve(C, f,l);
4281 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4283 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4284 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4286 for ( unsigned i = 0; i < _nodes.size(); ++i )
4288 if ( !_nodes[i] ) continue;
4289 double len = totLen * _normPar[i];
4290 GCPnts_AbscissaPoint discret( aCurve, len, f );
4291 if ( !discret.IsDone() )
4292 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4293 double u = discret.Parameter();
4294 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4295 pos->SetUParameter( u );
4296 gp_Pnt p = C->Value( u );
4297 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4302 BRep_Tool::Range( E, f,l );
4304 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4306 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4308 for ( unsigned i = 0; i < _nodes.size(); ++i )
4310 if ( !_nodes[i] ) continue;
4311 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4312 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4313 pos->SetUParameter( u );
4318 //================================================================================
4320 * \brief Restore initial parameters of nodes on EDGE
4322 //================================================================================
4324 void _Shrinker1D::RestoreParams()
4327 for ( unsigned i = 0; i < _nodes.size(); ++i )
4329 if ( !_nodes[i] ) continue;
4330 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4331 pos->SetUParameter( _initU[i] );
4336 //================================================================================
4338 * \brief Replace source nodes by target nodes in shrinked mesh edges
4340 //================================================================================
4342 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4344 const SMDS_MeshNode* nodes[3];
4345 for ( int i = 0; i < 2; ++i )
4347 if ( !_edges[i] ) continue;
4349 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4350 if ( !eSubMesh ) return;
4351 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4352 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4353 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4354 while ( eIt->more() )
4356 const SMDS_MeshElement* e = eIt->next();
4357 if ( !eSubMesh->Contains( e ))
4359 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4360 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4362 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4363 nodes[iN] = ( n == srcNode ? tgtNode : n );
4365 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4370 //================================================================================
4372 * \brief Creates 2D and 1D elements on boundaries of new prisms
4374 //================================================================================
4376 bool _ViscousBuilder::addBoundaryElements()
4378 SMESH_MesherHelper helper( *_mesh );
4380 for ( unsigned i = 0; i < _sdVec.size(); ++i )
4382 _SolidData& data = _sdVec[i];
4383 TopTools_IndexedMapOfShape geomEdges;
4384 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4385 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4387 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4389 // Get _LayerEdge's based on E
4391 map< double, const SMDS_MeshNode* > u2nodes;
4392 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4395 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
4396 TNode2Edge & n2eMap = data._n2eMap;
4397 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4399 //check if 2D elements are needed on E
4400 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
4401 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
4402 ledges.push_back( n2e->second );
4404 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
4405 continue; // no layers on E
4406 ledges.push_back( n2eMap[ u2n->second ]);
4408 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
4409 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
4410 int nbSharedPyram = 0;
4411 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
4412 while ( vIt->more() )
4414 const SMDS_MeshElement* v = vIt->next();
4415 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
4417 if ( nbSharedPyram > 1 )
4418 continue; // not free border of the pyramid
4420 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
4421 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
4422 continue; // faces already created
4424 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
4425 ledges.push_back( n2eMap[ u2n->second ]);
4427 // Find out orientation and type of face to create
4429 bool reverse = false, isOnFace;
4431 map< TGeomID, TopoDS_Shape >::iterator e2f =
4432 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
4434 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
4436 F = e2f->second.Oriented( TopAbs_FORWARD );
4437 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
4438 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
4443 // find FACE with layers sharing E
4444 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
4445 while ( fIt->more() && F.IsNull() )
4447 const TopoDS_Shape* pF = fIt->next();
4448 if ( helper.IsSubShape( *pF, data._solid) &&
4449 !_ignoreShapeIds.count( e2f->first ))
4453 // Find the sub-mesh to add new faces
4454 SMESHDS_SubMesh* sm = 0;
4456 sm = getMeshDS()->MeshElements( F );
4458 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
4460 return error("error in addBoundaryElements()", data._index);
4463 const int dj1 = reverse ? 0 : 1;
4464 const int dj2 = reverse ? 1 : 0;
4465 for ( unsigned j = 1; j < ledges.size(); ++j )
4467 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
4468 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
4470 for ( unsigned z = 1; z < nn1.size(); ++z )
4471 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
4473 for ( unsigned z = 1; z < nn1.size(); ++z )
4474 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));