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
20 // File : StdMeshers_ViscousLayers.cxx
21 // Created : Wed Dec 1 15:15:34 2010
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers.hxx"
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_Gen.hxx"
36 #include "SMESH_Group.hxx"
37 #include "SMESH_Mesh.hxx"
38 #include "SMESH_MesherHelper.hxx"
39 #include "SMESH_subMesh.hxx"
40 #include "SMESH_subMeshEventListener.hxx"
41 #include "SMESH_ProxyMesh.hxx"
43 #include "utilities.h"
45 #include <BRep_Tool.hxx>
46 #include <GCPnts_AbscissaPoint.hxx>
47 #include <GeomAdaptor_Curve.hxx>
48 #include <Geom_Curve.hxx>
49 #include <Precision.hxx>
51 #include <TopExp_Explorer.hxx>
52 #include <TopTools_IndexedMapOfShape.hxx>
53 #include <TopTools_MapOfShape.hxx>
55 #include <TopoDS_Edge.hxx>
56 #include <TopoDS_Face.hxx>
57 #include <TopoDS_Vertex.hxx>
72 //================================================================================
77 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
80 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
81 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
83 struct _MeshOfSolid : public SMESH_ProxyMesh,
84 public SMESH_subMeshEventListenerData
88 _MeshOfSolid( SMESH_Mesh* mesh)
89 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
91 SMESH_ProxyMesh::setMesh( *mesh );
94 // returns submesh for a geom face
95 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
97 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
98 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
100 void setNode2Node(const SMDS_MeshNode* srcNode,
101 const SMDS_MeshNode* proxyNode,
102 const SMESH_ProxyMesh::SubMesh* subMesh)
104 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
107 //--------------------------------------------------------------------------------
109 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
110 * It is used to clear an inferior dim sub-mesh modified by viscous layers
112 class _SrinkShapeListener : SMESH_subMeshEventListener
114 _SrinkShapeListener(): SMESH_subMeshEventListener(/*isDeletable=*/false) {}
115 static SMESH_subMeshEventListener* Get() { static _SrinkShapeListener l; return &l; }
117 virtual void ProcessEvent(const int event,
119 SMESH_subMesh* solidSM,
120 SMESH_subMeshEventListenerData* data,
121 const SMESH_Hypothesis* hyp)
123 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
125 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
128 static void ToClearSubMeshWithSolid( SMESH_subMesh* sm,
129 const TopoDS_Shape& solid)
131 SMESH_subMesh* solidSM = sm->GetFather()->GetSubMesh( solid );
132 SMESH_subMeshEventListenerData* data = solidSM->GetEventListenerData( Get());
135 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sm ) ==
136 data->mySubMeshes.end())
137 data->mySubMeshes.push_back( sm );
141 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sm );
142 sm->SetEventListener( Get(), data, /*whereToListenTo=*/solidSM );
146 //--------------------------------------------------------------------------------
148 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
149 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
150 * delete the data as soon as it has been used
152 class _ViscousListener : SMESH_subMeshEventListener
154 _ViscousListener(): SMESH_subMeshEventListener(/*isDeletable=*/false) {}
155 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
157 virtual void ProcessEvent(const int event,
159 SMESH_subMesh* subMesh,
160 SMESH_subMeshEventListenerData* data,
161 const SMESH_Hypothesis* hyp)
163 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
165 // delete SMESH_ProxyMesh containing temporary faces
166 subMesh->DeleteEventListener( this );
169 // Finds or creates proxy mesh of the solid
170 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
171 const TopoDS_Shape& solid,
174 if ( !mesh ) return 0;
175 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
176 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
177 if ( !data && toCreate )
179 data = new _MeshOfSolid(mesh);
180 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
181 sm->SetEventListener( Get(), data, sm );
185 // Removes proxy mesh of the solid
186 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
188 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
192 //--------------------------------------------------------------------------------
194 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
195 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
196 * The class is used to check validity of face or volumes around a smoothed node;
197 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
201 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
202 _Simplex(const SMDS_MeshNode* nPrev=0, const SMDS_MeshNode* nNext=0)
203 : _nPrev(nPrev), _nNext(nNext) {}
204 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
206 const double M[3][3] =
207 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
208 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
209 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
210 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
211 + M[0][1]*M[1][2]*M[2][0]
212 + M[0][2]*M[1][0]*M[2][1]
213 - M[0][0]*M[1][2]*M[2][1]
214 - M[0][1]*M[1][0]*M[2][2]
215 - M[0][2]*M[1][1]*M[2][0]);
216 return determinant > 1e-100;
218 bool IsForward(const gp_XY& tgtUV,
219 const TopoDS_Face& face,
220 SMESH_MesherHelper& helper,
221 const double refSign) const
223 gp_XY prevUV = helper.GetNodeUV( face, _nPrev );
224 gp_XY nextUV = helper.GetNodeUV( face, _nNext );
225 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
227 return d*refSign > 1e-100;
230 //--------------------------------------------------------------------------------
232 * Structure used to take into account surface curvature while smoothing
237 double _k; // factor to correct node smoothed position
239 static _Curvature* New( double avgNormProj, double avgDist )
242 if ( fabs( avgNormProj / avgDist ) > 1./200 )
245 c->_r = avgDist * avgDist / avgNormProj;
246 c->_k = avgDist * avgDist / c->_r / c->_r;
247 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
251 double lenDelta(double len) const { return _k * ( _r + len ); }
254 //--------------------------------------------------------------------------------
256 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
260 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
261 const SMDS_MeshNode* _nodes[2];
262 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
264 double _wgt[2]; // weights of _nodes
265 _LayerEdge* _edges[2];
267 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
270 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
272 //--------------------------------------------------------------------------------
274 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
275 * and a node of the most internal layer (_nodes.back())
279 vector< const SMDS_MeshNode*> _nodes;
281 gp_XYZ _normal; // to solid surface
282 vector<gp_XYZ> _pos; // points computed during inflation
283 double _len; // length achived with the last step
284 double _cosin; // of angle (_normal ^ surface)
285 double _lenFactor; // to compute _len taking _cosin into account
287 // face or edge w/o layer along or near which _LayerEdge is inflated
289 // simplices connected to the source node (_nodes[0]);
290 // used for smoothing and quality check of _LayerEdge's based on the FACE
291 vector<_Simplex> _simplices;
292 // data for smoothing of _LayerEdge's based on the EDGE
293 _2NearEdges* _2neibors;
295 _Curvature* _curvature;
296 // TODO:: detele _Curvature, _plnNorm
298 void SetNewLength( double len, SMESH_MesherHelper& helper );
299 bool SetNewLength2d( Handle(Geom_Surface)& surface,
300 const TopoDS_Face& F,
301 SMESH_MesherHelper& helper );
302 void SetDataByNeighbors( const SMDS_MeshNode* n1,
303 const SMDS_MeshNode* n2,
304 SMESH_MesherHelper& helper);
305 void InvalidateStep( int curStep );
306 bool Smooth(int& badNb);
307 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
308 const TopoDS_Face& F,
309 SMESH_MesherHelper& helper);
310 bool FindIntersection( SMESH_ElementSearcher& searcher,
312 const double& epsilon,
313 const SMDS_MeshElement** face = 0);
314 bool SegTriaInter( const gp_Ax1& lastSegment,
315 const SMDS_MeshNode* n0,
316 const SMDS_MeshNode* n1,
317 const SMDS_MeshNode* n2,
319 const double& epsilon) const;
320 gp_Ax1 LastSegment(double& segLen) const;
321 bool IsOnEdge() const { return _2neibors; }
322 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
323 void SetCosin( double cosin );
325 //--------------------------------------------------------------------------------
327 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
329 //--------------------------------------------------------------------------------
331 * \brief Data of a SOLID
336 const StdMeshers_ViscousLayers* _hyp;
337 _MeshOfSolid* _proxyMesh;
338 set<TGeomID> _reversedFaceIds;
340 double _stepSize, _stepSizeCoeff;
341 const SMDS_MeshNode* _stepSizeNodes[2];
344 // edges of _n2eMap. We keep same data in two containers because
345 // iteration over the map is 5 time longer than over the vector
346 vector< _LayerEdge* > _edges;
348 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
349 // layers and a FACE w/o layers
350 // value: the shape (FACE or EDGE) to shrink mesh on.
351 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
352 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
354 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
355 set< TGeomID > _noShrinkFaces;
357 // end index in _edges of _LayerEdge's based on EDGE (map key) to
358 // FACE (maybe NULL) they are inflated along
359 //map< int, TopoDS_Face > _endEdge2Face;
361 // end indices in _edges of _LayerEdge on one shape to smooth
362 vector< int > _endEdgeToSmooth;
364 double _epsilon; // precision for SegTriaInter()
366 int _index; // for debug
368 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
369 const StdMeshers_ViscousLayers* h=0,
370 _MeshOfSolid* m=0) :_solid(s), _hyp(h), _proxyMesh(m) {}
373 //--------------------------------------------------------------------------------
375 * \brief Data of node on a shrinked FACE
379 const SMDS_MeshNode* _node;
380 //vector<const SMDS_MeshNode*> _nodesAround;
381 vector<_Simplex> _simplices; // for quality check
383 bool Smooth(int& badNb,
384 Handle(Geom_Surface)& surface,
385 SMESH_MesherHelper& helper,
386 const double refSign,
389 //--------------------------------------------------------------------------------
391 * \brief Builder of viscous layers
393 class _ViscousBuilder
398 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
399 const TopoDS_Shape& shape);
401 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
402 void RestoreListeners();
404 // computes SMESH_ProxyMesh::SubMesh::_n2n;
405 bool MakeN2NMap( _MeshOfSolid* pm );
409 bool findSolidsWithLayers();
410 bool findFacesWithLayers();
411 bool makeLayer(_SolidData& data);
412 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
413 SMESH_MesherHelper& helper, _SolidData& data);
414 bool findNeiborsOnEdge(const _LayerEdge* edge,
415 const SMDS_MeshNode*& n1,
416 const SMDS_MeshNode*& n2,
418 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
419 const set<TGeomID>& ingnoreShapes,
420 const _SolidData* dataToCheckOri = 0);
421 bool sortEdges( _SolidData& data,
422 vector< vector<_LayerEdge*> >& edgesByGeom);
423 void limitStepSize( _SolidData& data,
424 const SMDS_MeshElement* face,
426 void limitStepSize( _SolidData& data, const double minSize);
427 bool inflate(_SolidData& data);
428 bool smoothAndCheck(_SolidData& data, int nbSteps, double & distToIntersection);
429 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
430 bool refine(_SolidData& data);
432 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
433 SMESH_MesherHelper& helper,
434 const SMESHDS_SubMesh* faceSubMesh );
435 bool addBoundaryElements();
437 bool error( const string& text, int solidID=-1 );
438 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
441 void makeGroupOfLE();
444 SMESH_ComputeErrorPtr _error;
446 vector< _SolidData > _sdVec;
447 set<TGeomID> _ignoreShapeIds;
450 //--------------------------------------------------------------------------------
452 * \brief Shrinker of nodes on the EDGE
456 vector<double> _initU;
457 vector<double> _normPar;
458 vector<const SMDS_MeshNode*> _nodes;
459 const _LayerEdge* _edges[2];
462 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
463 void Compute(bool set3D, SMESH_MesherHelper& helper);
464 void RestoreParams();
465 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
467 //--------------------------------------------------------------------------------
469 * \brief Class of temporary mesh face.
470 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
471 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
473 struct TmpMeshFace : public SMDS_MeshElement
475 vector<const SMDS_MeshNode* > _nn;
476 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
477 SMDS_MeshElement(id), _nn(nodes) {}
478 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
479 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
480 virtual vtkIdType GetVtkType() const { return -1; }
481 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
482 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const
483 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
485 //--------------------------------------------------------------------------------
487 * \brief Class of temporary mesh face storing _LayerEdge it's based on
489 struct TmpMeshFaceOnEdge : public TmpMeshFace
491 _LayerEdge *_le1, *_le2;
492 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
493 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
495 _nn[0]=_le1->_nodes[0];
496 _nn[1]=_le1->_nodes.back();
497 _nn[2]=_le2->_nodes.back();
498 _nn[3]=_le2->_nodes[0];
501 } // namespace VISCOUS
503 //================================================================================
504 // StdMeshers_ViscousLayers hypothesis
506 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
507 :SMESH_Hypothesis(hypId, studyId, gen),
508 _nbLayers(1), _thickness(1), _stretchFactor(1)
510 _name = StdMeshers_ViscousLayers::GetHypType();
511 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
512 } // --------------------------------------------------------------------------------
513 void StdMeshers_ViscousLayers::SetIgnoreFaces(const std::vector<int>& faceIds)
515 if ( faceIds != _ignoreFaceIds )
516 _ignoreFaceIds = faceIds, NotifySubMeshesHypothesisModification();
517 } // --------------------------------------------------------------------------------
518 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
520 if ( thickness != _thickness )
521 _thickness = thickness, NotifySubMeshesHypothesisModification();
522 } // --------------------------------------------------------------------------------
523 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
525 if ( _nbLayers != nb )
526 _nbLayers = nb, NotifySubMeshesHypothesisModification();
527 } // --------------------------------------------------------------------------------
528 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
530 if ( _stretchFactor != factor )
531 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
532 } // --------------------------------------------------------------------------------
534 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
535 const TopoDS_Shape& theShape,
536 const bool toMakeN2NMap) const
538 using namespace VISCOUS;
539 _ViscousBuilder bulder;
540 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
541 if ( err && !err->IsOK() )
542 return SMESH_ProxyMesh::Ptr();
544 vector<SMESH_ProxyMesh::Ptr> components;
545 TopExp_Explorer exp( theShape, TopAbs_SOLID );
546 for ( ; exp.More(); exp.Next() )
548 if ( _MeshOfSolid* pm =
549 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
551 if ( toMakeN2NMap && !pm->_n2nMapComputed )
552 if ( !bulder.MakeN2NMap( pm ))
553 return SMESH_ProxyMesh::Ptr();
554 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
555 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
557 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
559 switch ( components.size() )
563 case 1: return components[0];
565 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
567 return SMESH_ProxyMesh::Ptr();
568 } // --------------------------------------------------------------------------------
569 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
571 save << " " << _nbLayers
573 << " " << _stretchFactor
574 << " " << _ignoreFaceIds.size();
575 for ( unsigned i = 0; i < _ignoreFaceIds.size(); ++i )
576 save << " " << _ignoreFaceIds[i];
578 } // --------------------------------------------------------------------------------
579 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
582 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
583 while ( _ignoreFaceIds.size() < nbFaces && load >> faceID )
584 _ignoreFaceIds.push_back( faceID );
586 } // --------------------------------------------------------------------------------
587 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
588 const TopoDS_Shape& theShape)
593 // END StdMeshers_ViscousLayers hypothesis
594 //================================================================================
598 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
602 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
603 gp_Pnt p = BRep_Tool::Pnt( fromV );
604 double distF = p.SquareDistance( c->Value( f ));
605 double distL = p.SquareDistance( c->Value( l ));
606 c->D1(( distF < distL ? f : l), p, dir );
607 if ( distL < distF ) dir.Reverse();
610 //--------------------------------------------------------------------------------
611 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
612 SMESH_MesherHelper& helper)
615 double f,l; gp_Pnt p;
616 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
617 double u = helper.GetNodeU( E, atNode );
621 //--------------------------------------------------------------------------------
622 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
623 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
625 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
626 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
627 gp_Pnt p; gp_Vec du, dv, norm;
628 surface->D1( uv.X(),uv.Y(), p, du,dv );
632 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
633 double u = helper.GetNodeU( fromE, node, 0, &ok );
635 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
636 if ( o == TopAbs_REVERSED )
639 gp_Vec dir = norm ^ du;
641 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
642 helper.IsClosedEdge( fromE ))
644 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
645 else c->D1( f, p, dv );
646 if ( o == TopAbs_REVERSED )
648 gp_Vec dir2 = norm ^ dv;
649 dir = dir.Normalized() + dir2.Normalized();
653 //--------------------------------------------------------------------------------
654 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
655 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
656 bool& ok, double* cosin=0)
658 double f,l; TopLoc_Location loc;
659 vector< TopoDS_Edge > edges; // sharing a vertex
660 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
663 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
664 if ( helper.IsSubShape( *e, F ) && BRep_Tool::Curve( *e, loc,f,l))
665 edges.push_back( *e );
668 if ( !( ok = ( edges.size() > 0 ))) return dir;
669 // get average dir of edges going fromV
671 for ( unsigned i = 0; i < edges.size(); ++i )
673 edgeDir = getEdgeDir( edges[i], fromV );
674 double size2 = edgeDir.SquareMagnitude();
675 if ( size2 > numeric_limits<double>::min() )
676 edgeDir /= sqrt( size2 );
679 dir += edgeDir.XYZ();
681 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
682 if ( edges.size() == 1 || dir.SquareModulus() < 1e-10)
684 else if ( dir * fromEdgeDir < 0 )
688 //dir /= edges.size();
690 double angle = edgeDir.Angle( dir );
691 *cosin = cos( angle );
696 //--------------------------------------------------------------------------------
697 // DEBUG. Dump intermediate node positions into a python script
702 const char* fname = "/tmp/viscous.py";
703 cout << "execfile('"<<fname<<"')"<<endl;
704 py = new ofstream(fname);
705 *py << "from smesh import *" << endl
706 << "meshSO = GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
707 << "mesh = Mesh( meshSO.GetObject()._narrow( SMESH.SMESH_Mesh ))"<<endl;
710 *py << "mesh.MakeGroup('Prisms of viscous layers',VOLUME,FT_ElemGeomType,'=',Geom_PENTA)"
711 <<endl; delete py; py=0;
714 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
715 #define dumpMove(n) { _dumpMove(n, __LINE__);}
716 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
717 void _dumpFunction(const string& fun, int ln)
718 { *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
719 void _dumpMove(const SMDS_MeshNode* n, int ln)
720 { *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
721 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
722 void _dumpCmd(const string& txt, int ln)
723 { *py<< " "<<txt<<" # "<< ln <<endl; }
724 void dumpFunctionEnd()
725 { *py<< " return"<< endl; }
727 struct PyDump { PyDump() {} };
728 void dumpFunction(const string& fun ){}
729 void dumpFunctionEnd() {}
730 void dumpMove(const SMDS_MeshNode* n ){}
731 void dumpCmd(const string& txt){}
735 using namespace VISCOUS;
737 //================================================================================
739 * \brief Constructor of _ViscousBuilder
741 //================================================================================
743 _ViscousBuilder::_ViscousBuilder()
745 _error = SMESH_ComputeError::New(COMPERR_OK);
749 //================================================================================
751 * \brief Stores error description and returns false
753 //================================================================================
755 bool _ViscousBuilder::error(const string& text, int solidId )
757 _error->myName = COMPERR_ALGO_FAILED;
758 _error->myComment = string("Viscous layers builder: ") + text;
761 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
762 if ( !sm && !_sdVec.empty() )
763 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
764 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
766 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
767 if ( smError && smError->myAlgo )
768 _error->myAlgo = smError->myAlgo;
772 makeGroupOfLE(); // debug
777 //================================================================================
779 * \brief At study restoration, restore event listeners used to clear an inferior
780 * dim sub-mesh modified by viscous layers
782 //================================================================================
784 void _ViscousBuilder::RestoreListeners()
789 //================================================================================
791 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
793 //================================================================================
795 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
797 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
798 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
799 for ( ; fExp.More(); fExp.Next() )
801 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
802 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
804 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
806 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
809 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
810 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
812 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
813 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
814 while( prxIt->more() )
816 const SMDS_MeshElement* fSrc = srcIt->next();
817 const SMDS_MeshElement* fPrx = prxIt->next();
818 if ( fSrc->NbNodes() != fPrx->NbNodes())
819 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
820 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
821 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
824 pm->_n2nMapComputed = true;
828 //================================================================================
830 * \brief Does its job
832 //================================================================================
834 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
835 const TopoDS_Shape& theShape)
837 // TODO: set priority of solids during Gen::Compute()
841 // check if proxy mesh already computed
842 TopExp_Explorer exp( theShape, TopAbs_SOLID );
844 return error("No SOLID's in theShape"), _error;
846 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
847 return SMESH_ComputeErrorPtr(); // everything already computed
851 // TODO: ignore already computed SOLIDs
852 if ( !findSolidsWithLayers())
855 if ( !findFacesWithLayers() )
858 for ( unsigned i = 0; i < _sdVec.size(); ++i )
860 if ( ! makeLayer(_sdVec[i]) )
863 if ( ! inflate(_sdVec[i]) )
866 if ( ! refine(_sdVec[i]) )
872 addBoundaryElements();
874 makeGroupOfLE(); // debug
879 //================================================================================
881 * \brief Finds SOLIDs to compute using viscous layers. Fill _sdVec
883 //================================================================================
885 bool _ViscousBuilder::findSolidsWithLayers()
888 TopTools_IndexedMapOfShape allSolids;
889 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
890 _sdVec.reserve( allSolids.Extent());
892 SMESH_Gen* gen = _mesh->GetGen();
893 for ( int i = 1; i <= allSolids.Extent(); ++i )
895 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
896 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
897 if ( !algo ) continue;
898 // TODO: check if algo is hidden
899 const list <const SMESHDS_Hypothesis *> & allHyps =
900 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
901 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
902 const StdMeshers_ViscousLayers* viscHyp = 0;
903 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
904 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
907 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
910 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, proxyMesh ));
911 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
914 if ( _sdVec.empty() )
916 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
921 //================================================================================
925 //================================================================================
927 bool _ViscousBuilder::findFacesWithLayers()
929 // collect all faces to ignore defined by hyp
930 vector<TopoDS_Shape> ignoreFaces;
931 for ( unsigned i = 0; i < _sdVec.size(); ++i )
933 vector<TGeomID> ids = _sdVec[i]._hyp->GetIgnoreFaces();
934 for ( unsigned i = 0; i < ids.size(); ++i )
936 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
937 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
939 _ignoreShapeIds.insert( ids[i] );
940 ignoreFaces.push_back( s );
945 // ignore internal faces
946 SMESH_MesherHelper helper( *_mesh );
948 for ( unsigned i = 0; i < _sdVec.size(); ++i )
950 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
951 for ( ; exp.More(); exp.Next() )
953 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
954 if ( helper.NbAncestors( exp.Current(), *_mesh, TopAbs_SOLID ) > 1 )
956 _ignoreShapeIds.insert( faceInd );
957 ignoreFaces.push_back( exp.Current() );
958 if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face( exp.Current() ), getMeshDS()))
959 _sdVec[i]._reversedFaceIds.insert( faceInd );
964 // Find faces to shrink mesh on (solution 2 in issue 0020832);
965 TopTools_IndexedMapOfShape shapes;
966 for ( unsigned i = 0; i < _sdVec.size(); ++i )
969 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
970 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
972 const TopoDS_Shape& edge = shapes(iE);
973 // find 2 faces sharing an edge
975 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
978 const TopoDS_Shape* f = fIt->next();
979 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
980 FF[ int( !FF[0].IsNull()) ] = *f;
982 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
983 // check presence of layers on them
985 for ( int j = 0; j < 2; ++j )
986 ignore[j] = _ignoreShapeIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
987 if ( ignore[0] == ignore[1] ) continue; // nothing interesting
988 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
990 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
991 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
994 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
995 // the algo of the SOLID sharing the FACE does not support it
996 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
997 for ( unsigned i = 0; i < _sdVec.size(); ++i )
999 TopTools_MapOfShape noShrinkVertices;
1000 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1001 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1003 const TopoDS_Shape& fWOL = e2f->second;
1004 TGeomID edgeID = e2f->first;
1005 bool notShrinkFace = false;
1006 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1007 while ( soIt->more())
1009 const TopoDS_Shape* solid = soIt->next();
1010 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1011 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1012 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1013 notShrinkFace = true;
1014 for ( unsigned j = 0; j < _sdVec.size(); ++j )
1016 if ( _sdVec[j]._solid.IsSame( *solid ) )
1017 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1018 notShrinkFace = false;
1021 if ( notShrinkFace )
1023 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1024 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1025 noShrinkVertices.Add( vExp.Current() );
1028 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1029 // to the found not shrinked fWOL's
1030 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1031 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1033 TGeomID edgeID = e2f->first;
1034 TopoDS_Vertex VV[2];
1035 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1036 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1037 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1043 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1045 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1048 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1049 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1051 const TopoDS_Shape& vertex = shapes(iV);
1052 // find faces WOL sharing the vertex
1053 vector< TopoDS_Shape > facesWOL;
1054 int totalNbFaces = 0;
1055 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1056 while ( fIt->more())
1058 const TopoDS_Shape* f = fIt->next();
1059 const int fID = getMeshDS()->ShapeToIndex( *f );
1060 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1063 if ( _ignoreShapeIds.count ( fID ) && ! _sdVec[i]._noShrinkFaces.count( fID ))
1064 facesWOL.push_back( *f );
1067 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1068 continue; // no layers at this vertex or no WOL
1069 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1070 switch ( facesWOL.size() )
1074 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] )); break;
1078 // find an edge shared by 2 faces
1079 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1080 while ( eIt->more())
1082 const TopoDS_Shape* e = eIt->next();
1083 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1084 helper.IsSubShape( *e, facesWOL[1]))
1086 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1092 return error("Not yet supported case", _sdVec[i]._index);
1100 //================================================================================
1102 * \brief Create the inner surface of the viscous layer and prepare data for infation
1104 //================================================================================
1106 bool _ViscousBuilder::makeLayer(_SolidData& data)
1108 // get all sub-shapes to make layers on
1109 set<TGeomID> subIds, faceIds;
1110 subIds = data._noShrinkFaces;
1111 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1112 for ( ; exp.More(); exp.Next() )
1113 if ( ! _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1115 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1116 faceIds.insert( fSubM->GetId() );
1117 SMESH_subMeshIteratorPtr subIt =
1118 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1119 while ( subIt->more() )
1120 subIds.insert( subIt->next()->GetId() );
1123 // make a map to find new nodes on sub-shapes shared with other SOLID
1124 map< TGeomID, TNode2Edge* > s2neMap;
1125 map< TGeomID, TNode2Edge* >::iterator s2ne;
1126 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1127 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1129 TGeomID shapeInd = s2s->first;
1130 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1132 if ( _sdVec[i]._index == data._index ) continue;
1133 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1134 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1135 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1137 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1143 // Create temporary faces and _LayerEdge's
1145 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1147 data._stepSize = Precision::Infinite();
1148 data._stepSizeNodes[0] = 0;
1150 SMESH_MesherHelper helper( *_mesh );
1151 helper.SetSubShape( data._solid );
1152 helper.SetElementsOnShape(true);
1154 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1155 TNode2Edge::iterator n2e2;
1157 // collect _LayerEdge's of shapes they are based on
1158 const int nbShapes = getMeshDS()->MaxShapeIndex();
1159 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1161 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1163 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1164 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1166 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1167 SMESH_ProxyMesh::SubMesh* proxySub =
1168 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1170 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1171 while ( eIt->more() )
1173 const SMDS_MeshElement* face = eIt->next();
1174 newNodes.resize( face->NbCornerNodes() );
1175 double faceMaxCosin = -1;
1176 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1178 const SMDS_MeshNode* n = face->GetNode(i);
1179 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1180 if ( !(*n2e).second )
1183 _LayerEdge* edge = new _LayerEdge();
1185 edge->_nodes.push_back( n );
1186 const int shapeID = n->getshapeId();
1187 edgesByGeom[ shapeID ].push_back( edge );
1189 // set edge data or find already refined _LayerEdge and get data from it
1190 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1191 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1192 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1194 _LayerEdge* foundEdge = (*n2e2).second;
1195 edge->Copy( *foundEdge, helper );
1196 // location of the last node is modified but we can restore
1197 // it by node position on _sWOL stored by the node
1198 const_cast< SMDS_MeshNode* >
1199 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1203 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1204 if ( !setEdgeData( *edge, subIds, helper, data ))
1207 dumpMove(edge->_nodes.back());
1208 if ( edge->_cosin > 0.01 )
1210 if ( edge->_cosin > faceMaxCosin )
1211 faceMaxCosin = edge->_cosin;
1214 newNodes[ i ] = n2e->second->_nodes.back();
1216 // create a temporary face
1217 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1218 proxySub->AddElement( newFace );
1220 // compute inflation step size by min size of element on a convex surface
1221 if ( faceMaxCosin > 0.1 )
1222 limitStepSize( data, face, faceMaxCosin );
1223 } // loop on 2D elements on a FACE
1224 } // loop on FACEs of a SOLID
1226 data._epsilon = 1e-7;
1227 if ( data._stepSize < 1. )
1228 data._epsilon *= data._stepSize;
1230 // Put _LayerEdge's into a vector
1232 if ( !sortEdges( data, edgesByGeom ))
1235 // Set target nodes into _Simplex and _2NearEdges
1236 TNode2Edge::iterator n2e;
1237 for ( unsigned i = 0; i < data._edges.size(); ++i )
1239 if ( data._edges[i]->IsOnEdge())
1240 for ( int j = 0; j < 2; ++j )
1242 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1243 break; // _LayerEdge is shared by two _SolidData's
1244 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1245 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1246 return error("_LayerEdge not found by src node", data._index);
1247 n = (*n2e).second->_nodes.back();
1248 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1251 for ( unsigned j = 0; j < data._edges[i]->_simplices.size(); ++j )
1253 _Simplex& s = data._edges[i]->_simplices[j];
1254 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1255 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1263 //================================================================================
1265 * \brief Compute inflation step size by min size of element on a convex surface
1267 //================================================================================
1269 void _ViscousBuilder::limitStepSize( _SolidData& data,
1270 const SMDS_MeshElement* face,
1274 double minSize = 10 * data._stepSize;
1275 const int nbNodes = face->NbCornerNodes();
1276 for ( int i = 0; i < nbNodes; ++i )
1278 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1279 const SMDS_MeshNode* curN = face->GetNode( i );
1280 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1281 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1283 double dist = SMESH_MeshEditor::TNodeXYZ( face->GetNode(i)).Distance( nextN );
1284 if ( dist < minSize )
1285 minSize = dist, iN = i;
1288 double newStep = 0.8 * minSize / cosin;
1289 if ( newStep < data._stepSize )
1291 data._stepSize = newStep;
1292 data._stepSizeCoeff = 0.8 / cosin;
1293 data._stepSizeNodes[0] = face->GetNode( iN );
1294 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1298 //================================================================================
1300 * \brief Compute inflation step size by min size of element on a convex surface
1302 //================================================================================
1304 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1306 if ( minSize < data._stepSize )
1308 data._stepSize = minSize;
1309 if ( data._stepSizeNodes[0] )
1312 SMESH_MeshEditor::TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1313 data._stepSizeCoeff = data._stepSize / dist;
1318 //================================================================================
1320 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1322 //================================================================================
1324 bool _ViscousBuilder::sortEdges( _SolidData& data,
1325 vector< vector<_LayerEdge*> >& edgesByGeom)
1327 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1328 // boundry inclined at a sharp angle to the shape
1330 list< TGeomID > shapesToSmooth;
1332 SMESH_MesherHelper helper( *_mesh );
1335 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1337 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1338 if ( eS.empty() ) continue;
1339 TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1340 bool needSmooth = false;
1341 switch ( S.ShapeType() )
1345 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1346 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1348 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1349 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1350 if ( eV.empty() ) continue;
1351 double cosin = eV[0]->_cosin;
1353 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1357 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1358 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1360 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1361 eV[0]->_nodes[0], helper, ok);
1362 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1363 double angle = dir1.Angle( dir2 );
1364 cosin = cos( angle );
1366 needSmooth = ( cosin > 0.1 );
1372 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1374 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1375 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1376 if ( eE.empty() ) continue;
1377 if ( eE[0]->_sWOL.IsNull() )
1379 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1380 needSmooth = ( eE[i]->_cosin > 0.1 );
1384 const TopoDS_Face& F1 = TopoDS::Face( S );
1385 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1386 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1387 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1389 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1390 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1391 double angle = dir1.Angle( dir2 );
1392 double cosin = cos( angle );
1393 needSmooth = ( cosin > 0.1 );
1405 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1406 else shapesToSmooth.push_back ( iS );
1409 } // loop on edgesByGeom
1411 data._edges.reserve( data._n2eMap.size() );
1412 data._endEdgeToSmooth.clear();
1414 // first we put _LayerEdge's on shapes to smooth
1415 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1416 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1418 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1419 if ( eVec.empty() ) continue;
1420 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1421 data._endEdgeToSmooth.push_back( data._edges.size() );
1425 // then the rest _LayerEdge's
1426 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1428 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1429 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1436 //================================================================================
1438 * \brief Set data of _LayerEdge needed for smoothing
1439 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1441 //================================================================================
1443 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1444 const set<TGeomID>& subIds,
1445 SMESH_MesherHelper& helper,
1448 SMESH_MeshEditor editor(_mesh);
1450 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1451 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1455 edge._curvature = 0;
1457 // --------------------------
1458 // Compute _normal and _cosin
1459 // --------------------------
1462 edge._normal.SetCoord(0,0,0);
1464 int totalNbFaces = 0;
1466 gp_Vec du, dv, geomNorm;
1469 TGeomID shapeInd = node->getshapeId();
1470 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1471 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1472 TopoDS_Shape vertEdge;
1474 if ( onShrinkShape ) // one of faces the node is on has no layers
1476 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1477 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1479 // inflate from VERTEX along EDGE
1480 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1482 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1484 // inflate from VERTEX along FACE
1485 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1486 node, helper, normOK, &edge._cosin);
1490 // inflate from EDGE along FACE
1491 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1492 node, helper, normOK);
1495 else // layers are on all faces of SOLID the node is on
1497 // find indices of geom faces the node lies on
1498 set<TGeomID> faceIds;
1499 if ( posType == SMDS_TOP_FACE )
1501 faceIds.insert( node->getshapeId() );
1505 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1506 while ( fIt->more() )
1507 faceIds.insert( editor.FindShape(fIt->next()));
1510 set<TGeomID>::iterator id = faceIds.begin();
1512 for ( ; id != faceIds.end(); ++id )
1514 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1515 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1518 //nbLayerFaces += subIds.count( *id );
1519 F = TopoDS::Face( s );
1521 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1522 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1523 surface->D1( uv.X(),uv.Y(), p, du,dv );
1525 double size2 = geomNorm.SquareMagnitude();
1526 if ( size2 > numeric_limits<double>::min() )
1527 geomNorm /= sqrt( size2 );
1530 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1532 edge._normal += geomNorm.XYZ();
1534 if ( totalNbFaces == 0 )
1535 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1537 edge._normal /= totalNbFaces;
1542 edge._cosin = 0; break;
1544 case SMDS_TOP_EDGE: {
1545 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1546 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1547 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1548 edge._cosin = cos( angle );
1549 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1552 case SMDS_TOP_VERTEX: {
1553 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1554 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK);
1555 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1556 edge._cosin = cos( angle );
1557 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1561 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1565 double normSize = edge._normal.SquareModulus();
1566 if ( normSize < numeric_limits<double>::min() )
1567 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1569 edge._normal /= sqrt( normSize );
1571 // TODO: if ( !normOK ) then get normal by mesh faces
1573 // Set the rest data
1574 // --------------------
1575 if ( onShrinkShape )
1577 edge._sWOL = (*s2s).second;
1579 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1580 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1581 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1583 // set initial position which is parameters on _sWOL in this case
1584 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1586 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1587 edge._pos.push_back( gp_XYZ( u, 0, 0));
1588 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1592 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1593 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1594 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1599 edge._pos.push_back( SMESH_MeshEditor::TNodeXYZ( node ));
1601 if ( posType == SMDS_TOP_FACE )
1603 getSimplices( node, edge._simplices, _ignoreShapeIds, &data );
1604 double avgNormProj = 0, avgLen = 0;
1605 for ( unsigned i = 0; i < edge._simplices.size(); ++i )
1607 gp_XYZ vec = edge._pos.back() - SMESH_MeshEditor::TNodeXYZ( edge._simplices[i]._nPrev );
1608 avgNormProj += edge._normal * vec;
1609 avgLen += vec.Modulus();
1611 avgNormProj /= edge._simplices.size();
1612 avgLen /= edge._simplices.size();
1613 edge._curvature = _Curvature::New( avgNormProj, avgLen );
1617 // Set neighbour nodes for a _LayerEdge based on EDGE
1619 if ( posType == SMDS_TOP_EDGE /*||
1620 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1622 edge._2neibors = new _2NearEdges;
1623 // target node instead of source ones will be set later
1624 if ( ! findNeiborsOnEdge( &edge,
1625 edge._2neibors->_nodes[0],
1626 edge._2neibors->_nodes[1],
1629 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1630 edge._2neibors->_nodes[1],
1634 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1639 //================================================================================
1641 * \brief Find 2 neigbor nodes of a node on EDGE
1643 //================================================================================
1645 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
1646 const SMDS_MeshNode*& n1,
1647 const SMDS_MeshNode*& n2,
1650 const SMDS_MeshNode* node = edge->_nodes[0];
1651 const int shapeInd = node->getshapeId();
1652 SMESHDS_SubMesh* edgeSM = 0;
1653 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
1656 edgeSM = getMeshDS()->MeshElements( shapeInd );
1657 if ( !edgeSM || edgeSM->NbElements() == 0 )
1658 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
1662 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
1663 while ( eIt->more() && !n2 )
1665 const SMDS_MeshElement* e = eIt->next();
1666 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
1667 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
1670 if (!edgeSM->Contains(e)) continue;
1674 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
1675 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
1677 ( iN++ ? n2 : n1 ) = nNeibor;
1680 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
1684 //================================================================================
1686 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
1688 //================================================================================
1690 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
1691 const SMDS_MeshNode* n2,
1692 SMESH_MesherHelper& helper)
1694 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1697 gp_XYZ pos = SMESH_MeshEditor::TNodeXYZ( _nodes[0] );
1698 gp_XYZ vec1 = pos - SMESH_MeshEditor::TNodeXYZ( n1 );
1699 gp_XYZ vec2 = pos - SMESH_MeshEditor::TNodeXYZ( n2 );
1703 double sumLen = vec1.Modulus() + vec2.Modulus();
1704 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
1705 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
1706 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
1707 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
1708 if ( _curvature ) delete _curvature;
1709 _curvature = _Curvature::New( avgNormProj, avgLen );
1711 // if ( _curvature )
1712 // cout << _nodes[0]->GetID()
1713 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
1714 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
1715 // << _curvature->lenDelta(0) << endl;
1720 if ( _sWOL.IsNull() )
1722 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
1723 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
1724 gp_XYZ plnNorm = dirE ^ _normal;
1725 double proj0 = plnNorm * vec1;
1726 double proj1 = plnNorm * vec2;
1727 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
1729 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
1730 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
1735 //================================================================================
1737 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
1738 * this and other _LayerEdge's are inflated along a FACE or an EDGE
1740 //================================================================================
1742 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
1744 _nodes = other._nodes;
1745 _normal = other._normal;
1747 _lenFactor = other._lenFactor;
1748 _cosin = other._cosin;
1749 _sWOL = other._sWOL;
1750 _2neibors = other._2neibors;
1751 _curvature = 0; std::swap( _curvature, other._curvature );
1752 _2neibors = 0; std::swap( _2neibors, other._2neibors );
1754 if ( _sWOL.ShapeType() == TopAbs_EDGE )
1756 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
1757 _pos.push_back( gp_XYZ( u, 0, 0));
1761 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
1762 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1766 //================================================================================
1768 * \brief Set _cosin and _lenFactor
1770 //================================================================================
1772 void _LayerEdge::SetCosin( double cosin )
1775 _lenFactor = ( _cosin > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
1778 //================================================================================
1780 * \brief Fills a vector<_Simplex >
1782 //================================================================================
1784 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
1785 vector<_Simplex>& simplices,
1786 const set<TGeomID>& ingnoreShapes,
1787 const _SolidData* dataToCheckOri)
1789 SMESH_MeshEditor editor( _mesh );
1790 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1791 while ( fIt->more() )
1793 const SMDS_MeshElement* f = fIt->next();
1794 const TGeomID shapeInd = editor.FindShape( f );
1795 if ( ingnoreShapes.count( shapeInd )) continue;
1796 const int nbNodes = f->NbCornerNodes();
1797 int srcInd = f->GetNodeIndex( node );
1798 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
1799 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
1800 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
1801 std::swap( nPrev, nNext );
1802 simplices.push_back( _Simplex( nPrev, nNext ));
1804 simplices.resize( simplices.size() );
1807 //================================================================================
1809 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
1811 //================================================================================
1813 void _ViscousBuilder::makeGroupOfLE()
1816 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
1818 if ( _sdVec[i]._edges.empty() ) continue;
1819 // string name = SMESH_Comment("_LayerEdge's_") << i;
1821 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
1822 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
1823 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
1825 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
1826 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1828 _LayerEdge* le = _sdVec[i]._edges[j];
1829 for ( unsigned iN = 1; iN < le->_nodes.size(); ++iN )
1830 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
1831 << ", " << le->_nodes[iN]->GetID() <<"])");
1832 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
1836 dumpFunction( SMESH_Comment("makeNormals") << i );
1837 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1839 _LayerEdge& edge = *_sdVec[i]._edges[j];
1840 SMESH_MeshEditor::TNodeXYZ nXYZ( edge._nodes[0] );
1841 nXYZ += edge._normal * _sdVec[i]._stepSize;
1842 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
1843 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
1847 // name = SMESH_Comment("tmp_faces ") << i;
1848 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
1849 // gDS = (SMESHDS_Group*)g->GetGroupDS();
1850 // SMESH_MeshEditor editor( _mesh );
1851 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
1852 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
1853 for ( ; fExp.More(); fExp.Next() )
1855 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
1857 SMDS_ElemIteratorPtr fIt = sm->GetElements();
1858 while ( fIt->more())
1860 const SMDS_MeshElement* e = fIt->next();
1861 SMESH_Comment cmd("mesh.AddFace([");
1862 for ( int j=0; j < e->NbCornerNodes(); ++j )
1863 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
1865 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
1866 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
1875 //================================================================================
1877 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
1879 //================================================================================
1881 bool _ViscousBuilder::inflate(_SolidData& data)
1883 SMESH_MesherHelper helper( *_mesh );
1885 // Limit inflation step size by geometry size found by itersecting
1886 // normals of _LayerEdge's with mesh faces
1887 double geomSize = Precision::Infinite(), intersecDist;
1888 SMESH_MeshEditor editor( _mesh );
1889 auto_ptr<SMESH_ElementSearcher> searcher
1890 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
1891 for ( unsigned i = 0; i < data._edges.size(); ++i )
1893 if ( data._edges[i]->IsOnEdge() ) continue;
1894 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
1895 if ( geomSize > intersecDist )
1896 geomSize = intersecDist;
1898 if ( data._stepSize > 0.3 * geomSize )
1899 limitStepSize( data, 0.3 * geomSize );
1901 const double tgtThick = data._hyp->GetTotalThickness();
1902 if ( data._stepSize > tgtThick )
1903 limitStepSize( data, tgtThick );
1905 if ( data._stepSize < 1. )
1906 data._epsilon = data._stepSize * 1e-7;
1909 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
1912 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
1913 int nbSteps = 0, nbRepeats = 0;
1914 while ( 1.01 * avgThick < tgtThick )
1916 // new target length
1917 curThick += data._stepSize;
1918 if ( curThick > tgtThick )
1920 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
1924 // Elongate _LayerEdge's
1925 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
1926 for ( unsigned i = 0; i < data._edges.size(); ++i )
1928 data._edges[i]->SetNewLength( curThick, helper );
1933 if ( !updateNormals( data, helper ) )
1936 // Improve and check quality
1937 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
1941 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
1942 for ( unsigned i = 0; i < data._edges.size(); ++i )
1944 data._edges[i]->InvalidateStep( nbSteps+1 );
1948 break; // no more inflating possible
1952 // Evaluate achieved thickness
1954 for ( unsigned i = 0; i < data._edges.size(); ++i )
1955 avgThick += data._edges[i]->_len;
1956 avgThick /= data._edges.size();
1958 cout << "-- Thickness " << avgThick << " reached" << endl;
1961 if ( distToIntersection < avgThick*1.5 )
1964 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
1965 << avgThick << " ) * 1.5" << endl;
1970 limitStepSize( data, 0.25 * distToIntersection );
1971 if ( data._stepSizeNodes[0] )
1972 data._stepSize = data._stepSizeCoeff *
1973 SMESH_MeshEditor::TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1977 return error("failed at the very first inflation step", data._index);
1982 //================================================================================
1984 * \brief Improve quality of layer inner surface and check intersection
1986 //================================================================================
1988 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
1990 double & distToIntersection)
1992 if ( data._endEdgeToSmooth.empty() )
1993 return true; // no shapes needing smoothing
1995 bool moved, improved;
1997 SMESH_MesherHelper helper(*_mesh);
1998 Handle(Geom_Surface) surface;
2002 for ( unsigned iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2005 iEnd = data._endEdgeToSmooth[ iS ];
2007 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2008 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2010 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2011 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2012 helper.SetSubShape( F );
2013 surface = BRep_Tool::Surface( F );
2018 F.Nullify(); surface.Nullify();
2020 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2022 if ( data._edges[ iBeg ]->IsOnEdge() )
2024 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2029 for ( int i = iBeg; i < iEnd; ++i )
2031 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2033 dumpCmd( SMESH_Comment("# end step ")<<step);
2035 while ( moved && step++ < 5 );
2042 int step = 0, badNb = 0; moved = true;
2043 while (( ++step <= 5 && moved ) || improved )
2045 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2046 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2047 int oldBadNb = badNb;
2050 for ( int i = iBeg; i < iEnd; ++i )
2051 moved |= data._edges[i]->Smooth(badNb);
2052 improved = ( badNb < oldBadNb );
2059 for ( int i = iBeg; i < iEnd; ++i )
2061 _LayerEdge* edge = data._edges[i];
2062 SMESH_MeshEditor::TNodeXYZ tgtXYZ( edge->_nodes.back() );
2063 for ( unsigned j = 0; j < edge->_simplices.size(); ++j )
2064 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2066 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2067 << " "<< edge->_simplices[j]._nPrev->GetID()
2068 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2076 } // loop on shapes to smooth
2078 // Check if the last segments of _LayerEdge intersects 2D elements;
2079 // checked elements are either temporary faces or faces on surfaces w/o the layers
2081 SMESH_MeshEditor editor( _mesh );
2082 auto_ptr<SMESH_ElementSearcher> searcher
2083 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2085 distToIntersection = Precision::Infinite();
2087 const SMDS_MeshElement* intFace = 0, *closestFace = 0;
2089 for ( unsigned i = 0; i < data._edges.size(); ++i )
2091 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2093 if ( distToIntersection > dist )
2094 distToIntersection = dist, closestFace = intFace, iLE = i;
2099 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2100 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2101 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2102 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2103 << ") distance = " << distToIntersection<< endl;
2110 //================================================================================
2112 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2113 * _LayerEdge's on neighbor EDGE's
2115 //================================================================================
2117 bool _ViscousBuilder::updateNormals( _SolidData& data,
2118 SMESH_MesherHelper& helper )
2120 // make temporary quadrangles got by extrusion of
2121 // mesh edges along _LayerEdge._normal's
2123 vector< const SMDS_MeshElement* > tmpFaces;
2125 set< SMESH_TLink > extrudedLinks; // contains target nodes
2126 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2128 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2129 for ( unsigned i = 0; i < data._edges.size(); ++i )
2131 _LayerEdge* edge = data._edges[i];
2132 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2133 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2134 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2136 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2137 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2138 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2139 if ( !link_isnew.second )
2141 extrudedLinks.erase( link_isnew.first );
2142 continue; // already extruded and will no more encounter
2144 // look for a _LayerEdge containg tgt2
2145 // _LayerEdge* neiborEdge = 0;
2146 // unsigned di = 0; // check _edges[i+di] and _edges[i-di]
2147 // while ( !neiborEdge && ++di <= data._edges.size() )
2149 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2150 // neiborEdge = data._edges[i+di];
2151 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2152 // neiborEdge = data._edges[i-di];
2154 // if ( !neiborEdge )
2155 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2156 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2158 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2159 tmpFaces.push_back( f );
2161 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2162 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2163 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2168 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2169 // Perform two loops on _LayerEdge on EDGE's:
2170 // 1) to find and fix intersection
2171 // 2) to check that no new intersection appears as result of 1)
2173 SMESH_MeshEditor editor( _mesh );
2174 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2176 auto_ptr<SMESH_ElementSearcher> searcher ( editor.GetElementSearcher( fIt ));
2178 // 1) Find intersections
2180 const SMDS_MeshElement* face;
2181 map< _LayerEdge*, set< _LayerEdge* > > edge2CloseEdge;
2183 const double eps = data._epsilon * data._epsilon;
2184 for ( unsigned i = 0; i < data._edges.size(); ++i )
2186 _LayerEdge* edge = data._edges[i];
2187 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2188 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2190 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2191 set< _LayerEdge* > & ee = edge2CloseEdge[ edge ];
2192 ee.insert( f->_le1 );
2193 ee.insert( f->_le2 );
2194 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
2195 edge2CloseEdge[ f->_le1 ].insert( edge );
2196 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
2197 edge2CloseEdge[ f->_le2 ].insert( edge );
2201 // Set _LayerEdge._normal
2203 if ( !edge2CloseEdge.empty() )
2205 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2207 map< _LayerEdge*, set< _LayerEdge* > >::iterator e2ee = edge2CloseEdge.begin();
2208 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2210 _LayerEdge* edge1 = e2ee->first;
2211 _LayerEdge* edge2 = 0;
2212 set< _LayerEdge* >& ee = e2ee->second;
2214 // find EDGEs the edges reside
2216 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2217 if ( S.ShapeType() != TopAbs_EDGE )
2218 continue; // TODO: find EDGE by VERTEX
2219 E1 = TopoDS::Edge( S );
2220 set< _LayerEdge* >::iterator eIt = ee.begin();
2221 while ( E2.IsNull() && eIt != ee.end())
2223 _LayerEdge* e2 = *eIt++;
2224 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2225 if ( S.ShapeType() == TopAbs_EDGE )
2226 E2 = TopoDS::Edge( S ), edge2 = e2;
2228 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2230 // find 3 FACEs sharing 2 EDGEs
2232 TopoDS_Face FF1[2], FF2[2];
2233 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2234 while ( fIt->more() && FF1[1].IsNull())
2236 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2237 if ( helper.IsSubShape( *F, data._solid))
2238 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2240 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2241 while ( fIt->more() && FF2[1].IsNull())
2243 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2244 if ( helper.IsSubShape( *F, data._solid))
2245 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2247 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2248 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2249 std::swap( FF1[0], FF1[1] );
2250 if ( FF2[0].IsSame( FF1[0]) )
2251 std::swap( FF2[0], FF2[1] );
2252 if ( FF1[0].IsNull() || FF2[0].IsNull() )
2255 // // get a new normal for edge1
2257 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2258 if ( edge1->_cosin < 0 )
2259 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2260 if ( edge2->_cosin < 0 )
2261 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2262 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2263 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2264 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2265 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2266 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2267 // newNorm.Normalize();
2269 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2270 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2271 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2272 newNorm.Normalize();
2274 edge1->_normal = newNorm.XYZ();
2276 // update data of edge1 depending on _normal
2277 const SMDS_MeshNode *n1, *n2;
2278 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2279 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2280 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2282 edge1->SetDataByNeighbors( n1, n2, helper );
2284 if ( edge1->_cosin < 0 )
2287 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2288 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2289 edge1->SetCosin( cos( angle ));
2291 // limit data._stepSize
2292 if ( edge1->_cosin > 0.1 )
2294 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2295 while ( fIt->more() )
2296 limitStepSize( data, fIt->next(), edge1->_cosin );
2298 // set new XYZ of target node
2299 edge1->InvalidateStep( 1 );
2301 edge1->SetNewLength( data._stepSize, helper );
2304 // Update normals and other dependent data of not intersecting _LayerEdge's
2305 // neighboring the intersecting ones
2307 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2309 _LayerEdge* edge1 = e2ee->first;
2310 if ( !edge1->_2neibors )
2312 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2314 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2315 if ( edge2CloseEdge.count ( neighbor ))
2316 continue; // j-th neighbor is also intersected
2317 _LayerEdge* prevEdge = edge1;
2318 const int nbSteps = 6;
2319 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2321 if ( !neighbor->_2neibors )
2322 break; // neighbor is on VERTEX
2324 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2325 if ( nextEdge == prevEdge )
2326 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2327 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2328 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
2329 double r = double(step-1)/nbSteps;
2330 if ( !nextEdge->_2neibors )
2333 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2334 newNorm.Normalize();
2336 neighbor->_normal = newNorm;
2337 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2338 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2340 neighbor->InvalidateStep( 1 );
2342 neighbor->SetNewLength( data._stepSize, helper );
2344 // goto the next neighbor
2345 prevEdge = neighbor;
2346 neighbor = nextEdge;
2352 // 2) Check absence of intersections
2355 for ( unsigned i = 0 ; i < tmpFaces.size(); ++i )
2361 //================================================================================
2363 * \brief Looks for intersection of it's last segment with faces
2364 * \param distance - returns shortest distance from the last node to intersection
2366 //================================================================================
2368 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
2370 const double& epsilon,
2371 const SMDS_MeshElement** face)
2373 vector< const SMDS_MeshElement* > suspectFaces;
2375 gp_Ax1 lastSegment = LastSegment(segLen);
2376 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2378 bool segmentIntersected = false;
2379 distance = Precision::Infinite();
2380 int iFace = -1; // intersected face
2381 for ( unsigned j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
2383 const SMDS_MeshElement* face = suspectFaces[j];
2384 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
2385 face->GetNodeIndex( _nodes[0] ) >= 0 )
2386 continue; // face sharing _LayerEdge node
2387 const int nbNodes = face->NbCornerNodes();
2388 bool intFound = false;
2390 SMDS_MeshElement::iterator nIt = face->begin_nodes();
2393 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
2397 const SMDS_MeshNode* tria[3];
2400 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
2403 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
2409 if ( dist < segLen*(1.01))
2410 segmentIntersected = true;
2411 if ( distance > dist )
2412 distance = dist, iFace = j;
2415 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
2416 // if ( distance && iFace > -1 )
2418 // // distance is used to limit size of inflation step which depends on
2419 // // whether the intersected face bears viscous layers or not
2420 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
2424 if ( segmentIntersected )
2427 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
2428 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
2429 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
2430 << ", intersection with face ("
2431 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2432 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
2433 << ") distance = " << distance - segLen<< endl;
2439 return segmentIntersected;
2442 //================================================================================
2444 * \brief Returns size and direction of the last segment
2446 //================================================================================
2448 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
2450 // find two non-coincident positions
2451 gp_XYZ orig = _pos.back();
2453 int iPrev = _pos.size() - 2;
2454 while ( iPrev >= 0 )
2456 dir = orig - _pos[iPrev];
2457 if ( dir.SquareModulus() > 1e-100 )
2467 segDir.SetLocation( SMESH_MeshEditor::TNodeXYZ( _nodes[0] ));
2468 segDir.SetDirection( _normal );
2473 gp_Pnt pPrev = _pos[ iPrev ];
2474 if ( !_sWOL.IsNull() )
2476 TopLoc_Location loc;
2477 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2480 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2481 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
2485 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2486 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
2488 dir = SMESH_MeshEditor::TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
2490 segDir.SetLocation( pPrev );
2491 segDir.SetDirection( dir );
2492 segLen = dir.Modulus();
2498 //================================================================================
2500 * \brief Test intersection of the last segment with a given triangle
2501 * using Moller-Trumbore algorithm
2502 * Intersection is detected if distance to intersection is less than _LayerEdge._len
2504 //================================================================================
2506 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
2507 const SMDS_MeshNode* n0,
2508 const SMDS_MeshNode* n1,
2509 const SMDS_MeshNode* n2,
2511 const double& EPSILON) const
2513 //const double EPSILON = 1e-6;
2515 gp_XYZ orig = lastSegment.Location().XYZ();
2516 gp_XYZ dir = lastSegment.Direction().XYZ();
2518 SMESH_MeshEditor::TNodeXYZ vert0( n0 );
2519 SMESH_MeshEditor::TNodeXYZ vert1( n1 );
2520 SMESH_MeshEditor::TNodeXYZ vert2( n2 );
2522 /* calculate distance from vert0 to ray origin */
2523 gp_XYZ tvec = orig - vert0;
2525 if ( tvec * dir > EPSILON )
2526 // intersected face is at back side of the temporary face this _LayerEdge belongs to
2529 gp_XYZ edge1 = vert1 - vert0;
2530 gp_XYZ edge2 = vert2 - vert0;
2532 /* begin calculating determinant - also used to calculate U parameter */
2533 gp_XYZ pvec = dir ^ edge2;
2535 /* if determinant is near zero, ray lies in plane of triangle */
2536 double det = edge1 * pvec;
2538 if (det > -EPSILON && det < EPSILON)
2540 double inv_det = 1.0 / det;
2542 /* calculate U parameter and test bounds */
2543 double u = ( tvec * pvec ) * inv_det;
2544 if (u < 0.0 || u > 1.0)
2547 /* prepare to test V parameter */
2548 gp_XYZ qvec = tvec ^ edge1;
2550 /* calculate V parameter and test bounds */
2551 double v = (dir * qvec) * inv_det;
2552 if ( v < 0.0 || u + v > 1.0 )
2555 /* calculate t, ray intersects triangle */
2556 t = (edge2 * qvec) * inv_det;
2558 // if (det < EPSILON)
2561 // /* calculate distance from vert0 to ray origin */
2562 // gp_XYZ tvec = orig - vert0;
2564 // /* calculate U parameter and test bounds */
2565 // double u = tvec * pvec;
2566 // if (u < 0.0 || u > det)
2569 // /* prepare to test V parameter */
2570 // gp_XYZ qvec = tvec ^ edge1;
2572 // /* calculate V parameter and test bounds */
2573 // double v = dir * qvec;
2574 // if (v < 0.0 || u + v > det)
2577 // /* calculate t, scale parameters, ray intersects triangle */
2578 // double t = edge2 * qvec;
2579 // double inv_det = 1.0 / det;
2587 //================================================================================
2589 * \brief Perform smooth of _LayerEdge's based on EDGE's
2590 * \retval bool - true if node has been moved
2592 //================================================================================
2594 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
2595 const TopoDS_Face& F,
2596 SMESH_MesherHelper& helper)
2598 ASSERT( IsOnEdge() );
2600 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
2601 SMESH_MeshEditor::TNodeXYZ oldPos( tgtNode );
2602 double dist01, distNewOld;
2604 SMESH_MeshEditor::TNodeXYZ p0( _2neibors->_nodes[0]);
2605 SMESH_MeshEditor::TNodeXYZ p1( _2neibors->_nodes[1]);
2606 dist01 = p0.Distance( _2neibors->_nodes[1] );
2608 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
2609 double lenDelta = 0;
2612 lenDelta = _curvature->lenDelta( _len );
2613 newPos.ChangeCoord() += _normal * lenDelta;
2616 distNewOld = newPos.Distance( oldPos );
2620 if ( _2neibors->_plnNorm )
2622 // put newPos on the plane defined by source node and _plnNorm
2623 gp_XYZ new2src = SMESH_MeshEditor::TNodeXYZ( _nodes[0] ) - newPos.XYZ();
2624 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
2625 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
2627 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2628 _pos.back() = newPos.XYZ();
2632 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2633 gp_XY uv( Precision::Infinite(), 0 );
2634 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
2635 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
2637 newPos = surface->Value( uv.X(), uv.Y() );
2638 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2641 if ( _curvature && lenDelta < 0 )
2643 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
2644 _len -= prevPos.Distance( oldPos );
2645 _len += prevPos.Distance( newPos );
2647 bool moved = distNewOld > dist01/50;
2649 dumpMove( tgtNode ); // debug
2654 //================================================================================
2656 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
2657 * \retval bool - true if _tgtNode has been moved
2659 //================================================================================
2661 bool _LayerEdge::Smooth(int& badNb)
2663 if ( _simplices.size() < 2 )
2664 return false; // _LayerEdge inflated along EDGE or FACE
2666 // compute new position for the last _pos
2667 gp_XYZ newPos (0,0,0);
2668 for ( unsigned i = 0; i < _simplices.size(); ++i )
2669 newPos += SMESH_MeshEditor::TNodeXYZ( _simplices[i]._nPrev );
2670 newPos /= _simplices.size();
2673 newPos += _normal * _curvature->lenDelta( _len );
2675 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
2676 // if ( _cosin < -0.1)
2678 // // Avoid decreasing length of edge on concave surface
2679 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
2680 // gp_Vec newMove( prevPos, newPos );
2681 // newPos = _pos.back() + newMove.XYZ();
2683 // else if ( _cosin > 0.3 )
2685 // // Avoid increasing length of edge too much
2688 // count quality metrics (orientation) of tetras around _tgtNode
2690 SMESH_MeshEditor::TNodeXYZ tgtXYZ( _nodes.back() );
2691 for ( unsigned i = 0; i < _simplices.size(); ++i )
2692 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
2695 for ( unsigned i = 0; i < _simplices.size(); ++i )
2696 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
2698 if ( nbOkAfter < nbOkBefore )
2701 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
2703 _len -= prevPos.Distance(SMESH_MeshEditor::TNodeXYZ( n ));
2704 _len += prevPos.Distance(newPos);
2706 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
2707 _pos.back() = newPos;
2709 badNb += _simplices.size() - nbOkAfter;
2716 //================================================================================
2718 * \brief Add a new segment to _LayerEdge during inflation
2720 //================================================================================
2722 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
2724 if ( _len - len > -1e-6 )
2726 _pos.push_back( _pos.back() );
2730 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
2731 SMESH_MeshEditor::TNodeXYZ oldXYZ( n );
2732 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
2733 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
2735 _pos.push_back( nXYZ );
2737 if ( !_sWOL.IsNull() )
2740 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2742 double u = Precision::Infinite(); // to force projection w/o distance check
2743 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
2744 _pos.back().SetCoord( u, 0, 0 );
2745 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
2746 pos->SetUParameter( u );
2750 gp_XY uv( Precision::Infinite(), 0 );
2751 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
2752 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
2753 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
2754 pos->SetUParameter( uv.X() );
2755 pos->SetVParameter( uv.Y() );
2757 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
2759 dumpMove( n ); //debug
2762 //================================================================================
2764 * \brief Remove last inflation step
2766 //================================================================================
2768 void _LayerEdge::InvalidateStep( int curStep )
2770 if ( _pos.size() > curStep )
2772 _pos.resize( curStep );
2773 gp_Pnt nXYZ = _pos.back();
2774 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
2775 if ( !_sWOL.IsNull() )
2777 TopLoc_Location loc;
2778 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2780 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
2781 pos->SetUParameter( nXYZ.X() );
2783 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2784 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
2788 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
2789 pos->SetUParameter( nXYZ.X() );
2790 pos->SetVParameter( nXYZ.Y() );
2791 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2792 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
2795 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
2800 //================================================================================
2802 * \brief Create layers of prisms
2804 //================================================================================
2806 bool _ViscousBuilder::refine(_SolidData& data)
2808 SMESH_MesherHelper helper( *_mesh );
2809 helper.SetSubShape( data._solid );
2810 helper.SetElementsOnShape(false);
2812 Handle(Geom_Curve) curve;
2813 Handle(Geom_Surface) surface;
2814 TopoDS_Edge geomEdge;
2815 TopoDS_Face geomFace;
2816 TopLoc_Location loc;
2817 double f,l, u/*, distXYZ[4]*/;
2821 for ( unsigned i = 0; i < data._edges.size(); ++i )
2823 _LayerEdge& edge = *data._edges[i];
2825 // get accumulated length of segments
2826 vector< double > segLen( edge._pos.size() );
2828 for ( unsigned j = 1; j < edge._pos.size(); ++j )
2829 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
2831 // allocate memory for new nodes if it is not yet refined
2832 const SMDS_MeshNode* tgtNode = edge._nodes.back();
2833 if ( edge._nodes.size() == 2 )
2835 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
2837 edge._nodes.back() = tgtNode;
2839 if ( !edge._sWOL.IsNull() )
2841 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
2842 // restore position of the last node
2846 geomEdge = TopoDS::Edge( edge._sWOL );
2847 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
2848 // double u = helper.GetNodeU( tgtNode );
2849 // p = curve->Value( u );
2853 geomFace = TopoDS::Face( edge._sWOL );
2854 surface = BRep_Tool::Surface( geomFace, loc );
2855 // gp_XY uv = helper.GetNodeUV( tgtNode );
2856 // p = surface->Value( uv.X(), uv.Y() );
2858 // p.Transform( loc );
2859 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
2861 // calculate height of the first layer
2863 const double T = segLen.back(); //data._hyp.GetTotalThickness();
2864 const double f = data._hyp->GetStretchFactor();
2865 const int N = data._hyp->GetNumberLayers();
2866 const double fPowN = pow( f, N );
2867 if ( fPowN - 1 <= numeric_limits<double>::min() )
2870 h0 = T * ( f - 1 )/( fPowN - 1 );
2872 const double zeroLen = std::numeric_limits<double>::min();
2874 // create intermediate nodes
2875 double hSum = 0, hi = h0/f;
2877 for ( unsigned iStep = 1; iStep < edge._nodes.size(); ++iStep )
2879 // compute an intermediate position
2882 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
2884 int iPrevSeg = iSeg-1;
2885 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
2887 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
2888 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
2890 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
2891 if ( !edge._sWOL.IsNull() )
2893 // compute XYZ by parameters <pos>
2897 pos = curve->Value( u ).Transformed(loc);
2901 uv.SetCoord( pos.X(), pos.Y() );
2902 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
2905 // create or update the node
2908 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
2909 if ( !edge._sWOL.IsNull() )
2912 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
2914 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
2918 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
2923 if ( !edge._sWOL.IsNull() )
2925 // make average pos from new and current parameters
2928 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
2929 pos = curve->Value( u ).Transformed(loc);
2933 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
2934 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
2937 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
2942 // TODO: make quadratic prisms and polyhedrons(?)
2944 helper.SetElementsOnShape(true);
2946 TopExp_Explorer exp( data._solid, TopAbs_FACE );
2947 for ( ; exp.More(); exp.Next() )
2949 if ( _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
2951 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
2952 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
2953 vector< vector<const SMDS_MeshNode*>* > nnVec;
2954 while ( fIt->more() )
2956 const SMDS_MeshElement* face = fIt->next();
2957 int nbNodes = face->NbCornerNodes();
2958 nnVec.resize( nbNodes );
2959 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
2960 for ( int iN = 0; iN < nbNodes; ++iN )
2962 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
2963 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
2966 int nbZ = nnVec[0]->size();
2970 for ( int iZ = 1; iZ < nbZ; ++iZ )
2971 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
2972 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
2975 for ( int iZ = 1; iZ < nbZ; ++iZ )
2976 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
2977 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
2978 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
2979 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
2982 return error("Not supported type of element", data._index);
2989 //================================================================================
2991 * \brief Shrink 2D mesh on faces to let space for inflated layers
2993 //================================================================================
2995 bool _ViscousBuilder::shrink()
2997 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
2998 // inflated along FACE or EDGE)
2999 map< TGeomID, _SolidData* > f2sdMap;
3000 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
3002 _SolidData& data = _sdVec[i];
3003 TopTools_MapOfShape FFMap;
3004 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3005 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3006 if ( s2s->second.ShapeType() == TopAbs_FACE )
3008 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3010 if ( FFMap.Add( (*s2s).second ))
3011 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3012 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3013 // by StdMeshers_QuadToTriaAdaptor
3014 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3016 SMESH_ProxyMesh::SubMesh* proxySub =
3017 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3018 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3019 while ( fIt->more() )
3020 proxySub->AddElement( fIt->next() );
3025 SMESH_MesherHelper helper( *_mesh );
3028 map< int, _Shrinker1D > e2shrMap;
3030 // loop on FACES to srink mesh on
3031 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3032 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3034 _SolidData& data = *f2sd->second;
3035 TNode2Edge& n2eMap = data._n2eMap;
3036 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3037 const bool reverse = ( data._reversedFaceIds.count( f2sd->first ));
3039 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3041 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3042 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3044 helper.SetSubShape(F);
3046 // ===========================
3047 // Prepare data for shrinking
3048 // ===========================
3050 // Collect nodes to smooth as src nodes are not yet replaced by tgt ones
3051 // and thus all nodes on FACE connected to 2d elements are to be smoothed
3052 vector < const SMDS_MeshNode* > smoothNodes;
3054 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3055 while ( nIt->more() )
3057 const SMDS_MeshNode* n = nIt->next();
3058 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3059 smoothNodes.push_back( n );
3062 // Find out face orientation
3064 const set<TGeomID> ignoreShapes;
3065 if ( !smoothNodes.empty() )
3067 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0] );
3068 vector<_Simplex> simplices;
3069 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3070 if ( simplices[0].IsForward(uv, F, helper,refSign) != (!reverse))
3074 // Find _LayerEdge's inflated along F
3075 vector< _LayerEdge* > lEdges;
3077 SMESH_subMeshIteratorPtr subIt =
3078 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3079 while ( subIt->more() )
3081 SMESH_subMesh* sub = subIt->next();
3082 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3083 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3085 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3086 while ( nIt->more() )
3088 _LayerEdge* edge = n2eMap[ nIt->next() ];
3089 lEdges.push_back( edge );
3090 prepareEdgeToShrink( *edge, F, helper, smDS );
3095 // Replace source nodes by target nodes in mesh faces to shrink
3096 const SMDS_MeshNode* nodes[20];
3097 for ( unsigned i = 0; i < lEdges.size(); ++i )
3099 _LayerEdge& edge = *lEdges[i];
3100 const SMDS_MeshNode* srcNode = edge._nodes[0];
3101 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3102 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3103 while ( fIt->more() )
3105 const SMDS_MeshElement* f = fIt->next();
3106 if ( !smDS->Contains( f ))
3108 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3109 for ( int iN = 0; iN < f->NbNodes(); ++iN )
3111 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3112 nodes[iN] = ( n == srcNode ? tgtNode : n );
3114 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3118 // Create _SmoothNode's on face F
3119 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3121 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3122 for ( unsigned i = 0; i < smoothNodes.size(); ++i )
3124 const SMDS_MeshNode* n = smoothNodes[i];
3125 nodesToSmooth[ i ]._node = n;
3126 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3127 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes );
3132 //if ( nodesToSmooth.empty() ) continue;
3134 // Find EDGE's to shrink
3135 set< _Shrinker1D* > eShri1D;
3137 for ( unsigned i = 0; i < lEdges.size(); ++i )
3139 _LayerEdge* edge = lEdges[i];
3140 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3142 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3143 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3144 eShri1D.insert( & srinker );
3145 srinker.AddEdge( edge, helper );
3146 // restore params of nodes on EGDE if the EDGE has been already
3147 // srinked while srinking another FACE
3148 srinker.RestoreParams();
3153 // ==================
3154 // Perform shrinking
3155 // ==================
3157 bool shrinked = true;
3158 int badNb, shriStep=0, smooStep=0;
3161 // Move boundary nodes (actually just set new UV)
3162 // -----------------------------------------------
3163 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep++ ); // debug
3165 for ( unsigned i = 0; i < lEdges.size(); ++i )
3167 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3173 // Move nodes on EDGE's
3174 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3175 for ( ; shr != eShri1D.end(); ++shr )
3176 (*shr)->Compute( /*set3D=*/false, helper );
3179 // -----------------
3180 int nbNoImpSteps = 0;
3183 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3185 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3187 int oldBadNb = badNb;
3190 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3192 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,/*set3D=*/false );
3194 if ( badNb < oldBadNb )
3202 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3204 // No wrongly shaped faces remain; final smooth. Set node XYZ
3205 for ( int st = 3; st; --st )
3207 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3208 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3209 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,/*set3D=*/st==1 );
3212 // Set event listener to clear FACE sub-mesh together with SOLID sub-mesh
3213 _SrinkShapeListener::ToClearSubMeshWithSolid( sm, data._solid );
3215 }// loop on FACES to srink mesh on
3218 // Replace source nodes by target nodes in shrinked mesh edges
3220 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3221 for ( ; e2shr != e2shrMap.end(); ++e2shr )
3222 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3227 //================================================================================
3229 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3231 //================================================================================
3233 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
3234 const TopoDS_Face& F,
3235 SMESH_MesherHelper& helper,
3236 const SMESHDS_SubMesh* faceSubMesh)
3238 const SMDS_MeshNode* srcNode = edge._nodes[0];
3239 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3243 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3245 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3246 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3247 gp_Vec2d uvDir( srcUV, tgtUV );
3248 double uvLen = uvDir.Magnitude();
3250 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3252 // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3253 vector<const SMDS_MeshElement*> faces;
3254 multimap< double, const SMDS_MeshNode* > proj2node;
3255 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3256 while ( fIt->more() )
3258 const SMDS_MeshElement* f = fIt->next();
3259 if ( faceSubMesh->Contains( f ))
3260 faces.push_back( f );
3262 for ( unsigned i = 0; i < faces.size(); ++i )
3264 const int nbNodes = faces[i]->NbCornerNodes();
3265 for ( int j = 0; j < nbNodes; ++j )
3267 const SMDS_MeshNode* n = faces[i]->GetNode(j);
3268 if ( n == srcNode ) continue;
3269 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3270 ( faces.size() > 1 || nbNodes > 3 ))
3272 gp_Pnt2d uv = helper.GetNodeUV( F, n );
3273 gp_Vec2d uvDirN( srcUV, uv );
3274 double proj = uvDirN * uvDir;
3275 proj2node.insert( make_pair( proj, n ));
3279 multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
3280 const double minProj = p2n->first;
3281 const double projThreshold = 1.1 * uvLen;
3282 if ( minProj > projThreshold )
3284 // tgtNode is located so that it does not make faces with wrong orientation
3287 edge._pos.resize(1);
3288 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
3290 // store most risky nodes in _simplices
3291 p2nEnd = proj2node.lower_bound( projThreshold );
3292 int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
3293 edge._simplices.resize( nbSimpl );
3294 for ( int i = 0; i < nbSimpl; ++i )
3296 edge._simplices[i]._nPrev = p2n->second;
3297 if ( ++p2n != p2nEnd )
3298 edge._simplices[i]._nNext = p2n->second;
3300 // set UV of source node to target node
3301 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3302 pos->SetUParameter( srcUV.X() );
3303 pos->SetVParameter( srcUV.Y() );
3305 else // _sWOL is TopAbs_EDGE
3307 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
3308 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
3309 if ( !edgeSM || edgeSM->NbElements() == 0 )
3310 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3312 const SMDS_MeshNode* n2 = 0;
3313 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3314 while ( eIt->more() && !n2 )
3316 const SMDS_MeshElement* e = eIt->next();
3317 if ( !edgeSM->Contains(e)) continue;
3318 n2 = e->GetNode( 0 );
3319 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
3322 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3324 double uSrc = helper.GetNodeU( E, srcNode, n2 );
3325 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
3326 double u2 = helper.GetNodeU( E, n2, srcNode );
3328 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
3330 // tgtNode is located so that it does not make faces with wrong orientation
3333 edge._pos.resize(1);
3334 edge._pos[0].SetCoord( U_TGT, uTgt );
3335 edge._pos[0].SetCoord( U_SRC, uSrc );
3336 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
3338 edge._simplices.resize( 1 );
3339 edge._simplices[0]._nPrev = n2;
3341 // set UV of source node to target node
3342 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3343 pos->SetUParameter( uSrc );
3347 //================================================================================
3349 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
3351 //================================================================================
3353 // Compute UV to follow during shrinking
3355 // const SMDS_MeshNode* srcNode = edge._nodes[0];
3356 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
3358 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3359 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3360 // gp_Vec2d uvDir( srcUV, tgtUV );
3361 // double uvLen = uvDir.Magnitude();
3364 // // Select shrinking step such that not to make faces with wrong orientation.
3365 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3366 // const double minStepSize = uvLen / 20;
3367 // double stepSize = uvLen;
3368 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3369 // while ( fIt->more() )
3371 // const SMDS_MeshElement* f = fIt->next();
3372 // if ( !faceSubMesh->Contains( f )) continue;
3373 // const int nbNodes = f->NbCornerNodes();
3374 // for ( int i = 0; i < nbNodes; ++i )
3376 // const SMDS_MeshNode* n = f->GetNode(i);
3377 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
3379 // gp_XY uv = helper.GetNodeUV( F, n );
3380 // gp_Vec2d uvDirN( srcUV, uv );
3381 // double proj = uvDirN * uvDir;
3382 // if ( proj < stepSize && proj > minStepSize )
3388 // const int nbSteps = ceil( uvLen / stepSize );
3389 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
3390 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
3391 // edge._pos.resize( nbSteps );
3392 // edge._pos[0] = tgtUV0;
3393 // for ( int i = 1; i < nbSteps; ++i )
3395 // double r = i / double( nbSteps );
3396 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
3401 //================================================================================
3403 * \brief Move target node to it's final position on the FACE during shrinking
3405 //================================================================================
3407 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
3408 const TopoDS_Face& F,
3409 SMESH_MesherHelper& helper )
3412 return false; // already at the target position
3414 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
3416 if ( _sWOL.ShapeType() == TopAbs_FACE )
3418 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
3419 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y());
3420 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
3421 const double uvLen = tgtUV.Distance( curUV );
3423 // Select shrinking step such that not to make faces with wrong orientation.
3424 const double kSafe = 0.8;
3425 const double minStepSize = uvLen / 10;
3426 double stepSize = uvLen;
3427 for ( unsigned i = 0; i < _simplices.size(); ++i )
3429 const SMDS_MeshNode* nn[2] = { _simplices[i]._nPrev, _simplices[i]._nNext };
3430 for ( int j = 0; j < 2; ++j )
3431 if ( const SMDS_MeshNode* n = nn[j] )
3433 gp_XY uv = helper.GetNodeUV( F, n );
3434 gp_Vec2d uvDirN( curUV, uv );
3435 double proj = uvDirN * uvDir * kSafe;
3436 if ( proj < stepSize && proj > minStepSize )
3442 if ( stepSize == uvLen )
3449 newUV = curUV + uvDir.XY() * stepSize;
3452 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3453 pos->SetUParameter( newUV.X() );
3454 pos->SetVParameter( newUV.Y() );
3457 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
3458 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
3459 dumpMove( tgtNode );
3462 else // _sWOL is TopAbs_EDGE
3464 TopoDS_Edge E = TopoDS::Edge( _sWOL );
3465 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
3467 const double u2 = helper.GetNodeU( E, n2, tgtNode );
3468 const double uSrc = _pos[0].Coord( U_SRC );
3469 const double lenTgt = _pos[0].Coord( LEN_TGT );
3471 double newU = _pos[0].Coord( U_TGT );
3472 if ( lenTgt < 0.99 * fabs( uSrc-u2 ))
3478 newU = 0.1 * uSrc + 0.9 * u2;
3480 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3481 pos->SetUParameter( newU );
3483 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
3484 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
3485 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
3486 dumpMove( tgtNode );
3492 //================================================================================
3494 * \brief Perform laplacian smooth on the FACE
3495 * \retval bool - true if the node has been moved
3497 //================================================================================
3499 bool _SmoothNode::Smooth(int& badNb,
3500 Handle(Geom_Surface)& surface,
3501 SMESH_MesherHelper& helper,
3502 const double refSign,
3505 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
3507 // compute new UV for the node
3509 for ( unsigned i = 0; i < _simplices.size(); ++i )
3510 newPos += helper.GetNodeUV( face, _simplices[i]._nPrev );
3511 newPos /= _simplices.size();
3513 // count quality metrics (orientation) of triangles around the node
3515 gp_XY tgtUV = helper.GetNodeUV( face, _node );
3516 for ( unsigned i = 0; i < _simplices.size(); ++i )
3517 nbOkBefore += _simplices[i].IsForward( tgtUV, face, helper, refSign );
3520 for ( unsigned i = 0; i < _simplices.size(); ++i )
3521 nbOkAfter += _simplices[i].IsForward( newPos, face, helper, refSign );
3523 if ( nbOkAfter < nbOkBefore )
3526 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
3527 pos->SetUParameter( newPos.X() );
3528 pos->SetVParameter( newPos.Y() );
3535 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
3536 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
3540 badNb += _simplices.size() - nbOkAfter;
3541 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
3544 //================================================================================
3546 * \brief Delete _SolidData
3548 //================================================================================
3550 _SolidData::~_SolidData()
3552 for ( unsigned i = 0; i < _edges.size(); ++i )
3554 if ( _edges[i] && _edges[i]->_2neibors )
3555 delete _edges[i]->_2neibors;
3560 //================================================================================
3562 * \brief Add a _LayerEdge inflated along the EDGE
3564 //================================================================================
3566 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
3569 if ( _nodes.empty() )
3571 _edges[0] = _edges[1] = 0;
3575 if ( e == _edges[0] || e == _edges[1] )
3577 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
3578 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
3579 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
3580 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
3583 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
3585 BRep_Tool::Range( E, f,l );
3586 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
3587 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
3591 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
3592 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
3594 if ( _nodes.empty() )
3596 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
3597 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
3599 TopLoc_Location loc;
3600 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
3601 GeomAdaptor_Curve aCurve(C);
3602 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
3604 int nbExpectNodes = eSubMesh->NbNodes() - e->_nodes.size();
3605 _initU .reserve( nbExpectNodes );
3606 _normPar.reserve( nbExpectNodes );
3607 _nodes .reserve( nbExpectNodes );
3608 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
3609 while ( nIt->more() )
3611 const SMDS_MeshNode* node = nIt->next();
3612 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
3613 node == tgtNode0 || node == tgtNode1 )
3614 continue; // refinement nodes
3615 _nodes.push_back( node );
3616 _initU.push_back( helper.GetNodeU( E, node ));
3617 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
3618 _normPar.push_back( len / totLen );
3623 // remove target node of the _LayerEdge from _nodes
3625 for ( unsigned i = 0; i < _nodes.size(); ++i )
3626 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
3627 _nodes[i] = 0, nbFound++;
3628 if ( nbFound == _nodes.size() )
3633 //================================================================================
3635 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
3637 //================================================================================
3639 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
3641 if ( _done || _nodes.empty())
3643 const _LayerEdge* e = _edges[0];
3644 if ( !e ) e = _edges[1];
3647 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
3648 ( !_edges[1] || _edges[1]->_pos.empty() ));
3650 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
3652 if ( set3D || _done )
3654 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
3655 GeomAdaptor_Curve aCurve(C);
3658 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
3660 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
3661 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
3663 for ( unsigned i = 0; i < _nodes.size(); ++i )
3665 if ( !_nodes[i] ) continue;
3666 double len = totLen * _normPar[i];
3667 GCPnts_AbscissaPoint discret( aCurve, len, f );
3668 if ( !discret.IsDone() )
3669 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
3670 double u = discret.Parameter();
3671 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
3672 pos->SetUParameter( u );
3673 gp_Pnt p = C->Value( u );
3674 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
3679 BRep_Tool::Range( E, f,l );
3681 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
3683 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
3685 for ( unsigned i = 0; i < _nodes.size(); ++i )
3687 if ( !_nodes[i] ) continue;
3688 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
3689 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
3690 pos->SetUParameter( u );
3695 //================================================================================
3697 * \brief Restore initial parameters of nodes on EDGE
3699 //================================================================================
3701 void _Shrinker1D::RestoreParams()
3704 for ( unsigned i = 0; i < _nodes.size(); ++i )
3706 if ( !_nodes[i] ) continue;
3707 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
3708 pos->SetUParameter( _initU[i] );
3712 //================================================================================
3714 * \brief Replace source nodes by target nodes in shrinked mesh edges
3716 //================================================================================
3718 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
3720 const SMDS_MeshNode* nodes[3];
3721 for ( int i = 0; i < 2; ++i )
3723 if ( !_edges[i] ) continue;
3725 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
3726 if ( !eSubMesh ) return;
3727 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
3728 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
3729 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3730 while ( eIt->more() )
3732 const SMDS_MeshElement* e = eIt->next();
3733 if ( !eSubMesh->Contains( e ))
3735 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
3736 for ( int iN = 0; iN < e->NbNodes(); ++iN )
3738 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3739 nodes[iN] = ( n == srcNode ? tgtNode : n );
3741 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
3746 //================================================================================
3748 * \brief Creates 2D and 1D elements on boundaries of new prisms
3750 //================================================================================
3752 bool _ViscousBuilder::addBoundaryElements()
3754 SMESH_MesherHelper helper( *_mesh );
3756 for ( unsigned i = 0; i < _sdVec.size(); ++i )
3758 _SolidData& data = _sdVec[i];
3759 TopTools_IndexedMapOfShape geomEdges;
3760 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
3761 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
3763 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
3765 // Get _LayerEdge's based on E
3767 map< double, const SMDS_MeshNode* > u2nodes;
3768 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
3771 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
3772 TNode2Edge & n2eMap = data._n2eMap;
3773 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
3775 //check if 2D elements are needed on E
3776 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
3777 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
3778 ledges.push_back( n2e->second );
3780 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
3781 continue; // no layers on E
3782 ledges.push_back( n2eMap[ u2n->second ]);
3784 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
3785 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
3786 int nbSharedPyram = 0;
3787 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
3788 while ( vIt->more() )
3790 const SMDS_MeshElement* v = vIt->next();
3791 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
3793 if ( nbSharedPyram > 1 )
3794 continue; // not free border of the pyramid
3796 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
3797 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
3798 continue; // faces already created
3800 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
3801 ledges.push_back( n2eMap[ u2n->second ]);
3803 // Find out orientation and type of face to create
3805 bool reverse = false, tria = false, isOnFace;
3807 map< TGeomID, TopoDS_Shape >::iterator e2f =
3808 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
3810 if ( isOnFace = ( e2f != data._shrinkShape2Shape.end() ))
3812 F = e2f->second.Oriented( TopAbs_FORWARD );
3813 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
3814 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
3819 // find FACE with layers sharing E
3820 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
3821 while ( fIt->more() && F.IsNull() )
3823 const TopoDS_Shape* pF = fIt->next();
3824 if ( helper.IsSubShape( *pF, data._solid) &&
3825 !_ignoreShapeIds.count( e2f->first ))
3831 // Find the sub-mesh to add new faces
3832 SMESHDS_SubMesh* sm = 0;
3834 sm = getMeshDS()->MeshElements( F );
3836 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
3838 return error("error in addBoundaryElements()", data._index);
3841 const int dj1 = reverse ? 0 : 1;
3842 const int dj2 = reverse ? 1 : 0;
3843 vector<SMDS_MeshElement*> newFaces;
3844 newFaces.reserve(( ledges.size() - 1 ) * (ledges[0]->_nodes.size() - 1 ));
3845 for ( unsigned j = 1; j < ledges.size(); ++j )
3847 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
3848 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
3850 for ( unsigned z = 1; z < nn1.size(); ++z )
3851 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
3853 for ( unsigned z = 1; z < nn1.size(); ++z )
3854 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));