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(): SMESH_subMeshEventListener(/*isDeletable=*/false) {}
126 static SMESH_subMeshEventListener* Get() { static _SrinkShapeListener l; return &l; }
128 virtual void ProcessEvent(const int event,
130 SMESH_subMesh* solidSM,
131 SMESH_subMeshEventListenerData* data,
132 const SMESH_Hypothesis* hyp)
134 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
136 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
139 static void ToClearSubMeshWithSolid( SMESH_subMesh* sm,
140 const TopoDS_Shape& solid)
142 SMESH_subMesh* solidSM = sm->GetFather()->GetSubMesh( solid );
143 SMESH_subMeshEventListenerData* data = solidSM->GetEventListenerData( Get());
146 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sm ) ==
147 data->mySubMeshes.end())
148 data->mySubMeshes.push_back( sm );
152 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sm );
153 sm->SetEventListener( Get(), data, /*whereToListenTo=*/solidSM );
157 //--------------------------------------------------------------------------------
159 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
160 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
161 * delete the data as soon as it has been used
163 class _ViscousListener : SMESH_subMeshEventListener
165 _ViscousListener(): SMESH_subMeshEventListener(/*isDeletable=*/false) {}
166 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
168 virtual void ProcessEvent(const int event,
170 SMESH_subMesh* subMesh,
171 SMESH_subMeshEventListenerData* data,
172 const SMESH_Hypothesis* hyp)
174 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
176 // delete SMESH_ProxyMesh containing temporary faces
177 subMesh->DeleteEventListener( this );
180 // Finds or creates proxy mesh of the solid
181 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
182 const TopoDS_Shape& solid,
185 if ( !mesh ) return 0;
186 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
187 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
188 if ( !data && toCreate )
190 data = new _MeshOfSolid(mesh);
191 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
192 sm->SetEventListener( Get(), data, sm );
196 // Removes proxy mesh of the solid
197 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
199 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
203 //--------------------------------------------------------------------------------
205 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
206 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
207 * The class is used to check validity of face or volumes around a smoothed node;
208 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
212 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
213 _Simplex(const SMDS_MeshNode* nPrev=0, const SMDS_MeshNode* nNext=0)
214 : _nPrev(nPrev), _nNext(nNext) {}
215 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
217 const double M[3][3] =
218 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
219 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
220 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
221 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
222 + M[0][1]*M[1][2]*M[2][0]
223 + M[0][2]*M[1][0]*M[2][1]
224 - M[0][0]*M[1][2]*M[2][1]
225 - M[0][1]*M[1][0]*M[2][2]
226 - M[0][2]*M[1][1]*M[2][0]);
227 return determinant > 1e-100;
229 bool IsForward(const gp_XY& tgtUV,
230 const SMDS_MeshNode* smoothedNode,
231 const TopoDS_Face& face,
232 SMESH_MesherHelper& helper,
233 const double refSign) const
235 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
236 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
237 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
239 return d*refSign > 1e-100;
241 bool IsNeighbour(const _Simplex& other) const
243 return _nPrev == other._nNext || _nNext == other._nPrev;
246 //--------------------------------------------------------------------------------
248 * Structure used to take into account surface curvature while smoothing
253 double _k; // factor to correct node smoothed position
255 static _Curvature* New( double avgNormProj, double avgDist )
258 if ( fabs( avgNormProj / avgDist ) > 1./200 )
261 c->_r = avgDist * avgDist / avgNormProj;
262 c->_k = avgDist * avgDist / c->_r / c->_r;
263 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
267 double lenDelta(double len) const { return _k * ( _r + len ); }
270 //--------------------------------------------------------------------------------
272 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
276 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
277 const SMDS_MeshNode* _nodes[2];
278 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
280 double _wgt[2]; // weights of _nodes
281 _LayerEdge* _edges[2];
283 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
286 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
288 std::swap( _nodes[0], _nodes[1] );
289 std::swap( _wgt[0], _wgt[1] );
292 //--------------------------------------------------------------------------------
294 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
295 * and a node of the most internal layer (_nodes.back())
299 vector< const SMDS_MeshNode*> _nodes;
301 gp_XYZ _normal; // to solid surface
302 vector<gp_XYZ> _pos; // points computed during inflation
303 double _len; // length achived with the last step
304 double _cosin; // of angle (_normal ^ surface)
305 double _lenFactor; // to compute _len taking _cosin into account
307 // face or edge w/o layer along or near which _LayerEdge is inflated
309 // simplices connected to the source node (_nodes[0]);
310 // used for smoothing and quality check of _LayerEdge's based on the FACE
311 vector<_Simplex> _simplices;
312 // data for smoothing of _LayerEdge's based on the EDGE
313 _2NearEdges* _2neibors;
315 _Curvature* _curvature;
316 // TODO:: detele _Curvature, _plnNorm
318 void SetNewLength( double len, SMESH_MesherHelper& helper );
319 bool SetNewLength2d( Handle(Geom_Surface)& surface,
320 const TopoDS_Face& F,
321 SMESH_MesherHelper& helper );
322 void SetDataByNeighbors( const SMDS_MeshNode* n1,
323 const SMDS_MeshNode* n2,
324 SMESH_MesherHelper& helper);
325 void InvalidateStep( int curStep );
326 bool Smooth(int& badNb);
327 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
328 const TopoDS_Face& F,
329 SMESH_MesherHelper& helper);
330 bool FindIntersection( SMESH_ElementSearcher& searcher,
332 const double& epsilon,
333 const SMDS_MeshElement** face = 0);
334 bool SegTriaInter( const gp_Ax1& lastSegment,
335 const SMDS_MeshNode* n0,
336 const SMDS_MeshNode* n1,
337 const SMDS_MeshNode* n2,
339 const double& epsilon) const;
340 gp_Ax1 LastSegment(double& segLen) const;
341 bool IsOnEdge() const { return _2neibors; }
342 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
343 void SetCosin( double cosin );
347 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
349 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
350 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
353 //--------------------------------------------------------------------------------
355 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
357 //--------------------------------------------------------------------------------
359 * \brief Data of a SOLID
364 const StdMeshers_ViscousLayers* _hyp;
365 _MeshOfSolid* _proxyMesh;
366 set<TGeomID> _reversedFaceIds;
368 double _stepSize, _stepSizeCoeff;
369 const SMDS_MeshNode* _stepSizeNodes[2];
372 // edges of _n2eMap. We keep same data in two containers because
373 // iteration over the map is 5 time longer than over the vector
374 vector< _LayerEdge* > _edges;
376 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
377 // layers and a FACE w/o layers
378 // value: the shape (FACE or EDGE) to shrink mesh on.
379 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
380 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
382 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
383 set< TGeomID > _noShrinkFaces;
385 // <EDGE to smooth on> to <it's curve>
386 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
388 // end indices in _edges of _LayerEdge on one shape to smooth
389 vector< int > _endEdgeToSmooth;
391 double _epsilon; // precision for SegTriaInter()
393 int _index; // for debug
395 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
396 const StdMeshers_ViscousLayers* h=0,
397 _MeshOfSolid* m=0) :_solid(s), _hyp(h), _proxyMesh(m) {}
400 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
403 Handle(Geom_Surface)& surface,
404 const TopoDS_Face& F,
405 SMESH_MesherHelper& helper);
407 //--------------------------------------------------------------------------------
409 * \brief Data of node on a shrinked FACE
413 const SMDS_MeshNode* _node;
414 //vector<const SMDS_MeshNode*> _nodesAround;
415 vector<_Simplex> _simplices; // for quality check
417 bool Smooth(int& badNb,
418 Handle(Geom_Surface)& surface,
419 SMESH_MesherHelper& helper,
420 const double refSign,
424 //--------------------------------------------------------------------------------
426 * \brief Builder of viscous layers
428 class _ViscousBuilder
433 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
434 const TopoDS_Shape& shape);
436 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
437 void RestoreListeners();
439 // computes SMESH_ProxyMesh::SubMesh::_n2n;
440 bool MakeN2NMap( _MeshOfSolid* pm );
444 bool findSolidsWithLayers();
445 bool findFacesWithLayers();
446 bool makeLayer(_SolidData& data);
447 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
448 SMESH_MesherHelper& helper, _SolidData& data);
449 bool findNeiborsOnEdge(const _LayerEdge* edge,
450 const SMDS_MeshNode*& n1,
451 const SMDS_MeshNode*& n2,
453 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
454 const set<TGeomID>& ingnoreShapes,
455 const _SolidData* dataToCheckOri = 0,
456 const bool toSort = false);
457 bool sortEdges( _SolidData& data,
458 vector< vector<_LayerEdge*> >& edgesByGeom);
459 void limitStepSize( _SolidData& data,
460 const SMDS_MeshElement* face,
462 void limitStepSize( _SolidData& data, const double minSize);
463 bool inflate(_SolidData& data);
464 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
465 bool smoothAnalyticEdge( _SolidData& data,
468 Handle(Geom_Surface)& surface,
469 const TopoDS_Face& F,
470 SMESH_MesherHelper& helper);
471 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
472 bool refine(_SolidData& data);
474 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
475 SMESH_MesherHelper& helper,
476 const SMESHDS_SubMesh* faceSubMesh );
477 void fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper);
478 bool addBoundaryElements();
480 bool error( const string& text, int solidID=-1 );
481 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
484 void makeGroupOfLE();
487 SMESH_ComputeErrorPtr _error;
489 vector< _SolidData > _sdVec;
490 set<TGeomID> _ignoreShapeIds;
493 //--------------------------------------------------------------------------------
495 * \brief Shrinker of nodes on the EDGE
499 vector<double> _initU;
500 vector<double> _normPar;
501 vector<const SMDS_MeshNode*> _nodes;
502 const _LayerEdge* _edges[2];
505 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
506 void Compute(bool set3D, SMESH_MesherHelper& helper);
507 void RestoreParams();
508 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
510 //--------------------------------------------------------------------------------
512 * \brief Class of temporary mesh face.
513 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
514 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
516 struct TmpMeshFace : public SMDS_MeshElement
518 vector<const SMDS_MeshNode* > _nn;
519 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
520 SMDS_MeshElement(id), _nn(nodes) {}
521 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
522 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
523 virtual vtkIdType GetVtkType() const { return -1; }
524 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
525 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const
526 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
528 //--------------------------------------------------------------------------------
530 * \brief Class of temporary mesh face storing _LayerEdge it's based on
532 struct TmpMeshFaceOnEdge : public TmpMeshFace
534 _LayerEdge *_le1, *_le2;
535 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
536 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
538 _nn[0]=_le1->_nodes[0];
539 _nn[1]=_le1->_nodes.back();
540 _nn[2]=_le2->_nodes.back();
541 _nn[3]=_le2->_nodes[0];
544 } // namespace VISCOUS
546 //================================================================================
547 // StdMeshers_ViscousLayers hypothesis
549 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
550 :SMESH_Hypothesis(hypId, studyId, gen),
551 _nbLayers(1), _thickness(1), _stretchFactor(1)
553 _name = StdMeshers_ViscousLayers::GetHypType();
554 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
555 } // --------------------------------------------------------------------------------
556 void StdMeshers_ViscousLayers::SetIgnoreFaces(const std::vector<int>& faceIds)
558 if ( faceIds != _ignoreFaceIds )
559 _ignoreFaceIds = faceIds, NotifySubMeshesHypothesisModification();
560 } // --------------------------------------------------------------------------------
561 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
563 if ( thickness != _thickness )
564 _thickness = thickness, NotifySubMeshesHypothesisModification();
565 } // --------------------------------------------------------------------------------
566 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
568 if ( _nbLayers != nb )
569 _nbLayers = nb, NotifySubMeshesHypothesisModification();
570 } // --------------------------------------------------------------------------------
571 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
573 if ( _stretchFactor != factor )
574 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
575 } // --------------------------------------------------------------------------------
577 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
578 const TopoDS_Shape& theShape,
579 const bool toMakeN2NMap) const
581 using namespace VISCOUS;
582 _ViscousBuilder bulder;
583 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
584 if ( err && !err->IsOK() )
585 return SMESH_ProxyMesh::Ptr();
587 vector<SMESH_ProxyMesh::Ptr> components;
588 TopExp_Explorer exp( theShape, TopAbs_SOLID );
589 for ( ; exp.More(); exp.Next() )
591 if ( _MeshOfSolid* pm =
592 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
594 if ( toMakeN2NMap && !pm->_n2nMapComputed )
595 if ( !bulder.MakeN2NMap( pm ))
596 return SMESH_ProxyMesh::Ptr();
597 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
598 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
600 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
602 switch ( components.size() )
606 case 1: return components[0];
608 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
610 return SMESH_ProxyMesh::Ptr();
611 } // --------------------------------------------------------------------------------
612 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
614 save << " " << _nbLayers
616 << " " << _stretchFactor
617 << " " << _ignoreFaceIds.size();
618 for ( unsigned i = 0; i < _ignoreFaceIds.size(); ++i )
619 save << " " << _ignoreFaceIds[i];
621 } // --------------------------------------------------------------------------------
622 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
625 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
626 while ( _ignoreFaceIds.size() < nbFaces && load >> faceID )
627 _ignoreFaceIds.push_back( faceID );
629 } // --------------------------------------------------------------------------------
630 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
631 const TopoDS_Shape& theShape)
636 // END StdMeshers_ViscousLayers hypothesis
637 //================================================================================
641 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
645 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
646 gp_Pnt p = BRep_Tool::Pnt( fromV );
647 double distF = p.SquareDistance( c->Value( f ));
648 double distL = p.SquareDistance( c->Value( l ));
649 c->D1(( distF < distL ? f : l), p, dir );
650 if ( distL < distF ) dir.Reverse();
653 //--------------------------------------------------------------------------------
654 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
655 SMESH_MesherHelper& helper)
658 double f,l; gp_Pnt p;
659 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
660 double u = helper.GetNodeU( E, atNode );
664 //--------------------------------------------------------------------------------
665 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
666 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
668 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
669 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
670 gp_Pnt p; gp_Vec du, dv, norm;
671 surface->D1( uv.X(),uv.Y(), p, du,dv );
675 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
676 double u = helper.GetNodeU( fromE, node, 0, &ok );
678 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
679 if ( o == TopAbs_REVERSED )
682 gp_Vec dir = norm ^ du;
684 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
685 helper.IsClosedEdge( fromE ))
687 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
688 else c->D1( f, p, dv );
689 if ( o == TopAbs_REVERSED )
691 gp_Vec dir2 = norm ^ dv;
692 dir = dir.Normalized() + dir2.Normalized();
696 //--------------------------------------------------------------------------------
697 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
698 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
699 bool& ok, double* cosin=0)
701 double f,l; TopLoc_Location loc;
702 vector< TopoDS_Edge > edges; // sharing a vertex
703 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
706 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
707 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
708 edges.push_back( *e );
711 if ( !( ok = ( edges.size() > 0 ))) return dir;
712 // get average dir of edges going fromV
714 for ( unsigned i = 0; i < edges.size(); ++i )
716 edgeDir = getEdgeDir( edges[i], fromV );
717 double size2 = edgeDir.SquareMagnitude();
718 if ( size2 > numeric_limits<double>::min() )
719 edgeDir /= sqrt( size2 );
722 dir += edgeDir.XYZ();
724 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
725 if ( edges.size() == 1 || dir.SquareModulus() < 1e-10)
727 else if ( dir * fromEdgeDir < 0 )
731 //dir /= edges.size();
733 double angle = edgeDir.Angle( dir );
734 *cosin = cos( angle );
739 //================================================================================
741 * \brief Returns true if a FACE is bound by a concave EDGE
743 //================================================================================
745 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
749 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
750 for ( ; eExp.More(); eExp.Next() )
752 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
753 if ( BRep_Tool::Degenerated( E )) continue;
754 // check if 2D curve is concave
755 BRepAdaptor_Curve2d curve( E, F );
756 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
757 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
758 curve.Intervals( intervals, GeomAbs_C2 );
759 bool isConvex = true;
760 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
762 double u1 = intervals( i );
763 double u2 = intervals( i+1 );
764 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
765 double cross = drv2 ^ drv1;
766 if ( E.Orientation() == TopAbs_REVERSED )
768 isConvex = ( cross < 1e-9 );
770 // check if concavity is strong enough to care about it
771 //const double maxAngle = 5 * Standard_PI180;
774 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
776 // map< double, const SMDS_MeshNode* > u2nodes;
777 // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
778 // /*ignoreMedium=*/true, u2nodes))
780 // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
781 // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
782 // double uPrev = u2n->first;
783 // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
785 // gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
786 // gp_Vec2d segmentDir( uvPrev, uv );
787 // curve.D1( uPrev, p, drv1 );
789 // if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
794 // uPrev = u2n->first;
800 //--------------------------------------------------------------------------------
801 // DEBUG. Dump intermediate node positions into a python script
806 const char* fname = "/tmp/viscous.py";
807 cout << "execfile('"<<fname<<"')"<<endl;
808 py = new ofstream(fname);
809 *py << "from smesh import *" << endl
810 << "meshSO = GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
811 << "mesh = Mesh( meshSO.GetObject() )"<<endl;
815 *py << "mesh.MakeGroup('Viscous Prisms',VOLUME,FT_ElemGeomType,'=',Geom_PENTA)"<<endl;
818 ~PyDump() { Finish(); }
820 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
821 #define dumpMove(n) { _dumpMove(n, __LINE__);}
822 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
823 void _dumpFunction(const string& fun, int ln)
824 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
825 void _dumpMove(const SMDS_MeshNode* n, int ln)
826 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
827 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
828 void _dumpCmd(const string& txt, int ln)
829 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
830 void dumpFunctionEnd()
831 { if (py) *py<< " return"<< endl; }
832 void dumpChangeNodes( const SMDS_MeshElement* f )
833 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
834 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
835 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
837 struct PyDump { void Finish() {} };
838 #define dumpFunction(f) f
841 #define dumpFunctionEnd()
842 #define dumpChangeNodes(f)
846 using namespace VISCOUS;
848 //================================================================================
850 * \brief Constructor of _ViscousBuilder
852 //================================================================================
854 _ViscousBuilder::_ViscousBuilder()
856 _error = SMESH_ComputeError::New(COMPERR_OK);
860 //================================================================================
862 * \brief Stores error description and returns false
864 //================================================================================
866 bool _ViscousBuilder::error(const string& text, int solidId )
868 _error->myName = COMPERR_ALGO_FAILED;
869 _error->myComment = string("Viscous layers builder: ") + text;
872 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
873 if ( !sm && !_sdVec.empty() )
874 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
875 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
877 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
878 if ( smError && smError->myAlgo )
879 _error->myAlgo = smError->myAlgo;
883 makeGroupOfLE(); // debug
888 //================================================================================
890 * \brief At study restoration, restore event listeners used to clear an inferior
891 * dim sub-mesh modified by viscous layers
893 //================================================================================
895 void _ViscousBuilder::RestoreListeners()
900 //================================================================================
902 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
904 //================================================================================
906 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
908 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
909 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
910 for ( ; fExp.More(); fExp.Next() )
912 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
913 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
915 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
917 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
920 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
921 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
923 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
924 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
925 while( prxIt->more() )
927 const SMDS_MeshElement* fSrc = srcIt->next();
928 const SMDS_MeshElement* fPrx = prxIt->next();
929 if ( fSrc->NbNodes() != fPrx->NbNodes())
930 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
931 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
932 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
935 pm->_n2nMapComputed = true;
939 //================================================================================
941 * \brief Does its job
943 //================================================================================
945 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
946 const TopoDS_Shape& theShape)
948 // TODO: set priority of solids during Gen::Compute()
952 // check if proxy mesh already computed
953 TopExp_Explorer exp( theShape, TopAbs_SOLID );
955 return error("No SOLID's in theShape"), _error;
957 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
958 return SMESH_ComputeErrorPtr(); // everything already computed
962 // TODO: ignore already computed SOLIDs
963 if ( !findSolidsWithLayers())
966 if ( !findFacesWithLayers() )
969 for ( unsigned i = 0; i < _sdVec.size(); ++i )
971 if ( ! makeLayer(_sdVec[i]) )
974 if ( ! inflate(_sdVec[i]) )
977 if ( ! refine(_sdVec[i]) )
983 addBoundaryElements();
985 makeGroupOfLE(); // debug
991 //================================================================================
993 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
995 //================================================================================
997 bool _ViscousBuilder::findSolidsWithLayers()
1000 TopTools_IndexedMapOfShape allSolids;
1001 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1002 _sdVec.reserve( allSolids.Extent());
1004 SMESH_Gen* gen = _mesh->GetGen();
1005 for ( int i = 1; i <= allSolids.Extent(); ++i )
1007 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1008 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1009 if ( !algo ) continue;
1010 // TODO: check if algo is hidden
1011 const list <const SMESHDS_Hypothesis *> & allHyps =
1012 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1013 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1014 const StdMeshers_ViscousLayers* viscHyp = 0;
1015 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1016 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1019 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1022 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, proxyMesh ));
1023 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1026 if ( _sdVec.empty() )
1028 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1033 //================================================================================
1037 //================================================================================
1039 bool _ViscousBuilder::findFacesWithLayers()
1041 // collect all faces to ignore defined by hyp
1042 vector<TopoDS_Shape> ignoreFaces;
1043 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1045 vector<TGeomID> ids = _sdVec[i]._hyp->GetIgnoreFaces();
1046 for ( unsigned i = 0; i < ids.size(); ++i )
1048 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
1049 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1051 _ignoreShapeIds.insert( ids[i] );
1052 ignoreFaces.push_back( s );
1057 // ignore internal faces
1058 SMESH_MesherHelper helper( *_mesh );
1059 TopExp_Explorer exp;
1060 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1062 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1063 for ( ; exp.More(); exp.Next() )
1065 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1066 if ( helper.NbAncestors( exp.Current(), *_mesh, TopAbs_SOLID ) > 1 )
1068 _ignoreShapeIds.insert( faceInd );
1069 ignoreFaces.push_back( exp.Current() );
1070 if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face( exp.Current() ), getMeshDS()))
1071 _sdVec[i]._reversedFaceIds.insert( faceInd );
1076 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1077 TopTools_IndexedMapOfShape shapes;
1078 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1081 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1082 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1084 const TopoDS_Shape& edge = shapes(iE);
1085 // find 2 faces sharing an edge
1087 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1088 while ( fIt->more())
1090 const TopoDS_Shape* f = fIt->next();
1091 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1092 FF[ int( !FF[0].IsNull()) ] = *f;
1094 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1095 // check presence of layers on them
1097 for ( int j = 0; j < 2; ++j )
1098 ignore[j] = _ignoreShapeIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1099 if ( ignore[0] == ignore[1] ) continue; // nothing interesting
1100 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1102 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1103 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1106 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1107 // the algo of the SOLID sharing the FACE does not support it
1108 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1109 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1111 TopTools_MapOfShape noShrinkVertices;
1112 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1113 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1115 const TopoDS_Shape& fWOL = e2f->second;
1116 TGeomID edgeID = e2f->first;
1117 bool notShrinkFace = false;
1118 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1119 while ( soIt->more())
1121 const TopoDS_Shape* solid = soIt->next();
1122 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1123 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1124 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1125 notShrinkFace = true;
1126 for ( unsigned j = 0; j < _sdVec.size(); ++j )
1128 if ( _sdVec[j]._solid.IsSame( *solid ) )
1129 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1130 notShrinkFace = false;
1133 if ( notShrinkFace )
1135 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1136 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1137 noShrinkVertices.Add( vExp.Current() );
1140 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1141 // to the found not shrinked fWOL's
1142 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1143 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1145 TGeomID edgeID = e2f->first;
1146 TopoDS_Vertex VV[2];
1147 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1148 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1150 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1151 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1160 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1162 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1165 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1166 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1168 const TopoDS_Shape& vertex = shapes(iV);
1169 // find faces WOL sharing the vertex
1170 vector< TopoDS_Shape > facesWOL;
1171 int totalNbFaces = 0;
1172 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1173 while ( fIt->more())
1175 const TopoDS_Shape* f = fIt->next();
1176 const int fID = getMeshDS()->ShapeToIndex( *f );
1177 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1180 if ( _ignoreShapeIds.count ( fID ) && ! _sdVec[i]._noShrinkFaces.count( fID ))
1181 facesWOL.push_back( *f );
1184 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1185 continue; // no layers at this vertex or no WOL
1186 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1187 switch ( facesWOL.size() )
1191 helper.SetSubShape( facesWOL[0] );
1192 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1194 TopoDS_Shape seamEdge;
1195 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1196 while ( eIt->more() && seamEdge.IsNull() )
1198 const TopoDS_Shape* e = eIt->next();
1199 if ( helper.IsRealSeam( *e ) )
1202 if ( !seamEdge.IsNull() )
1204 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1208 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1213 // find an edge shared by 2 faces
1214 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1215 while ( eIt->more())
1217 const TopoDS_Shape* e = eIt->next();
1218 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1219 helper.IsSubShape( *e, facesWOL[1]))
1221 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1227 return error("Not yet supported case", _sdVec[i]._index);
1235 //================================================================================
1237 * \brief Create the inner surface of the viscous layer and prepare data for infation
1239 //================================================================================
1241 bool _ViscousBuilder::makeLayer(_SolidData& data)
1243 // get all sub-shapes to make layers on
1244 set<TGeomID> subIds, faceIds;
1245 subIds = data._noShrinkFaces;
1246 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1247 for ( ; exp.More(); exp.Next() )
1248 if ( ! _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1250 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1251 faceIds.insert( fSubM->GetId() );
1252 SMESH_subMeshIteratorPtr subIt =
1253 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1254 while ( subIt->more() )
1255 subIds.insert( subIt->next()->GetId() );
1258 // make a map to find new nodes on sub-shapes shared with other SOLID
1259 map< TGeomID, TNode2Edge* > s2neMap;
1260 map< TGeomID, TNode2Edge* >::iterator s2ne;
1261 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1262 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1264 TGeomID shapeInd = s2s->first;
1265 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1267 if ( _sdVec[i]._index == data._index ) continue;
1268 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1269 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1270 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1272 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1278 // Create temporary faces and _LayerEdge's
1280 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1282 data._stepSize = Precision::Infinite();
1283 data._stepSizeNodes[0] = 0;
1285 SMESH_MesherHelper helper( *_mesh );
1286 helper.SetSubShape( data._solid );
1287 helper.SetElementsOnShape(true);
1289 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1290 TNode2Edge::iterator n2e2;
1292 // collect _LayerEdge's of shapes they are based on
1293 const int nbShapes = getMeshDS()->MaxShapeIndex();
1294 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1296 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1298 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1299 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1301 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1302 SMESH_ProxyMesh::SubMesh* proxySub =
1303 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1305 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1306 while ( eIt->more() )
1308 const SMDS_MeshElement* face = eIt->next();
1309 newNodes.resize( face->NbCornerNodes() );
1310 double faceMaxCosin = -1;
1311 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1313 const SMDS_MeshNode* n = face->GetNode(i);
1314 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1315 if ( !(*n2e).second )
1318 _LayerEdge* edge = new _LayerEdge();
1320 edge->_nodes.push_back( n );
1321 const int shapeID = n->getshapeId();
1322 edgesByGeom[ shapeID ].push_back( edge );
1324 // set edge data or find already refined _LayerEdge and get data from it
1325 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1326 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1327 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1329 _LayerEdge* foundEdge = (*n2e2).second;
1330 edge->Copy( *foundEdge, helper );
1331 // location of the last node is modified but we can restore
1332 // it by node position on _sWOL stored by the node
1333 const_cast< SMDS_MeshNode* >
1334 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1338 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1339 if ( !setEdgeData( *edge, subIds, helper, data ))
1342 dumpMove(edge->_nodes.back());
1343 if ( edge->_cosin > 0.01 )
1345 if ( edge->_cosin > faceMaxCosin )
1346 faceMaxCosin = edge->_cosin;
1349 newNodes[ i ] = n2e->second->_nodes.back();
1351 // create a temporary face
1352 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1353 proxySub->AddElement( newFace );
1355 // compute inflation step size by min size of element on a convex surface
1356 if ( faceMaxCosin > 0.1 )
1357 limitStepSize( data, face, faceMaxCosin );
1358 } // loop on 2D elements on a FACE
1359 } // loop on FACEs of a SOLID
1361 data._epsilon = 1e-7;
1362 if ( data._stepSize < 1. )
1363 data._epsilon *= data._stepSize;
1365 // Put _LayerEdge's into a vector
1367 if ( !sortEdges( data, edgesByGeom ))
1370 // Set target nodes into _Simplex and _2NearEdges
1371 TNode2Edge::iterator n2e;
1372 for ( unsigned i = 0; i < data._edges.size(); ++i )
1374 if ( data._edges[i]->IsOnEdge())
1375 for ( int j = 0; j < 2; ++j )
1377 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1378 break; // _LayerEdge is shared by two _SolidData's
1379 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1380 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1381 return error("_LayerEdge not found by src node", data._index);
1382 n = (*n2e).second->_nodes.back();
1383 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1386 for ( unsigned j = 0; j < data._edges[i]->_simplices.size(); ++j )
1388 _Simplex& s = data._edges[i]->_simplices[j];
1389 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1390 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1398 //================================================================================
1400 * \brief Compute inflation step size by min size of element on a convex surface
1402 //================================================================================
1404 void _ViscousBuilder::limitStepSize( _SolidData& data,
1405 const SMDS_MeshElement* face,
1409 double minSize = 10 * data._stepSize;
1410 const int nbNodes = face->NbCornerNodes();
1411 for ( int i = 0; i < nbNodes; ++i )
1413 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1414 const SMDS_MeshNode* curN = face->GetNode( i );
1415 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1416 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1418 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1419 if ( dist < minSize )
1420 minSize = dist, iN = i;
1423 double newStep = 0.8 * minSize / cosin;
1424 if ( newStep < data._stepSize )
1426 data._stepSize = newStep;
1427 data._stepSizeCoeff = 0.8 / cosin;
1428 data._stepSizeNodes[0] = face->GetNode( iN );
1429 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1433 //================================================================================
1435 * \brief Compute inflation step size by min size of element on a convex surface
1437 //================================================================================
1439 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1441 if ( minSize < data._stepSize )
1443 data._stepSize = minSize;
1444 if ( data._stepSizeNodes[0] )
1447 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1448 data._stepSizeCoeff = data._stepSize / dist;
1453 //================================================================================
1455 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1457 //================================================================================
1459 bool _ViscousBuilder::sortEdges( _SolidData& data,
1460 vector< vector<_LayerEdge*> >& edgesByGeom)
1462 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1463 // boundry inclined at a sharp angle to the shape
1465 list< TGeomID > shapesToSmooth;
1467 SMESH_MesherHelper helper( *_mesh );
1470 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1472 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1473 if ( eS.empty() ) continue;
1474 TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1475 bool needSmooth = false;
1476 switch ( S.ShapeType() )
1480 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1481 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1483 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1484 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1485 if ( eV.empty() ) continue;
1486 double cosin = eV[0]->_cosin;
1488 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1492 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1493 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1495 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1496 eV[0]->_nodes[0], helper, ok);
1497 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1498 double angle = dir1.Angle( dir2 );
1499 cosin = cos( angle );
1501 needSmooth = ( cosin > 0.1 );
1507 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1509 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1510 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1511 if ( eE.empty() ) continue;
1512 if ( eE[0]->_sWOL.IsNull() )
1514 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1515 needSmooth = ( eE[i]->_cosin > 0.1 );
1519 const TopoDS_Face& F1 = TopoDS::Face( S );
1520 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1521 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1522 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1524 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1525 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1526 double angle = dir1.Angle( dir2 );
1527 double cosin = cos( angle );
1528 needSmooth = ( cosin > 0.1 );
1540 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1541 else shapesToSmooth.push_back ( iS );
1544 } // loop on edgesByGeom
1546 data._edges.reserve( data._n2eMap.size() );
1547 data._endEdgeToSmooth.clear();
1549 // first we put _LayerEdge's on shapes to smooth
1550 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1551 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1553 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1554 if ( eVec.empty() ) continue;
1555 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1556 data._endEdgeToSmooth.push_back( data._edges.size() );
1560 // then the rest _LayerEdge's
1561 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1563 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1564 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1571 //================================================================================
1573 * \brief Set data of _LayerEdge needed for smoothing
1574 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1576 //================================================================================
1578 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1579 const set<TGeomID>& subIds,
1580 SMESH_MesherHelper& helper,
1583 SMESH_MeshEditor editor(_mesh);
1585 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1586 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1590 edge._curvature = 0;
1592 // --------------------------
1593 // Compute _normal and _cosin
1594 // --------------------------
1597 edge._normal.SetCoord(0,0,0);
1599 int totalNbFaces = 0;
1601 gp_Vec du, dv, geomNorm;
1604 TGeomID shapeInd = node->getshapeId();
1605 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1606 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1607 TopoDS_Shape vertEdge;
1609 if ( onShrinkShape ) // one of faces the node is on has no layers
1611 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1612 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1614 // inflate from VERTEX along EDGE
1615 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1617 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1619 // inflate from VERTEX along FACE
1620 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1621 node, helper, normOK, &edge._cosin);
1625 // inflate from EDGE along FACE
1626 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1627 node, helper, normOK);
1630 else // layers are on all faces of SOLID the node is on
1632 // find indices of geom faces the node lies on
1633 set<TGeomID> faceIds;
1634 if ( posType == SMDS_TOP_FACE )
1636 faceIds.insert( node->getshapeId() );
1640 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1641 while ( fIt->more() )
1642 faceIds.insert( editor.FindShape(fIt->next()));
1645 set<TGeomID>::iterator id = faceIds.begin();
1647 for ( ; id != faceIds.end(); ++id )
1649 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1650 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1653 //nbLayerFaces += subIds.count( *id );
1654 F = TopoDS::Face( s );
1656 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1657 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1658 surface->D1( uv.X(),uv.Y(), p, du,dv );
1660 double size2 = geomNorm.SquareMagnitude();
1661 if ( size2 > numeric_limits<double>::min() )
1662 geomNorm /= sqrt( size2 );
1665 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1667 edge._normal += geomNorm.XYZ();
1669 if ( totalNbFaces == 0 )
1670 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1672 edge._normal /= totalNbFaces;
1677 edge._cosin = 0; break;
1679 case SMDS_TOP_EDGE: {
1680 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1681 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1682 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1683 edge._cosin = cos( angle );
1684 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1687 case SMDS_TOP_VERTEX: {
1688 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1689 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK);
1690 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1691 edge._cosin = cos( angle );
1692 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1696 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1700 double normSize = edge._normal.SquareModulus();
1701 if ( normSize < numeric_limits<double>::min() )
1702 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1704 edge._normal /= sqrt( normSize );
1706 // TODO: if ( !normOK ) then get normal by mesh faces
1708 // Set the rest data
1709 // --------------------
1710 if ( onShrinkShape )
1712 edge._sWOL = (*s2s).second;
1714 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1715 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1716 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1718 // set initial position which is parameters on _sWOL in this case
1719 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1721 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1722 edge._pos.push_back( gp_XYZ( u, 0, 0));
1723 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1727 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1728 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1729 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1734 edge._pos.push_back( SMESH_TNodeXYZ( node ));
1736 if ( posType == SMDS_TOP_FACE )
1738 getSimplices( node, edge._simplices, _ignoreShapeIds, &data );
1739 double avgNormProj = 0, avgLen = 0;
1740 for ( unsigned i = 0; i < edge._simplices.size(); ++i )
1742 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
1743 avgNormProj += edge._normal * vec;
1744 avgLen += vec.Modulus();
1746 avgNormProj /= edge._simplices.size();
1747 avgLen /= edge._simplices.size();
1748 edge._curvature = _Curvature::New( avgNormProj, avgLen );
1752 // Set neighbour nodes for a _LayerEdge based on EDGE
1754 if ( posType == SMDS_TOP_EDGE /*||
1755 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1757 edge._2neibors = new _2NearEdges;
1758 // target node instead of source ones will be set later
1759 if ( ! findNeiborsOnEdge( &edge,
1760 edge._2neibors->_nodes[0],
1761 edge._2neibors->_nodes[1],
1764 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1765 edge._2neibors->_nodes[1],
1769 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1774 //================================================================================
1776 * \brief Find 2 neigbor nodes of a node on EDGE
1778 //================================================================================
1780 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
1781 const SMDS_MeshNode*& n1,
1782 const SMDS_MeshNode*& n2,
1785 const SMDS_MeshNode* node = edge->_nodes[0];
1786 const int shapeInd = node->getshapeId();
1787 SMESHDS_SubMesh* edgeSM = 0;
1788 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
1791 edgeSM = getMeshDS()->MeshElements( shapeInd );
1792 if ( !edgeSM || edgeSM->NbElements() == 0 )
1793 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
1797 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
1798 while ( eIt->more() && !n2 )
1800 const SMDS_MeshElement* e = eIt->next();
1801 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
1802 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
1805 if (!edgeSM->Contains(e)) continue;
1809 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
1810 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
1812 ( iN++ ? n2 : n1 ) = nNeibor;
1815 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
1819 //================================================================================
1821 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
1823 //================================================================================
1825 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
1826 const SMDS_MeshNode* n2,
1827 SMESH_MesherHelper& helper)
1829 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1832 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
1833 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
1834 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
1838 double sumLen = vec1.Modulus() + vec2.Modulus();
1839 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
1840 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
1841 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
1842 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
1843 if ( _curvature ) delete _curvature;
1844 _curvature = _Curvature::New( avgNormProj, avgLen );
1846 // if ( _curvature )
1847 // cout << _nodes[0]->GetID()
1848 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
1849 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
1850 // << _curvature->lenDelta(0) << endl;
1855 if ( _sWOL.IsNull() )
1857 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
1858 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
1859 gp_XYZ plnNorm = dirE ^ _normal;
1860 double proj0 = plnNorm * vec1;
1861 double proj1 = plnNorm * vec2;
1862 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
1864 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
1865 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
1870 //================================================================================
1872 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
1873 * this and other _LayerEdge's are inflated along a FACE or an EDGE
1875 //================================================================================
1877 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
1879 _nodes = other._nodes;
1880 _normal = other._normal;
1882 _lenFactor = other._lenFactor;
1883 _cosin = other._cosin;
1884 _sWOL = other._sWOL;
1885 _2neibors = other._2neibors;
1886 _curvature = 0; std::swap( _curvature, other._curvature );
1887 _2neibors = 0; std::swap( _2neibors, other._2neibors );
1889 if ( _sWOL.ShapeType() == TopAbs_EDGE )
1891 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
1892 _pos.push_back( gp_XYZ( u, 0, 0));
1896 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
1897 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1901 //================================================================================
1903 * \brief Set _cosin and _lenFactor
1905 //================================================================================
1907 void _LayerEdge::SetCosin( double cosin )
1910 _lenFactor = ( _cosin > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
1913 //================================================================================
1915 * \brief Fills a vector<_Simplex >
1917 //================================================================================
1919 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
1920 vector<_Simplex>& simplices,
1921 const set<TGeomID>& ingnoreShapes,
1922 const _SolidData* dataToCheckOri,
1925 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1926 while ( fIt->more() )
1928 const SMDS_MeshElement* f = fIt->next();
1929 const TGeomID shapeInd = f->getshapeId();
1930 if ( ingnoreShapes.count( shapeInd )) continue;
1931 const int nbNodes = f->NbCornerNodes();
1932 int srcInd = f->GetNodeIndex( node );
1933 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
1934 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
1935 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
1936 std::swap( nPrev, nNext );
1937 simplices.push_back( _Simplex( nPrev, nNext ));
1942 vector<_Simplex> sortedSimplices( simplices.size() );
1943 sortedSimplices[0] = simplices[0];
1945 for ( size_t i = 1; i < simplices.size(); ++i )
1947 for ( size_t j = 1; j < simplices.size(); ++j )
1948 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
1950 sortedSimplices[i] = simplices[j];
1955 if ( nbFound == simplices.size() - 1 )
1956 simplices.swap( sortedSimplices );
1960 //================================================================================
1962 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
1964 //================================================================================
1966 void _ViscousBuilder::makeGroupOfLE()
1969 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
1971 if ( _sdVec[i]._edges.empty() ) continue;
1972 // string name = SMESH_Comment("_LayerEdge's_") << i;
1974 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
1975 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
1976 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
1978 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
1979 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1981 _LayerEdge* le = _sdVec[i]._edges[j];
1982 for ( unsigned iN = 1; iN < le->_nodes.size(); ++iN )
1983 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
1984 << ", " << le->_nodes[iN]->GetID() <<"])");
1985 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
1989 dumpFunction( SMESH_Comment("makeNormals") << i );
1990 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1992 _LayerEdge& edge = *_sdVec[i]._edges[j];
1993 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
1994 nXYZ += edge._normal * _sdVec[i]._stepSize;
1995 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
1996 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2000 // name = SMESH_Comment("tmp_faces ") << i;
2001 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2002 // gDS = (SMESHDS_Group*)g->GetGroupDS();
2003 // SMESH_MeshEditor editor( _mesh );
2004 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2005 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2006 for ( ; fExp.More(); fExp.Next() )
2008 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2010 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2011 while ( fIt->more())
2013 const SMDS_MeshElement* e = fIt->next();
2014 SMESH_Comment cmd("mesh.AddFace([");
2015 for ( int j=0; j < e->NbCornerNodes(); ++j )
2016 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2018 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2019 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2028 //================================================================================
2030 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2032 //================================================================================
2034 bool _ViscousBuilder::inflate(_SolidData& data)
2036 SMESH_MesherHelper helper( *_mesh );
2038 // Limit inflation step size by geometry size found by itersecting
2039 // normals of _LayerEdge's with mesh faces
2040 double geomSize = Precision::Infinite(), intersecDist;
2041 SMESH_MeshEditor editor( _mesh );
2042 auto_ptr<SMESH_ElementSearcher> searcher
2043 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2044 for ( unsigned i = 0; i < data._edges.size(); ++i )
2046 if ( data._edges[i]->IsOnEdge() ) continue;
2047 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2048 if ( geomSize > intersecDist )
2049 geomSize = intersecDist;
2051 if ( data._stepSize > 0.3 * geomSize )
2052 limitStepSize( data, 0.3 * geomSize );
2054 const double tgtThick = data._hyp->GetTotalThickness();
2055 if ( data._stepSize > tgtThick )
2056 limitStepSize( data, tgtThick );
2058 if ( data._stepSize < 1. )
2059 data._epsilon = data._stepSize * 1e-7;
2062 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2065 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2066 int nbSteps = 0, nbRepeats = 0;
2067 while ( 1.01 * avgThick < tgtThick )
2069 // new target length
2070 curThick += data._stepSize;
2071 if ( curThick > tgtThick )
2073 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2077 // Elongate _LayerEdge's
2078 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2079 for ( unsigned i = 0; i < data._edges.size(); ++i )
2081 data._edges[i]->SetNewLength( curThick, helper );
2086 if ( !updateNormals( data, helper ) )
2089 // Improve and check quality
2090 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2094 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2095 for ( unsigned i = 0; i < data._edges.size(); ++i )
2097 data._edges[i]->InvalidateStep( nbSteps+1 );
2101 break; // no more inflating possible
2105 // Evaluate achieved thickness
2107 for ( unsigned i = 0; i < data._edges.size(); ++i )
2108 avgThick += data._edges[i]->_len;
2109 avgThick /= data._edges.size();
2111 cout << "-- Thickness " << avgThick << " reached" << endl;
2114 if ( distToIntersection < avgThick*1.5 )
2117 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2118 << avgThick << " ) * 1.5" << endl;
2123 limitStepSize( data, 0.25 * distToIntersection );
2124 if ( data._stepSizeNodes[0] )
2125 data._stepSize = data._stepSizeCoeff *
2126 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2130 return error("failed at the very first inflation step", data._index);
2135 //================================================================================
2137 * \brief Improve quality of layer inner surface and check intersection
2139 //================================================================================
2141 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2143 double & distToIntersection)
2145 if ( data._endEdgeToSmooth.empty() )
2146 return true; // no shapes needing smoothing
2148 bool moved, improved;
2150 SMESH_MesherHelper helper(*_mesh);
2151 Handle(Geom_Surface) surface;
2155 for ( unsigned iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2158 iEnd = data._endEdgeToSmooth[ iS ];
2160 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2161 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2163 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2164 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2165 helper.SetSubShape( F );
2166 surface = BRep_Tool::Surface( F );
2171 F.Nullify(); surface.Nullify();
2173 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2175 if ( data._edges[ iBeg ]->IsOnEdge() )
2177 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2179 // try a simple solution on an analytic EDGE
2180 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2186 for ( int i = iBeg; i < iEnd; ++i )
2188 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2190 dumpCmd( SMESH_Comment("# end step ")<<step);
2192 while ( moved && step++ < 5 );
2193 //cout << " NB STEPS: " << step << endl;
2200 int step = 0, badNb = 0; moved = true;
2201 while (( ++step <= 5 && moved ) || improved )
2203 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2204 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2205 int oldBadNb = badNb;
2208 for ( int i = iBeg; i < iEnd; ++i )
2209 moved |= data._edges[i]->Smooth(badNb);
2210 improved = ( badNb < oldBadNb );
2217 for ( int i = iBeg; i < iEnd; ++i )
2219 _LayerEdge* edge = data._edges[i];
2220 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2221 for ( unsigned j = 0; j < edge->_simplices.size(); ++j )
2222 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2224 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2225 << " "<< edge->_simplices[j]._nPrev->GetID()
2226 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2234 } // loop on shapes to smooth
2236 // Check if the last segments of _LayerEdge intersects 2D elements;
2237 // checked elements are either temporary faces or faces on surfaces w/o the layers
2239 SMESH_MeshEditor editor( _mesh );
2240 auto_ptr<SMESH_ElementSearcher> searcher
2241 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2243 distToIntersection = Precision::Infinite();
2245 const SMDS_MeshElement* intFace = 0;
2247 const SMDS_MeshElement* closestFace = 0;
2250 for ( unsigned i = 0; i < data._edges.size(); ++i )
2252 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2254 if ( distToIntersection > dist )
2256 distToIntersection = dist;
2259 closestFace = intFace;
2266 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2267 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2268 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2269 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2270 << ") distance = " << distToIntersection<< endl;
2277 //================================================================================
2279 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2280 * _LayerEdge's to be in a consequent order
2282 //================================================================================
2284 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2287 Handle(Geom_Surface)& surface,
2288 const TopoDS_Face& F,
2289 SMESH_MesherHelper& helper)
2291 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2293 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2295 if ( i2curve == _edge2curve.end() )
2297 // sort _LayerEdge's by position on the EDGE
2299 map< double, _LayerEdge* > u2edge;
2300 for ( int i = iFrom; i < iTo; ++i )
2301 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2303 ASSERT( u2edge.size() == iTo - iFrom );
2304 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2305 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2306 _edges[i] = u2e->second;
2308 // set _2neibors according to the new order
2309 for ( int i = iFrom; i < iTo-1; ++i )
2310 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2311 _edges[i]->_2neibors->reverse();
2312 if ( u2edge.size() > 1 &&
2313 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2314 _edges[iTo-1]->_2neibors->reverse();
2317 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2319 TopLoc_Location loc; double f,l;
2321 Handle(Geom_Line) line;
2322 Handle(Geom_Circle) circle;
2323 bool isLine, isCirc;
2324 if ( F.IsNull() ) // 3D case
2326 // check if the EDGE is a line
2327 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2328 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2329 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2331 line = Handle(Geom_Line)::DownCast( curve );
2332 circle = Handle(Geom_Circle)::DownCast( curve );
2333 isLine = (!line.IsNull());
2334 isCirc = (!circle.IsNull());
2336 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2339 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2340 while ( nIt->more() )
2341 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2342 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2344 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2345 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2346 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2347 for ( int i = 0; i < 3 && !isLine; ++i )
2348 isLine = ( size.Coord( i+1 ) <= lineTol );
2350 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2357 // check if the EDGE is a line
2358 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2359 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2360 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2362 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2363 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2364 isLine = (!line2d.IsNull());
2365 isCirc = (!circle2d.IsNull());
2367 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2370 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2371 while ( nIt->more() )
2372 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2373 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2375 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2376 for ( int i = 0; i < 2 && !isLine; ++i )
2377 isLine = ( size.Coord( i+1 ) <= lineTol );
2379 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2385 line = new Geom_Line( gp::OX() ); // only type does matter
2389 gp_Pnt2d p = circle2d->Location();
2390 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2391 circle = new Geom_Circle( ax, 1.); // only center position does matter
2395 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2403 return i2curve->second;
2406 //================================================================================
2408 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2410 //================================================================================
2412 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2415 Handle(Geom_Surface)& surface,
2416 const TopoDS_Face& F,
2417 SMESH_MesherHelper& helper)
2419 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2420 helper.GetMeshDS());
2421 TopoDS_Edge E = TopoDS::Edge( S );
2423 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2424 if ( curve.IsNull() ) return false;
2426 // compute a relative length of segments
2427 vector< double > len( iTo-iFrom+1 );
2429 double curLen, prevLen = len[0] = 1.0;
2430 for ( int i = iFrom; i < iTo; ++i )
2432 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2433 len[i-iFrom+1] = len[i-iFrom] + curLen;
2438 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2440 if ( F.IsNull() ) // 3D
2442 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2443 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2444 for ( int i = iFrom; i < iTo; ++i )
2446 double r = len[i-iFrom] / len.back();
2447 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2448 data._edges[i]->_pos.back() = newPos;
2449 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2450 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2451 dumpMove( tgtNode );
2456 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2457 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2458 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2459 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2461 int iPeriodic = helper.GetPeriodicIndex();
2462 if ( iPeriodic == 1 || iPeriodic == 2 )
2464 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2465 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2466 std::swap( uv0, uv1 );
2469 const gp_XY rangeUV = uv1 - uv0;
2470 for ( int i = iFrom; i < iTo; ++i )
2472 double r = len[i-iFrom] / len.back();
2473 gp_XY newUV = uv0 + r * rangeUV;
2474 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2476 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2477 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2478 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2479 dumpMove( tgtNode );
2481 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2482 pos->SetUParameter( newUV.X() );
2483 pos->SetVParameter( newUV.Y() );
2489 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2491 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2492 gp_Pnt center3D = circle->Location();
2494 if ( F.IsNull() ) // 3D
2496 return false; // TODO ???
2500 const gp_XY center( center3D.X(), center3D.Y() );
2502 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2503 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2504 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2505 gp_Vec2d vec0( center, uv0 );
2506 gp_Vec2d vecM( center, uvM);
2507 gp_Vec2d vec1( center, uv1 );
2508 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2509 double uMidl = vec0.Angle( vecM );
2510 if ( uLast < 0 ) uLast += 2.*M_PI; // 0.0 - 2*PI
2511 if ( uMidl < 0 ) uMidl += 2.*M_PI;
2512 const bool sense = ( uMidl < uLast );
2513 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2515 gp_Ax2d axis( center, vec0 );
2516 gp_Circ2d circ ( axis, radius, sense );
2517 for ( int i = iFrom; i < iTo; ++i )
2519 double newU = uLast * len[i-iFrom] / len.back();
2520 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2521 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2523 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2524 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2525 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2526 dumpMove( tgtNode );
2528 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2529 pos->SetUParameter( newUV.X() );
2530 pos->SetVParameter( newUV.Y() );
2539 //================================================================================
2541 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2542 * _LayerEdge's on neighbor EDGE's
2544 //================================================================================
2546 bool _ViscousBuilder::updateNormals( _SolidData& data,
2547 SMESH_MesherHelper& helper )
2549 // make temporary quadrangles got by extrusion of
2550 // mesh edges along _LayerEdge._normal's
2552 vector< const SMDS_MeshElement* > tmpFaces;
2554 set< SMESH_TLink > extrudedLinks; // contains target nodes
2555 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2557 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2558 for ( unsigned i = 0; i < data._edges.size(); ++i )
2560 _LayerEdge* edge = data._edges[i];
2561 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2562 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2563 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2565 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2566 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2567 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2568 if ( !link_isnew.second )
2570 extrudedLinks.erase( link_isnew.first );
2571 continue; // already extruded and will no more encounter
2573 // look for a _LayerEdge containg tgt2
2574 // _LayerEdge* neiborEdge = 0;
2575 // unsigned di = 0; // check _edges[i+di] and _edges[i-di]
2576 // while ( !neiborEdge && ++di <= data._edges.size() )
2578 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2579 // neiborEdge = data._edges[i+di];
2580 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2581 // neiborEdge = data._edges[i-di];
2583 // if ( !neiborEdge )
2584 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2585 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2587 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2588 tmpFaces.push_back( f );
2590 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2591 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2592 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2597 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2598 // Perform two loops on _LayerEdge on EDGE's:
2599 // 1) to find and fix intersection
2600 // 2) to check that no new intersection appears as result of 1)
2602 SMESH_MeshEditor editor( _mesh );
2603 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2605 auto_ptr<SMESH_ElementSearcher> searcher ( editor.GetElementSearcher( fIt ));
2607 // 1) Find intersections
2609 const SMDS_MeshElement* face;
2610 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2611 TLEdge2LEdgeSet edge2CloseEdge;
2613 const double eps = data._epsilon * data._epsilon;
2614 for ( unsigned i = 0; i < data._edges.size(); ++i )
2616 _LayerEdge* edge = data._edges[i];
2617 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2618 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2620 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2621 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2622 ee.insert( f->_le1 );
2623 ee.insert( f->_le2 );
2624 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
2625 edge2CloseEdge[ f->_le1 ].insert( edge );
2626 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
2627 edge2CloseEdge[ f->_le2 ].insert( edge );
2631 // Set _LayerEdge._normal
2633 if ( !edge2CloseEdge.empty() )
2635 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2637 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2638 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2640 _LayerEdge* edge1 = e2ee->first;
2641 _LayerEdge* edge2 = 0;
2642 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
2644 // find EDGEs the edges reside
2646 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2647 if ( S.ShapeType() != TopAbs_EDGE )
2648 continue; // TODO: find EDGE by VERTEX
2649 E1 = TopoDS::Edge( S );
2650 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
2651 while ( E2.IsNull() && eIt != ee.end())
2653 _LayerEdge* e2 = *eIt++;
2654 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2655 if ( S.ShapeType() == TopAbs_EDGE )
2656 E2 = TopoDS::Edge( S ), edge2 = e2;
2658 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2660 // find 3 FACEs sharing 2 EDGEs
2662 TopoDS_Face FF1[2], FF2[2];
2663 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2664 while ( fIt->more() && FF1[1].IsNull())
2666 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2667 if ( helper.IsSubShape( *F, data._solid))
2668 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2670 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2671 while ( fIt->more() && FF2[1].IsNull())
2673 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2674 if ( helper.IsSubShape( *F, data._solid))
2675 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2677 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2678 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2679 std::swap( FF1[0], FF1[1] );
2680 if ( FF2[0].IsSame( FF1[0]) )
2681 std::swap( FF2[0], FF2[1] );
2682 if ( FF1[0].IsNull() || FF2[0].IsNull() )
2685 // // get a new normal for edge1
2687 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2688 if ( edge1->_cosin < 0 )
2689 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2690 if ( edge2->_cosin < 0 )
2691 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2692 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2693 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2694 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2695 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2696 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2697 // newNorm.Normalize();
2699 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2700 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2701 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2702 newNorm.Normalize();
2704 edge1->_normal = newNorm.XYZ();
2706 // update data of edge1 depending on _normal
2707 const SMDS_MeshNode *n1, *n2;
2708 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2709 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2710 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2712 edge1->SetDataByNeighbors( n1, n2, helper );
2714 if ( edge1->_cosin < 0 )
2717 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2718 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2719 edge1->SetCosin( cos( angle ));
2721 // limit data._stepSize
2722 if ( edge1->_cosin > 0.1 )
2724 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2725 while ( fIt->more() )
2726 limitStepSize( data, fIt->next(), edge1->_cosin );
2728 // set new XYZ of target node
2729 edge1->InvalidateStep( 1 );
2731 edge1->SetNewLength( data._stepSize, helper );
2734 // Update normals and other dependent data of not intersecting _LayerEdge's
2735 // neighboring the intersecting ones
2737 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2739 _LayerEdge* edge1 = e2ee->first;
2740 if ( !edge1->_2neibors )
2742 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2744 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2745 if ( edge2CloseEdge.count ( neighbor ))
2746 continue; // j-th neighbor is also intersected
2747 _LayerEdge* prevEdge = edge1;
2748 const int nbSteps = 6;
2749 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2751 if ( !neighbor->_2neibors )
2752 break; // neighbor is on VERTEX
2754 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2755 if ( nextEdge == prevEdge )
2756 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2757 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2758 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
2759 double r = double(step-1)/nbSteps;
2760 if ( !nextEdge->_2neibors )
2763 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2764 newNorm.Normalize();
2766 neighbor->_normal = newNorm;
2767 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2768 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2770 neighbor->InvalidateStep( 1 );
2772 neighbor->SetNewLength( data._stepSize, helper );
2774 // goto the next neighbor
2775 prevEdge = neighbor;
2776 neighbor = nextEdge;
2782 // 2) Check absence of intersections
2785 for ( unsigned i = 0 ; i < tmpFaces.size(); ++i )
2791 //================================================================================
2793 * \brief Looks for intersection of it's last segment with faces
2794 * \param distance - returns shortest distance from the last node to intersection
2796 //================================================================================
2798 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
2800 const double& epsilon,
2801 const SMDS_MeshElement** face)
2803 vector< const SMDS_MeshElement* > suspectFaces;
2805 gp_Ax1 lastSegment = LastSegment(segLen);
2806 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2808 bool segmentIntersected = false;
2809 distance = Precision::Infinite();
2810 int iFace = -1; // intersected face
2811 for ( unsigned j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
2813 const SMDS_MeshElement* face = suspectFaces[j];
2814 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
2815 face->GetNodeIndex( _nodes[0] ) >= 0 )
2816 continue; // face sharing _LayerEdge node
2817 const int nbNodes = face->NbCornerNodes();
2818 bool intFound = false;
2820 SMDS_MeshElement::iterator nIt = face->begin_nodes();
2823 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
2827 const SMDS_MeshNode* tria[3];
2830 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
2833 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
2839 if ( dist < segLen*(1.01))
2840 segmentIntersected = true;
2841 if ( distance > dist )
2842 distance = dist, iFace = j;
2845 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
2846 // if ( distance && iFace > -1 )
2848 // // distance is used to limit size of inflation step which depends on
2849 // // whether the intersected face bears viscous layers or not
2850 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
2854 if ( segmentIntersected )
2857 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
2858 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
2859 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
2860 << ", intersection with face ("
2861 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2862 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
2863 << ") distance = " << distance - segLen<< endl;
2869 return segmentIntersected;
2872 //================================================================================
2874 * \brief Returns size and direction of the last segment
2876 //================================================================================
2878 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
2880 // find two non-coincident positions
2881 gp_XYZ orig = _pos.back();
2883 int iPrev = _pos.size() - 2;
2884 while ( iPrev >= 0 )
2886 dir = orig - _pos[iPrev];
2887 if ( dir.SquareModulus() > 1e-100 )
2897 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
2898 segDir.SetDirection( _normal );
2903 gp_Pnt pPrev = _pos[ iPrev ];
2904 if ( !_sWOL.IsNull() )
2906 TopLoc_Location loc;
2907 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2910 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2911 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
2915 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2916 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
2918 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
2920 segDir.SetLocation( pPrev );
2921 segDir.SetDirection( dir );
2922 segLen = dir.Modulus();
2928 //================================================================================
2930 * \brief Test intersection of the last segment with a given triangle
2931 * using Moller-Trumbore algorithm
2932 * Intersection is detected if distance to intersection is less than _LayerEdge._len
2934 //================================================================================
2936 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
2937 const SMDS_MeshNode* n0,
2938 const SMDS_MeshNode* n1,
2939 const SMDS_MeshNode* n2,
2941 const double& EPSILON) const
2943 //const double EPSILON = 1e-6;
2945 gp_XYZ orig = lastSegment.Location().XYZ();
2946 gp_XYZ dir = lastSegment.Direction().XYZ();
2948 SMESH_TNodeXYZ vert0( n0 );
2949 SMESH_TNodeXYZ vert1( n1 );
2950 SMESH_TNodeXYZ vert2( n2 );
2952 /* calculate distance from vert0 to ray origin */
2953 gp_XYZ tvec = orig - vert0;
2955 if ( tvec * dir > EPSILON )
2956 // intersected face is at back side of the temporary face this _LayerEdge belongs to
2959 gp_XYZ edge1 = vert1 - vert0;
2960 gp_XYZ edge2 = vert2 - vert0;
2962 /* begin calculating determinant - also used to calculate U parameter */
2963 gp_XYZ pvec = dir ^ edge2;
2965 /* if determinant is near zero, ray lies in plane of triangle */
2966 double det = edge1 * pvec;
2968 if (det > -EPSILON && det < EPSILON)
2970 double inv_det = 1.0 / det;
2972 /* calculate U parameter and test bounds */
2973 double u = ( tvec * pvec ) * inv_det;
2974 if (u < 0.0 || u > 1.0)
2977 /* prepare to test V parameter */
2978 gp_XYZ qvec = tvec ^ edge1;
2980 /* calculate V parameter and test bounds */
2981 double v = (dir * qvec) * inv_det;
2982 if ( v < 0.0 || u + v > 1.0 )
2985 /* calculate t, ray intersects triangle */
2986 t = (edge2 * qvec) * inv_det;
2988 // if (det < EPSILON)
2991 // /* calculate distance from vert0 to ray origin */
2992 // gp_XYZ tvec = orig - vert0;
2994 // /* calculate U parameter and test bounds */
2995 // double u = tvec * pvec;
2996 // if (u < 0.0 || u > det)
2999 // /* prepare to test V parameter */
3000 // gp_XYZ qvec = tvec ^ edge1;
3002 // /* calculate V parameter and test bounds */
3003 // double v = dir * qvec;
3004 // if (v < 0.0 || u + v > det)
3007 // /* calculate t, scale parameters, ray intersects triangle */
3008 // double t = edge2 * qvec;
3009 // double inv_det = 1.0 / det;
3017 //================================================================================
3019 * \brief Perform smooth of _LayerEdge's based on EDGE's
3020 * \retval bool - true if node has been moved
3022 //================================================================================
3024 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3025 const TopoDS_Face& F,
3026 SMESH_MesherHelper& helper)
3028 ASSERT( IsOnEdge() );
3030 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3031 SMESH_TNodeXYZ oldPos( tgtNode );
3032 double dist01, distNewOld;
3034 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3035 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3036 dist01 = p0.Distance( _2neibors->_nodes[1] );
3038 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3039 double lenDelta = 0;
3042 lenDelta = _curvature->lenDelta( _len );
3043 newPos.ChangeCoord() += _normal * lenDelta;
3046 distNewOld = newPos.Distance( oldPos );
3050 if ( _2neibors->_plnNorm )
3052 // put newPos on the plane defined by source node and _plnNorm
3053 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3054 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3055 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3057 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3058 _pos.back() = newPos.XYZ();
3062 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3063 gp_XY uv( Precision::Infinite(), 0 );
3064 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3065 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3067 newPos = surface->Value( uv.X(), uv.Y() );
3068 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3071 if ( _curvature && lenDelta < 0 )
3073 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3074 _len -= prevPos.Distance( oldPos );
3075 _len += prevPos.Distance( newPos );
3077 bool moved = distNewOld > dist01/50;
3079 dumpMove( tgtNode ); // debug
3084 //================================================================================
3086 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3087 * \retval bool - true if _tgtNode has been moved
3089 //================================================================================
3091 bool _LayerEdge::Smooth(int& badNb)
3093 if ( _simplices.size() < 2 )
3094 return false; // _LayerEdge inflated along EDGE or FACE
3096 // compute new position for the last _pos
3097 gp_XYZ newPos (0,0,0);
3098 for ( unsigned i = 0; i < _simplices.size(); ++i )
3099 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3100 newPos /= _simplices.size();
3103 newPos += _normal * _curvature->lenDelta( _len );
3105 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3106 // if ( _cosin < -0.1)
3108 // // Avoid decreasing length of edge on concave surface
3109 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3110 // gp_Vec newMove( prevPos, newPos );
3111 // newPos = _pos.back() + newMove.XYZ();
3113 // else if ( _cosin > 0.3 )
3115 // // Avoid increasing length of edge too much
3118 // count quality metrics (orientation) of tetras around _tgtNode
3120 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3121 for ( unsigned i = 0; i < _simplices.size(); ++i )
3122 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3125 for ( unsigned i = 0; i < _simplices.size(); ++i )
3126 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3128 if ( nbOkAfter < nbOkBefore )
3131 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3133 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3134 _len += prevPos.Distance(newPos);
3136 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3137 _pos.back() = newPos;
3139 badNb += _simplices.size() - nbOkAfter;
3146 //================================================================================
3148 * \brief Add a new segment to _LayerEdge during inflation
3150 //================================================================================
3152 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3154 if ( _len - len > -1e-6 )
3156 _pos.push_back( _pos.back() );
3160 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3161 SMESH_TNodeXYZ oldXYZ( n );
3162 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3163 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3165 _pos.push_back( nXYZ );
3167 if ( !_sWOL.IsNull() )
3170 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3172 double u = Precision::Infinite(); // to force projection w/o distance check
3173 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3174 _pos.back().SetCoord( u, 0, 0 );
3175 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3176 pos->SetUParameter( u );
3180 gp_XY uv( Precision::Infinite(), 0 );
3181 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3182 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3183 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3184 pos->SetUParameter( uv.X() );
3185 pos->SetVParameter( uv.Y() );
3187 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3189 dumpMove( n ); //debug
3192 //================================================================================
3194 * \brief Remove last inflation step
3196 //================================================================================
3198 void _LayerEdge::InvalidateStep( int curStep )
3200 if ( _pos.size() > curStep )
3202 _pos.resize( curStep );
3203 gp_Pnt nXYZ = _pos.back();
3204 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3205 if ( !_sWOL.IsNull() )
3207 TopLoc_Location loc;
3208 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3210 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3211 pos->SetUParameter( nXYZ.X() );
3213 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3214 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3218 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3219 pos->SetUParameter( nXYZ.X() );
3220 pos->SetVParameter( nXYZ.Y() );
3221 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3222 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3225 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3230 //================================================================================
3232 * \brief Create layers of prisms
3234 //================================================================================
3236 bool _ViscousBuilder::refine(_SolidData& data)
3238 SMESH_MesherHelper helper( *_mesh );
3239 helper.SetSubShape( data._solid );
3240 helper.SetElementsOnShape(false);
3242 Handle(Geom_Curve) curve;
3243 Handle(Geom_Surface) surface;
3244 TopoDS_Edge geomEdge;
3245 TopoDS_Face geomFace;
3246 TopLoc_Location loc;
3247 double f,l, u/*, distXYZ[4]*/;
3251 for ( unsigned i = 0; i < data._edges.size(); ++i )
3253 _LayerEdge& edge = *data._edges[i];
3255 // get accumulated length of segments
3256 vector< double > segLen( edge._pos.size() );
3258 for ( unsigned j = 1; j < edge._pos.size(); ++j )
3259 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3261 // allocate memory for new nodes if it is not yet refined
3262 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3263 if ( edge._nodes.size() == 2 )
3265 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3267 edge._nodes.back() = tgtNode;
3269 if ( !edge._sWOL.IsNull() )
3271 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3272 // restore position of the last node
3276 geomEdge = TopoDS::Edge( edge._sWOL );
3277 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3278 // double u = helper.GetNodeU( tgtNode );
3279 // p = curve->Value( u );
3283 geomFace = TopoDS::Face( edge._sWOL );
3284 surface = BRep_Tool::Surface( geomFace, loc );
3285 // gp_XY uv = helper.GetNodeUV( tgtNode );
3286 // p = surface->Value( uv.X(), uv.Y() );
3288 // p.Transform( loc );
3289 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3291 // calculate height of the first layer
3293 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3294 const double f = data._hyp->GetStretchFactor();
3295 const int N = data._hyp->GetNumberLayers();
3296 const double fPowN = pow( f, N );
3297 if ( fPowN - 1 <= numeric_limits<double>::min() )
3300 h0 = T * ( f - 1 )/( fPowN - 1 );
3302 const double zeroLen = std::numeric_limits<double>::min();
3304 // create intermediate nodes
3305 double hSum = 0, hi = h0/f;
3307 for ( unsigned iStep = 1; iStep < edge._nodes.size(); ++iStep )
3309 // compute an intermediate position
3312 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3314 int iPrevSeg = iSeg-1;
3315 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3317 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3318 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3320 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3321 if ( !edge._sWOL.IsNull() )
3323 // compute XYZ by parameters <pos>
3327 pos = curve->Value( u ).Transformed(loc);
3331 uv.SetCoord( pos.X(), pos.Y() );
3332 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3335 // create or update the node
3338 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3339 if ( !edge._sWOL.IsNull() )
3342 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3344 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3348 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3353 if ( !edge._sWOL.IsNull() )
3355 // make average pos from new and current parameters
3358 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3359 pos = curve->Value( u ).Transformed(loc);
3363 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3364 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3367 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3372 // TODO: make quadratic prisms and polyhedrons(?)
3374 helper.SetElementsOnShape(true);
3376 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3377 for ( ; exp.More(); exp.Next() )
3379 if ( _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3381 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3382 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3383 vector< vector<const SMDS_MeshNode*>* > nnVec;
3384 while ( fIt->more() )
3386 const SMDS_MeshElement* face = fIt->next();
3387 int nbNodes = face->NbCornerNodes();
3388 nnVec.resize( nbNodes );
3389 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3390 for ( int iN = 0; iN < nbNodes; ++iN )
3392 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3393 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3396 int nbZ = nnVec[0]->size();
3400 for ( int iZ = 1; iZ < nbZ; ++iZ )
3401 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3402 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3405 for ( int iZ = 1; iZ < nbZ; ++iZ )
3406 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3407 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3408 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3409 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3412 return error("Not supported type of element", data._index);
3419 //================================================================================
3421 * \brief Shrink 2D mesh on faces to let space for inflated layers
3423 //================================================================================
3425 bool _ViscousBuilder::shrink()
3427 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3428 // inflated along FACE or EDGE)
3429 map< TGeomID, _SolidData* > f2sdMap;
3430 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
3432 _SolidData& data = _sdVec[i];
3433 TopTools_MapOfShape FFMap;
3434 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3435 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3436 if ( s2s->second.ShapeType() == TopAbs_FACE )
3438 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3440 if ( FFMap.Add( (*s2s).second ))
3441 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3442 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3443 // by StdMeshers_QuadToTriaAdaptor
3444 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3446 SMESH_ProxyMesh::SubMesh* proxySub =
3447 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3448 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3449 while ( fIt->more() )
3450 proxySub->AddElement( fIt->next() );
3451 // as a result 3D algo will use elements from proxySub and not from smDS
3456 SMESH_MesherHelper helper( *_mesh );
3459 map< int, _Shrinker1D > e2shrMap;
3461 // loop on FACES to srink mesh on
3462 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3463 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3465 _SolidData& data = *f2sd->second;
3466 TNode2Edge& n2eMap = data._n2eMap;
3467 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3469 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3471 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3472 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3474 helper.SetSubShape(F);
3476 // ===========================
3477 // Prepare data for shrinking
3478 // ===========================
3480 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3481 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3482 vector < const SMDS_MeshNode* > smoothNodes;
3484 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3485 while ( nIt->more() )
3487 const SMDS_MeshNode* n = nIt->next();
3488 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3489 smoothNodes.push_back( n );
3492 // Find out face orientation
3494 const set<TGeomID> ignoreShapes;
3496 if ( !smoothNodes.empty() )
3498 vector<_Simplex> simplices;
3499 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3500 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3501 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3502 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3503 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3507 // Find _LayerEdge's inflated along F
3508 vector< _LayerEdge* > lEdges;
3510 SMESH_subMeshIteratorPtr subIt =
3511 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3512 while ( subIt->more() )
3514 SMESH_subMesh* sub = subIt->next();
3515 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3516 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3518 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3519 while ( nIt->more() )
3521 _LayerEdge* edge = n2eMap[ nIt->next() ];
3522 lEdges.push_back( edge );
3523 prepareEdgeToShrink( *edge, F, helper, smDS );
3528 // Replace source nodes by target nodes in mesh faces to shrink
3529 const SMDS_MeshNode* nodes[20];
3530 for ( unsigned i = 0; i < lEdges.size(); ++i )
3532 _LayerEdge& edge = *lEdges[i];
3533 const SMDS_MeshNode* srcNode = edge._nodes[0];
3534 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3535 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3536 while ( fIt->more() )
3538 const SMDS_MeshElement* f = fIt->next();
3539 if ( !smDS->Contains( f ))
3541 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3542 for ( int iN = 0; iN < f->NbNodes(); ++iN )
3544 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3545 nodes[iN] = ( n == srcNode ? tgtNode : n );
3547 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3551 // find out if a FACE is concave
3552 const bool isConcaveFace = isConcave( F, helper );
3554 // Create _SmoothNode's on face F
3555 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3557 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3558 for ( unsigned i = 0; i < smoothNodes.size(); ++i )
3560 const SMDS_MeshNode* n = smoothNodes[i];
3561 nodesToSmooth[ i ]._node = n;
3562 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3563 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, isConcaveFace );
3564 // fix up incorrect uv of nodes on the FACE
3565 helper.GetNodeUV( F, n, 0, &isOkUV);
3570 //if ( nodesToSmooth.empty() ) continue;
3572 // Find EDGE's to shrink
3573 set< _Shrinker1D* > eShri1D;
3575 for ( unsigned i = 0; i < lEdges.size(); ++i )
3577 _LayerEdge* edge = lEdges[i];
3578 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3580 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3581 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3582 eShri1D.insert( & srinker );
3583 srinker.AddEdge( edge, helper );
3584 // restore params of nodes on EGDE if the EDGE has been already
3585 // srinked while srinking another FACE
3586 srinker.RestoreParams();
3591 // ==================
3592 // Perform shrinking
3593 // ==================
3595 bool shrinked = true;
3596 int badNb, shriStep=0, smooStep=0;
3599 // Move boundary nodes (actually just set new UV)
3600 // -----------------------------------------------
3601 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep++ ); // debug
3603 for ( unsigned i = 0; i < lEdges.size(); ++i )
3605 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3609 // Move nodes on EDGE's
3610 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3611 for ( ; shr != eShri1D.end(); ++shr )
3612 (*shr)->Compute( /*set3D=*/false, helper );
3615 // -----------------
3616 int nbNoImpSteps = 0;
3619 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3621 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3623 int oldBadNb = badNb;
3626 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3628 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3629 /*isCentroidal=*/isConcaveFace,/*set3D=*/false );
3631 if ( badNb < oldBadNb )
3639 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3641 // No wrongly shaped faces remain; final smooth. Set node XYZ.
3642 // First, find out a needed quality of smoothing (high for quadrangles only)
3645 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
3646 if ( hasTria != hasQuad )
3648 highQuality = hasQuad;
3652 set<int> nbNodesSet;
3653 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3654 while ( fIt->more() && nbNodesSet.size() < 2 )
3655 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
3656 highQuality = ( *nbNodesSet.begin() == 4 );
3659 if ( !highQuality && isConcaveFace )
3660 fixBadFaces( F, helper ); // fix narrow faces by swaping diagonals
3661 for ( int st = highQuality ? 10 : 3; st; --st )
3663 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3664 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3665 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3666 /*isCentroidal=*/isConcaveFace,/*set3D=*/st==1 );
3669 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
3670 _SrinkShapeListener::ToClearSubMeshWithSolid( sm, data._solid );
3672 } // loop on FACES to srink mesh on
3675 // Replace source nodes by target nodes in shrinked mesh edges
3677 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3678 for ( ; e2shr != e2shrMap.end(); ++e2shr )
3679 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3684 //================================================================================
3686 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3688 //================================================================================
3690 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
3691 const TopoDS_Face& F,
3692 SMESH_MesherHelper& helper,
3693 const SMESHDS_SubMesh* faceSubMesh)
3695 const SMDS_MeshNode* srcNode = edge._nodes[0];
3696 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3700 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3702 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3703 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3704 gp_Vec2d uvDir( srcUV, tgtUV );
3705 double uvLen = uvDir.Magnitude();
3707 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3709 // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3710 vector<const SMDS_MeshElement*> faces;
3711 multimap< double, const SMDS_MeshNode* > proj2node;
3712 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3713 while ( fIt->more() )
3715 const SMDS_MeshElement* f = fIt->next();
3716 if ( faceSubMesh->Contains( f ))
3717 faces.push_back( f );
3719 for ( unsigned i = 0; i < faces.size(); ++i )
3721 const int nbNodes = faces[i]->NbCornerNodes();
3722 for ( int j = 0; j < nbNodes; ++j )
3724 const SMDS_MeshNode* n = faces[i]->GetNode(j);
3725 if ( n == srcNode ) continue;
3726 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3727 ( faces.size() > 1 || nbNodes > 3 ))
3729 gp_Pnt2d uv = helper.GetNodeUV( F, n );
3730 gp_Vec2d uvDirN( srcUV, uv );
3731 double proj = uvDirN * uvDir;
3732 proj2node.insert( make_pair( proj, n ));
3736 multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
3737 const double minProj = p2n->first;
3738 const double projThreshold = 1.1 * uvLen;
3739 if ( minProj > projThreshold )
3741 // tgtNode is located so that it does not make faces with wrong orientation
3744 edge._pos.resize(1);
3745 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
3747 // store most risky nodes in _simplices
3748 p2nEnd = proj2node.lower_bound( projThreshold );
3749 int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
3750 edge._simplices.resize( nbSimpl );
3751 for ( int i = 0; i < nbSimpl; ++i )
3753 edge._simplices[i]._nPrev = p2n->second;
3754 if ( ++p2n != p2nEnd )
3755 edge._simplices[i]._nNext = p2n->second;
3757 // set UV of source node to target node
3758 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3759 pos->SetUParameter( srcUV.X() );
3760 pos->SetVParameter( srcUV.Y() );
3762 else // _sWOL is TopAbs_EDGE
3764 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
3765 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
3766 if ( !edgeSM || edgeSM->NbElements() == 0 )
3767 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3769 const SMDS_MeshNode* n2 = 0;
3770 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3771 while ( eIt->more() && !n2 )
3773 const SMDS_MeshElement* e = eIt->next();
3774 if ( !edgeSM->Contains(e)) continue;
3775 n2 = e->GetNode( 0 );
3776 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
3779 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3781 double uSrc = helper.GetNodeU( E, srcNode, n2 );
3782 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
3783 double u2 = helper.GetNodeU( E, n2, srcNode );
3785 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
3787 // tgtNode is located so that it does not make faces with wrong orientation
3790 edge._pos.resize(1);
3791 edge._pos[0].SetCoord( U_TGT, uTgt );
3792 edge._pos[0].SetCoord( U_SRC, uSrc );
3793 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
3795 edge._simplices.resize( 1 );
3796 edge._simplices[0]._nPrev = n2;
3798 // set UV of source node to target node
3799 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3800 pos->SetUParameter( uSrc );
3804 //================================================================================
3806 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
3808 //================================================================================
3810 // Compute UV to follow during shrinking
3812 // const SMDS_MeshNode* srcNode = edge._nodes[0];
3813 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
3815 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3816 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3817 // gp_Vec2d uvDir( srcUV, tgtUV );
3818 // double uvLen = uvDir.Magnitude();
3821 // // Select shrinking step such that not to make faces with wrong orientation.
3822 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3823 // const double minStepSize = uvLen / 20;
3824 // double stepSize = uvLen;
3825 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3826 // while ( fIt->more() )
3828 // const SMDS_MeshElement* f = fIt->next();
3829 // if ( !faceSubMesh->Contains( f )) continue;
3830 // const int nbNodes = f->NbCornerNodes();
3831 // for ( int i = 0; i < nbNodes; ++i )
3833 // const SMDS_MeshNode* n = f->GetNode(i);
3834 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
3836 // gp_XY uv = helper.GetNodeUV( F, n );
3837 // gp_Vec2d uvDirN( srcUV, uv );
3838 // double proj = uvDirN * uvDir;
3839 // if ( proj < stepSize && proj > minStepSize )
3845 // const int nbSteps = ceil( uvLen / stepSize );
3846 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
3847 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
3848 // edge._pos.resize( nbSteps );
3849 // edge._pos[0] = tgtUV0;
3850 // for ( int i = 1; i < nbSteps; ++i )
3852 // double r = i / double( nbSteps );
3853 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
3858 //================================================================================
3860 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
3862 //================================================================================
3864 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper)
3866 SMESH::Controls::AspectRatio qualifier;
3867 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
3868 const double maxAspectRatio = 4.;
3870 // find bad triangles
3872 vector< const SMDS_MeshElement* > badTrias;
3873 vector< double > badAspects;
3874 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
3875 SMDS_ElemIteratorPtr fIt = sm->GetElements();
3876 while ( fIt->more() )
3878 const SMDS_MeshElement * f = fIt->next();
3879 if ( f->NbCornerNodes() != 3 ) continue;
3880 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = SMESH_TNodeXYZ( f->GetNode(iP));
3881 double aspect = qualifier.GetValue( points );
3882 if ( aspect > maxAspectRatio )
3884 badTrias.push_back( f );
3885 badAspects.push_back( aspect );
3888 if ( badTrias.empty() )
3891 // find couples of faces to swap diagonal
3893 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
3894 vector< T2Trias > triaCouples;
3896 TIDSortedElemSet involvedFaces, emptySet;
3897 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
3900 double aspRatio [3];
3903 involvedFaces.insert( badTrias[iTia] );
3904 for ( int iP = 0; iP < 3; ++iP )
3905 points(iP+1) = SMESH_TNodeXYZ( badTrias[iTia]->GetNode(iP));
3907 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
3908 int bestCouple = -1;
3909 for ( int iSide = 0; iSide < 3; ++iSide )
3911 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
3912 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
3913 trias [iSide].first = badTrias[iTia];
3914 trias [iSide].second = SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, involvedFaces,
3916 if ( ! trias[iSide].second || trias[iSide].second->NbCornerNodes() != 3 )
3919 // aspect ratio of an adjacent tria
3920 for ( int iP = 0; iP < 3; ++iP )
3921 points2(iP+1) = SMESH_TNodeXYZ( trias[iSide].second->GetNode(iP));
3922 double aspectInit = qualifier.GetValue( points2 );
3924 // arrange nodes as after diag-swaping
3925 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
3926 i3 = helper.WrapIndex( i1-1, 3 );
3928 i3 = helper.WrapIndex( i1+1, 3 );
3930 points1( 1+ iSide ) = points2( 1+ i3 );
3931 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
3933 // aspect ratio after diag-swaping
3934 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
3935 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
3938 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
3942 if ( bestCouple >= 0 )
3944 triaCouples.push_back( trias[bestCouple] );
3945 involvedFaces.insert ( trias[bestCouple].second );
3949 involvedFaces.erase( badTrias[iTia] );
3952 if ( triaCouples.empty() )
3957 SMESH_MeshEditor editor( helper.GetMesh() );
3958 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
3959 for ( size_t i = 0; i < triaCouples.size(); ++i )
3961 dumpChangeNodes( triaCouples[i].first );
3962 dumpChangeNodes( triaCouples[i].second );
3963 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
3967 // just for debug dump resulting triangles
3968 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID());
3969 for ( size_t i = 0; i < triaCouples.size(); ++i )
3971 dumpChangeNodes( triaCouples[i].first );
3972 dumpChangeNodes( triaCouples[i].second );
3976 //================================================================================
3978 * \brief Move target node to it's final position on the FACE during shrinking
3980 //================================================================================
3982 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
3983 const TopoDS_Face& F,
3984 SMESH_MesherHelper& helper )
3987 return false; // already at the target position
3989 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
3991 if ( _sWOL.ShapeType() == TopAbs_FACE )
3993 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
3994 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y());
3995 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
3996 const double uvLen = tgtUV.Distance( curUV );
3998 // Select shrinking step such that not to make faces with wrong orientation.
3999 const double kSafe = 0.8;
4000 const double minStepSize = uvLen / 10;
4001 double stepSize = uvLen;
4002 for ( unsigned i = 0; i < _simplices.size(); ++i )
4004 const SMDS_MeshNode* nn[2] = { _simplices[i]._nPrev, _simplices[i]._nNext };
4005 for ( int j = 0; j < 2; ++j )
4006 if ( const SMDS_MeshNode* n = nn[j] )
4008 gp_XY uv = helper.GetNodeUV( F, n );
4009 gp_Vec2d uvDirN( curUV, uv );
4010 double proj = uvDirN * uvDir * kSafe;
4011 if ( proj < stepSize && proj > minStepSize )
4017 if ( stepSize == uvLen )
4024 newUV = curUV + uvDir.XY() * stepSize;
4027 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4028 pos->SetUParameter( newUV.X() );
4029 pos->SetVParameter( newUV.Y() );
4032 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4033 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4034 dumpMove( tgtNode );
4037 else // _sWOL is TopAbs_EDGE
4039 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4040 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4042 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4043 const double uSrc = _pos[0].Coord( U_SRC );
4044 const double lenTgt = _pos[0].Coord( LEN_TGT );
4046 double newU = _pos[0].Coord( U_TGT );
4047 if ( lenTgt < 0.99 * fabs( uSrc-u2 ))
4053 newU = 0.1 * uSrc + 0.9 * u2;
4055 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4056 pos->SetUParameter( newU );
4058 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4059 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4060 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4061 dumpMove( tgtNode );
4067 //================================================================================
4069 * \brief Perform smooth on the FACE
4070 * \retval bool - true if the node has been moved
4072 //================================================================================
4074 bool _SmoothNode::Smooth(int& badNb,
4075 Handle(Geom_Surface)& surface,
4076 SMESH_MesherHelper& helper,
4077 const double refSign,
4081 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4083 // get uv of surrounding nodes
4084 vector<gp_XY> uv( _simplices.size() );
4085 for ( size_t i = 0; i < _simplices.size(); ++i )
4086 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4088 // compute new UV for the node
4090 if ( isCentroidal && _simplices.size() > 3 )
4092 // average centers of diagonals wieghted with their reciprocal lengths
4093 if ( _simplices.size() == 4 )
4095 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4096 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4097 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4101 double sumWeight = 0;
4102 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4103 for ( int i = 0; i < nb; ++i )
4106 int iTo = i + _simplices.size() - 1;
4107 for ( int j = iFrom; j < iTo; ++j )
4109 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4110 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4112 newPos += w * ( uv[i]+uv[i2] );
4115 newPos /= 2 * sumWeight;
4121 isCentroidal = false;
4122 for ( size_t i = 0; i < _simplices.size(); ++i )
4124 newPos /= _simplices.size();
4127 // count quality metrics (orientation) of triangles around the node
4129 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4130 for ( unsigned i = 0; i < _simplices.size(); ++i )
4131 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4134 for ( unsigned i = 0; i < _simplices.size(); ++i )
4135 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4137 if ( nbOkAfter < nbOkBefore )
4139 // if ( isCentroidal )
4140 // return Smooth( badNb, surface, helper, refSign, !isCentroidal, set3D );
4141 badNb += _simplices.size() - nbOkBefore;
4145 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4146 pos->SetUParameter( newPos.X() );
4147 pos->SetVParameter( newPos.Y() );
4154 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4155 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4159 badNb += _simplices.size() - nbOkAfter;
4160 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4163 //================================================================================
4165 * \brief Delete _SolidData
4167 //================================================================================
4169 _SolidData::~_SolidData()
4171 for ( unsigned i = 0; i < _edges.size(); ++i )
4173 if ( _edges[i] && _edges[i]->_2neibors )
4174 delete _edges[i]->_2neibors;
4179 //================================================================================
4181 * \brief Add a _LayerEdge inflated along the EDGE
4183 //================================================================================
4185 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4188 if ( _nodes.empty() )
4190 _edges[0] = _edges[1] = 0;
4194 if ( e == _edges[0] || e == _edges[1] )
4196 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4197 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4198 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4199 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4202 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4204 BRep_Tool::Range( E, f,l );
4205 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4206 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4210 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4211 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4213 if ( _nodes.empty() )
4215 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4216 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4218 TopLoc_Location loc;
4219 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4220 GeomAdaptor_Curve aCurve(C, f,l);
4221 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4223 int nbExpectNodes = eSubMesh->NbNodes() - e->_nodes.size();
4224 _initU .reserve( nbExpectNodes );
4225 _normPar.reserve( nbExpectNodes );
4226 _nodes .reserve( nbExpectNodes );
4227 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4228 while ( nIt->more() )
4230 const SMDS_MeshNode* node = nIt->next();
4231 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4232 node == tgtNode0 || node == tgtNode1 )
4233 continue; // refinement nodes
4234 _nodes.push_back( node );
4235 _initU.push_back( helper.GetNodeU( E, node ));
4236 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4237 _normPar.push_back( len / totLen );
4242 // remove target node of the _LayerEdge from _nodes
4244 for ( unsigned i = 0; i < _nodes.size(); ++i )
4245 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4246 _nodes[i] = 0, nbFound++;
4247 if ( nbFound == _nodes.size() )
4252 //================================================================================
4254 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4256 //================================================================================
4258 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4260 if ( _done || _nodes.empty())
4262 const _LayerEdge* e = _edges[0];
4263 if ( !e ) e = _edges[1];
4266 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4267 ( !_edges[1] || _edges[1]->_pos.empty() ));
4269 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4271 if ( set3D || _done )
4273 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4274 GeomAdaptor_Curve aCurve(C, f,l);
4277 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4279 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4280 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4282 for ( unsigned i = 0; i < _nodes.size(); ++i )
4284 if ( !_nodes[i] ) continue;
4285 double len = totLen * _normPar[i];
4286 GCPnts_AbscissaPoint discret( aCurve, len, f );
4287 if ( !discret.IsDone() )
4288 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4289 double u = discret.Parameter();
4290 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4291 pos->SetUParameter( u );
4292 gp_Pnt p = C->Value( u );
4293 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4298 BRep_Tool::Range( E, f,l );
4300 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4302 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4304 for ( unsigned i = 0; i < _nodes.size(); ++i )
4306 if ( !_nodes[i] ) continue;
4307 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4308 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4309 pos->SetUParameter( u );
4314 //================================================================================
4316 * \brief Restore initial parameters of nodes on EDGE
4318 //================================================================================
4320 void _Shrinker1D::RestoreParams()
4323 for ( unsigned i = 0; i < _nodes.size(); ++i )
4325 if ( !_nodes[i] ) continue;
4326 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4327 pos->SetUParameter( _initU[i] );
4332 //================================================================================
4334 * \brief Replace source nodes by target nodes in shrinked mesh edges
4336 //================================================================================
4338 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4340 const SMDS_MeshNode* nodes[3];
4341 for ( int i = 0; i < 2; ++i )
4343 if ( !_edges[i] ) continue;
4345 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4346 if ( !eSubMesh ) return;
4347 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4348 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4349 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4350 while ( eIt->more() )
4352 const SMDS_MeshElement* e = eIt->next();
4353 if ( !eSubMesh->Contains( e ))
4355 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4356 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4358 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4359 nodes[iN] = ( n == srcNode ? tgtNode : n );
4361 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4366 //================================================================================
4368 * \brief Creates 2D and 1D elements on boundaries of new prisms
4370 //================================================================================
4372 bool _ViscousBuilder::addBoundaryElements()
4374 SMESH_MesherHelper helper( *_mesh );
4376 for ( unsigned i = 0; i < _sdVec.size(); ++i )
4378 _SolidData& data = _sdVec[i];
4379 TopTools_IndexedMapOfShape geomEdges;
4380 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4381 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4383 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4385 // Get _LayerEdge's based on E
4387 map< double, const SMDS_MeshNode* > u2nodes;
4388 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4391 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
4392 TNode2Edge & n2eMap = data._n2eMap;
4393 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4395 //check if 2D elements are needed on E
4396 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
4397 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
4398 ledges.push_back( n2e->second );
4400 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
4401 continue; // no layers on E
4402 ledges.push_back( n2eMap[ u2n->second ]);
4404 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
4405 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
4406 int nbSharedPyram = 0;
4407 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
4408 while ( vIt->more() )
4410 const SMDS_MeshElement* v = vIt->next();
4411 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
4413 if ( nbSharedPyram > 1 )
4414 continue; // not free border of the pyramid
4416 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
4417 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
4418 continue; // faces already created
4420 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
4421 ledges.push_back( n2eMap[ u2n->second ]);
4423 // Find out orientation and type of face to create
4425 bool reverse = false, isOnFace;
4427 map< TGeomID, TopoDS_Shape >::iterator e2f =
4428 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
4430 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
4432 F = e2f->second.Oriented( TopAbs_FORWARD );
4433 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
4434 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
4439 // find FACE with layers sharing E
4440 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
4441 while ( fIt->more() && F.IsNull() )
4443 const TopoDS_Shape* pF = fIt->next();
4444 if ( helper.IsSubShape( *pF, data._solid) &&
4445 !_ignoreShapeIds.count( e2f->first ))
4449 // Find the sub-mesh to add new faces
4450 SMESHDS_SubMesh* sm = 0;
4452 sm = getMeshDS()->MeshElements( F );
4454 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
4456 return error("error in addBoundaryElements()", data._index);
4459 const int dj1 = reverse ? 0 : 1;
4460 const int dj2 = reverse ? 1 : 0;
4461 for ( unsigned j = 1; j < ledges.size(); ++j )
4463 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
4464 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
4466 for ( unsigned z = 1; z < nn1.size(); ++z )
4467 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
4469 for ( unsigned z = 1; z < nn1.size(); ++z )
4470 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));