1 // Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_ViscousLayers.cxx
21 // Created : Wed Dec 1 15:15:34 2010
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers.hxx"
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_ControlsDef.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_Mesh.hxx"
39 #include "SMESH_MesherHelper.hxx"
40 #include "SMESH_ProxyMesh.hxx"
41 #include "SMESH_subMesh.hxx"
42 #include "SMESH_subMeshEventListener.hxx"
44 #include "utilities.h"
46 #include <BRepAdaptor_Curve2d.hxx>
47 #include <BRep_Tool.hxx>
48 #include <Bnd_B2d.hxx>
49 #include <Bnd_B3d.hxx>
51 #include <GCPnts_AbscissaPoint.hxx>
52 #include <Geom2d_Circle.hxx>
53 #include <Geom2d_Line.hxx>
54 #include <Geom2d_TrimmedCurve.hxx>
55 #include <GeomAdaptor_Curve.hxx>
56 #include <Geom_Circle.hxx>
57 #include <Geom_Curve.hxx>
58 #include <Geom_Line.hxx>
59 #include <Geom_TrimmedCurve.hxx>
60 #include <Precision.hxx>
61 #include <Standard_ErrorHandler.hxx>
62 #include <TColStd_Array1OfReal.hxx>
64 #include <TopExp_Explorer.hxx>
65 #include <TopTools_IndexedMapOfShape.hxx>
66 #include <TopTools_MapOfShape.hxx>
68 #include <TopoDS_Edge.hxx>
69 #include <TopoDS_Face.hxx>
70 #include <TopoDS_Vertex.hxx>
84 //================================================================================
89 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
92 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
93 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
95 struct _MeshOfSolid : public SMESH_ProxyMesh,
96 public SMESH_subMeshEventListenerData
100 _MeshOfSolid( SMESH_Mesh* mesh)
101 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
103 SMESH_ProxyMesh::setMesh( *mesh );
106 // returns submesh for a geom face
107 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
109 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
110 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
112 void setNode2Node(const SMDS_MeshNode* srcNode,
113 const SMDS_MeshNode* proxyNode,
114 const SMESH_ProxyMesh::SubMesh* subMesh)
116 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
119 //--------------------------------------------------------------------------------
121 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
122 * It is used to clear an inferior dim sub-meshes modified by viscous layers
124 class _SrinkShapeListener : SMESH_subMeshEventListener
126 _SrinkShapeListener()
127 : SMESH_subMeshEventListener(/*isDeletable=*/false,
128 "StdMeshers_ViscousLayers::_SrinkShapeListener") {}
129 static SMESH_subMeshEventListener* Get() { static _SrinkShapeListener l; return &l; }
131 virtual void ProcessEvent(const int event,
133 SMESH_subMesh* solidSM,
134 SMESH_subMeshEventListenerData* data,
135 const SMESH_Hypothesis* hyp)
137 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
139 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
142 static void ToClearSubMeshWithSolid( SMESH_subMesh* sm,
143 const TopoDS_Shape& solid)
145 SMESH_subMesh* solidSM = sm->GetFather()->GetSubMesh( solid );
146 SMESH_subMeshEventListenerData* data = solidSM->GetEventListenerData( Get());
149 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sm ) ==
150 data->mySubMeshes.end())
151 data->mySubMeshes.push_back( sm );
155 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sm );
156 sm->SetEventListener( Get(), data, /*whereToListenTo=*/solidSM );
160 //--------------------------------------------------------------------------------
162 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
163 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
164 * delete the data as soon as it has been used
166 class _ViscousListener : SMESH_subMeshEventListener
169 SMESH_subMeshEventListener(/*isDeletable=*/false,
170 "StdMeshers_ViscousLayers::_ViscousListener") {}
171 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
173 virtual void ProcessEvent(const int event,
175 SMESH_subMesh* subMesh,
176 SMESH_subMeshEventListenerData* data,
177 const SMESH_Hypothesis* hyp)
179 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
181 // delete SMESH_ProxyMesh containing temporary faces
182 subMesh->DeleteEventListener( this );
185 // Finds or creates proxy mesh of the solid
186 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
187 const TopoDS_Shape& solid,
190 if ( !mesh ) return 0;
191 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
192 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
193 if ( !data && toCreate )
195 data = new _MeshOfSolid(mesh);
196 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
197 sm->SetEventListener( Get(), data, sm );
201 // Removes proxy mesh of the solid
202 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
204 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
208 //--------------------------------------------------------------------------------
210 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
211 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
212 * The class is used to check validity of face or volumes around a smoothed node;
213 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
217 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
218 _Simplex(const SMDS_MeshNode* nPrev=0, const SMDS_MeshNode* nNext=0)
219 : _nPrev(nPrev), _nNext(nNext) {}
220 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
222 const double M[3][3] =
223 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
224 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
225 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
226 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
227 + M[0][1]*M[1][2]*M[2][0]
228 + M[0][2]*M[1][0]*M[2][1]
229 - M[0][0]*M[1][2]*M[2][1]
230 - M[0][1]*M[1][0]*M[2][2]
231 - M[0][2]*M[1][1]*M[2][0]);
232 return determinant > 1e-100;
234 bool IsForward(const gp_XY& tgtUV,
235 const SMDS_MeshNode* smoothedNode,
236 const TopoDS_Face& face,
237 SMESH_MesherHelper& helper,
238 const double refSign) const
240 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
241 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
242 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
244 return d*refSign > 1e-100;
246 bool IsNeighbour(const _Simplex& other) const
248 return _nPrev == other._nNext || _nNext == other._nPrev;
251 //--------------------------------------------------------------------------------
253 * Structure used to take into account surface curvature while smoothing
258 double _k; // factor to correct node smoothed position
260 static _Curvature* New( double avgNormProj, double avgDist )
263 if ( fabs( avgNormProj / avgDist ) > 1./200 )
266 c->_r = avgDist * avgDist / avgNormProj;
267 c->_k = avgDist * avgDist / c->_r / c->_r;
268 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
272 double lenDelta(double len) const { return _k * ( _r + len ); }
275 //--------------------------------------------------------------------------------
277 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
281 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
282 const SMDS_MeshNode* _nodes[2];
283 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
285 double _wgt[2]; // weights of _nodes
286 _LayerEdge* _edges[2];
288 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
291 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
293 std::swap( _nodes[0], _nodes[1] );
294 std::swap( _wgt[0], _wgt[1] );
297 //--------------------------------------------------------------------------------
299 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
300 * and a node of the most internal layer (_nodes.back())
304 vector< const SMDS_MeshNode*> _nodes;
306 gp_XYZ _normal; // to solid surface
307 vector<gp_XYZ> _pos; // points computed during inflation
308 double _len; // length achived with the last step
309 double _cosin; // of angle (_normal ^ surface)
310 double _lenFactor; // to compute _len taking _cosin into account
312 // face or edge w/o layer along or near which _LayerEdge is inflated
314 // simplices connected to the source node (_nodes[0]);
315 // used for smoothing and quality check of _LayerEdge's based on the FACE
316 vector<_Simplex> _simplices;
317 // data for smoothing of _LayerEdge's based on the EDGE
318 _2NearEdges* _2neibors;
320 _Curvature* _curvature;
321 // TODO:: detele _Curvature, _plnNorm
323 void SetNewLength( double len, SMESH_MesherHelper& helper );
324 bool SetNewLength2d( Handle(Geom_Surface)& surface,
325 const TopoDS_Face& F,
326 SMESH_MesherHelper& helper );
327 void SetDataByNeighbors( const SMDS_MeshNode* n1,
328 const SMDS_MeshNode* n2,
329 SMESH_MesherHelper& helper);
330 void InvalidateStep( int curStep );
331 bool Smooth(int& badNb);
332 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
333 const TopoDS_Face& F,
334 SMESH_MesherHelper& helper);
335 bool FindIntersection( SMESH_ElementSearcher& searcher,
337 const double& epsilon,
338 const SMDS_MeshElement** face = 0);
339 bool SegTriaInter( const gp_Ax1& lastSegment,
340 const SMDS_MeshNode* n0,
341 const SMDS_MeshNode* n1,
342 const SMDS_MeshNode* n2,
344 const double& epsilon) const;
345 gp_Ax1 LastSegment(double& segLen) const;
346 bool IsOnEdge() const { return _2neibors; }
347 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
348 void SetCosin( double cosin );
352 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
354 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
355 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
358 //--------------------------------------------------------------------------------
360 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
362 //--------------------------------------------------------------------------------
364 * \brief Data of a SOLID
369 const StdMeshers_ViscousLayers* _hyp;
370 _MeshOfSolid* _proxyMesh;
371 set<TGeomID> _reversedFaceIds;
373 double _stepSize, _stepSizeCoeff;
374 const SMDS_MeshNode* _stepSizeNodes[2];
377 // edges of _n2eMap. We keep same data in two containers because
378 // iteration over the map is 5 time longer than over the vector
379 vector< _LayerEdge* > _edges;
381 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
382 // layers and a FACE w/o layers
383 // value: the shape (FACE or EDGE) to shrink mesh on.
384 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
385 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
387 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
388 set< TGeomID > _noShrinkFaces;
390 // <EDGE to smooth on> to <it's curve>
391 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
393 // end indices in _edges of _LayerEdge on one shape to smooth
394 vector< int > _endEdgeToSmooth;
396 double _epsilon; // precision for SegTriaInter()
398 int _index; // for debug
400 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
401 const StdMeshers_ViscousLayers* h=0,
402 _MeshOfSolid* m=0) :_solid(s), _hyp(h), _proxyMesh(m) {}
405 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
408 Handle(Geom_Surface)& surface,
409 const TopoDS_Face& F,
410 SMESH_MesherHelper& helper);
412 //--------------------------------------------------------------------------------
414 * \brief Data of node on a shrinked FACE
418 const SMDS_MeshNode* _node;
419 //vector<const SMDS_MeshNode*> _nodesAround;
420 vector<_Simplex> _simplices; // for quality check
422 bool Smooth(int& badNb,
423 Handle(Geom_Surface)& surface,
424 SMESH_MesherHelper& helper,
425 const double refSign,
429 //--------------------------------------------------------------------------------
431 * \brief Builder of viscous layers
433 class _ViscousBuilder
438 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
439 const TopoDS_Shape& shape);
441 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
442 void RestoreListeners();
444 // computes SMESH_ProxyMesh::SubMesh::_n2n;
445 bool MakeN2NMap( _MeshOfSolid* pm );
449 bool findSolidsWithLayers();
450 bool findFacesWithLayers();
451 bool makeLayer(_SolidData& data);
452 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
453 SMESH_MesherHelper& helper, _SolidData& data);
454 bool findNeiborsOnEdge(const _LayerEdge* edge,
455 const SMDS_MeshNode*& n1,
456 const SMDS_MeshNode*& n2,
458 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
459 const set<TGeomID>& ingnoreShapes,
460 const _SolidData* dataToCheckOri = 0,
461 const bool toSort = false);
462 bool sortEdges( _SolidData& data,
463 vector< vector<_LayerEdge*> >& edgesByGeom);
464 void limitStepSize( _SolidData& data,
465 const SMDS_MeshElement* face,
467 void limitStepSize( _SolidData& data, const double minSize);
468 bool inflate(_SolidData& data);
469 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
470 bool smoothAnalyticEdge( _SolidData& data,
473 Handle(Geom_Surface)& surface,
474 const TopoDS_Face& F,
475 SMESH_MesherHelper& helper);
476 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
477 bool refine(_SolidData& data);
479 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
480 SMESH_MesherHelper& helper,
481 const SMESHDS_SubMesh* faceSubMesh );
482 void fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper);
483 bool addBoundaryElements();
485 bool error( const string& text, int solidID=-1 );
486 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
489 void makeGroupOfLE();
492 SMESH_ComputeErrorPtr _error;
494 vector< _SolidData > _sdVec;
495 set<TGeomID> _ignoreShapeIds;
498 //--------------------------------------------------------------------------------
500 * \brief Shrinker of nodes on the EDGE
504 vector<double> _initU;
505 vector<double> _normPar;
506 vector<const SMDS_MeshNode*> _nodes;
507 const _LayerEdge* _edges[2];
510 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
511 void Compute(bool set3D, SMESH_MesherHelper& helper);
512 void RestoreParams();
513 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
515 //--------------------------------------------------------------------------------
517 * \brief Class of temporary mesh face.
518 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
519 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
521 struct TmpMeshFace : public SMDS_MeshElement
523 vector<const SMDS_MeshNode* > _nn;
524 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
525 SMDS_MeshElement(id), _nn(nodes) {}
526 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
527 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
528 virtual vtkIdType GetVtkType() const { return -1; }
529 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
530 virtual SMDSAbs_GeometryType GetGeomType() const { return SMDSGeom_TRIANGLE; }
531 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const
532 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
534 //--------------------------------------------------------------------------------
536 * \brief Class of temporary mesh face storing _LayerEdge it's based on
538 struct TmpMeshFaceOnEdge : public TmpMeshFace
540 _LayerEdge *_le1, *_le2;
541 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
542 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
544 _nn[0]=_le1->_nodes[0];
545 _nn[1]=_le1->_nodes.back();
546 _nn[2]=_le2->_nodes.back();
547 _nn[3]=_le2->_nodes[0];
550 } // namespace VISCOUS
552 //================================================================================
553 // StdMeshers_ViscousLayers hypothesis
555 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
556 :SMESH_Hypothesis(hypId, studyId, gen),
557 _nbLayers(1), _thickness(1), _stretchFactor(1)
559 _name = StdMeshers_ViscousLayers::GetHypType();
560 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
561 } // --------------------------------------------------------------------------------
562 void StdMeshers_ViscousLayers::SetIgnoreFaces(const std::vector<int>& faceIds)
564 if ( faceIds != _ignoreFaceIds )
565 _ignoreFaceIds = faceIds, NotifySubMeshesHypothesisModification();
566 } // --------------------------------------------------------------------------------
567 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
569 if ( thickness != _thickness )
570 _thickness = thickness, NotifySubMeshesHypothesisModification();
571 } // --------------------------------------------------------------------------------
572 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
574 if ( _nbLayers != nb )
575 _nbLayers = nb, NotifySubMeshesHypothesisModification();
576 } // --------------------------------------------------------------------------------
577 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
579 if ( _stretchFactor != factor )
580 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
581 } // --------------------------------------------------------------------------------
583 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
584 const TopoDS_Shape& theShape,
585 const bool toMakeN2NMap) const
587 using namespace VISCOUS;
588 _ViscousBuilder bulder;
589 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
590 if ( err && !err->IsOK() )
591 return SMESH_ProxyMesh::Ptr();
593 vector<SMESH_ProxyMesh::Ptr> components;
594 TopExp_Explorer exp( theShape, TopAbs_SOLID );
595 for ( ; exp.More(); exp.Next() )
597 if ( _MeshOfSolid* pm =
598 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
600 if ( toMakeN2NMap && !pm->_n2nMapComputed )
601 if ( !bulder.MakeN2NMap( pm ))
602 return SMESH_ProxyMesh::Ptr();
603 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
604 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
606 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
608 switch ( components.size() )
612 case 1: return components[0];
614 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
616 return SMESH_ProxyMesh::Ptr();
617 } // --------------------------------------------------------------------------------
618 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
620 save << " " << _nbLayers
622 << " " << _stretchFactor
623 << " " << _ignoreFaceIds.size();
624 for ( unsigned i = 0; i < _ignoreFaceIds.size(); ++i )
625 save << " " << _ignoreFaceIds[i];
627 } // --------------------------------------------------------------------------------
628 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
631 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
632 while ( _ignoreFaceIds.size() < nbFaces && load >> faceID )
633 _ignoreFaceIds.push_back( faceID );
635 } // --------------------------------------------------------------------------------
636 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
637 const TopoDS_Shape& theShape)
642 // END StdMeshers_ViscousLayers hypothesis
643 //================================================================================
647 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
651 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
652 gp_Pnt p = BRep_Tool::Pnt( fromV );
653 double distF = p.SquareDistance( c->Value( f ));
654 double distL = p.SquareDistance( c->Value( l ));
655 c->D1(( distF < distL ? f : l), p, dir );
656 if ( distL < distF ) dir.Reverse();
659 //--------------------------------------------------------------------------------
660 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
661 SMESH_MesherHelper& helper)
664 double f,l; gp_Pnt p;
665 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
666 double u = helper.GetNodeU( E, atNode );
670 //--------------------------------------------------------------------------------
671 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
672 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
674 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
675 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
676 gp_Pnt p; gp_Vec du, dv, norm;
677 surface->D1( uv.X(),uv.Y(), p, du,dv );
681 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
682 double u = helper.GetNodeU( fromE, node, 0, &ok );
684 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
685 if ( o == TopAbs_REVERSED )
688 gp_Vec dir = norm ^ du;
690 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
691 helper.IsClosedEdge( fromE ))
693 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
694 else c->D1( f, p, dv );
695 if ( o == TopAbs_REVERSED )
697 gp_Vec dir2 = norm ^ dv;
698 dir = dir.Normalized() + dir2.Normalized();
702 //--------------------------------------------------------------------------------
703 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
704 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
705 bool& ok, double* cosin=0)
707 double f,l; TopLoc_Location loc;
708 vector< TopoDS_Edge > edges; // sharing a vertex
709 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
712 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
713 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
714 edges.push_back( *e );
717 if ( !( ok = ( edges.size() > 0 ))) return dir;
718 // get average dir of edges going fromV
720 for ( unsigned i = 0; i < edges.size(); ++i )
722 edgeDir = getEdgeDir( edges[i], fromV );
723 double size2 = edgeDir.SquareMagnitude();
724 if ( size2 > numeric_limits<double>::min() )
725 edgeDir /= sqrt( size2 );
728 dir += edgeDir.XYZ();
730 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
731 if ( edges.size() == 1 || dir.SquareModulus() < 1e-10)
733 else if ( dir * fromEdgeDir < 0 )
737 //dir /= edges.size();
739 double angle = edgeDir.Angle( dir );
740 *cosin = cos( angle );
745 //================================================================================
747 * \brief Returns true if a FACE is bound by a concave EDGE
749 //================================================================================
751 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
755 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
756 for ( ; eExp.More(); eExp.Next() )
758 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
759 if ( BRep_Tool::Degenerated( E )) continue;
760 // check if 2D curve is concave
761 BRepAdaptor_Curve2d curve( E, F );
762 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
763 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
764 curve.Intervals( intervals, GeomAbs_C2 );
765 bool isConvex = true;
766 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
768 double u1 = intervals( i );
769 double u2 = intervals( i+1 );
770 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
771 double cross = drv2 ^ drv1;
772 if ( E.Orientation() == TopAbs_REVERSED )
774 isConvex = ( cross < 1e-9 );
776 // check if concavity is strong enough to care about it
777 //const double maxAngle = 5 * Standard_PI180;
780 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
782 // map< double, const SMDS_MeshNode* > u2nodes;
783 // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
784 // /*ignoreMedium=*/true, u2nodes))
786 // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
787 // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
788 // double uPrev = u2n->first;
789 // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
791 // gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
792 // gp_Vec2d segmentDir( uvPrev, uv );
793 // curve.D1( uPrev, p, drv1 );
795 // if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
800 // uPrev = u2n->first;
806 //--------------------------------------------------------------------------------
807 // DEBUG. Dump intermediate node positions into a python script
812 const char* fname = "/tmp/viscous.py";
813 cout << "execfile('"<<fname<<"')"<<endl;
814 py = new ofstream(fname);
815 *py << "from smesh import *" << endl
816 << "meshSO = GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
817 << "mesh = Mesh( meshSO.GetObject() )"<<endl;
821 *py << "mesh.MakeGroup('Viscous Prisms',VOLUME,FT_ElemGeomType,'=',Geom_PENTA)"<<endl;
824 ~PyDump() { Finish(); }
826 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
827 #define dumpMove(n) { _dumpMove(n, __LINE__);}
828 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
829 void _dumpFunction(const string& fun, int ln)
830 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
831 void _dumpMove(const SMDS_MeshNode* n, int ln)
832 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
833 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
834 void _dumpCmd(const string& txt, int ln)
835 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
836 void dumpFunctionEnd()
837 { if (py) *py<< " return"<< endl; }
838 void dumpChangeNodes( const SMDS_MeshElement* f )
839 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
840 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
841 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
843 struct PyDump { void Finish() {} };
844 #define dumpFunction(f) f
847 #define dumpFunctionEnd()
848 #define dumpChangeNodes(f)
852 using namespace VISCOUS;
854 //================================================================================
856 * \brief Constructor of _ViscousBuilder
858 //================================================================================
860 _ViscousBuilder::_ViscousBuilder()
862 _error = SMESH_ComputeError::New(COMPERR_OK);
866 //================================================================================
868 * \brief Stores error description and returns false
870 //================================================================================
872 bool _ViscousBuilder::error(const string& text, int solidId )
874 _error->myName = COMPERR_ALGO_FAILED;
875 _error->myComment = string("Viscous layers builder: ") + text;
878 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
879 if ( !sm && !_sdVec.empty() )
880 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
881 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
883 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
884 if ( smError && smError->myAlgo )
885 _error->myAlgo = smError->myAlgo;
889 makeGroupOfLE(); // debug
894 //================================================================================
896 * \brief At study restoration, restore event listeners used to clear an inferior
897 * dim sub-mesh modified by viscous layers
899 //================================================================================
901 void _ViscousBuilder::RestoreListeners()
906 //================================================================================
908 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
910 //================================================================================
912 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
914 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
915 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
916 for ( ; fExp.More(); fExp.Next() )
918 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
919 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
921 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
923 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
926 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
927 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
929 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
930 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
931 while( prxIt->more() )
933 const SMDS_MeshElement* fSrc = srcIt->next();
934 const SMDS_MeshElement* fPrx = prxIt->next();
935 if ( fSrc->NbNodes() != fPrx->NbNodes())
936 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
937 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
938 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
941 pm->_n2nMapComputed = true;
945 //================================================================================
947 * \brief Does its job
949 //================================================================================
951 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
952 const TopoDS_Shape& theShape)
954 // TODO: set priority of solids during Gen::Compute()
958 // check if proxy mesh already computed
959 TopExp_Explorer exp( theShape, TopAbs_SOLID );
961 return error("No SOLID's in theShape"), _error;
963 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
964 return SMESH_ComputeErrorPtr(); // everything already computed
968 // TODO: ignore already computed SOLIDs
969 if ( !findSolidsWithLayers())
972 if ( !findFacesWithLayers() )
975 for ( unsigned i = 0; i < _sdVec.size(); ++i )
977 if ( ! makeLayer(_sdVec[i]) )
980 if ( _sdVec[i]._edges.size() == 0 )
983 if ( ! inflate(_sdVec[i]) )
986 if ( ! refine(_sdVec[i]) )
992 addBoundaryElements();
994 makeGroupOfLE(); // debug
1000 //================================================================================
1002 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1004 //================================================================================
1006 bool _ViscousBuilder::findSolidsWithLayers()
1009 TopTools_IndexedMapOfShape allSolids;
1010 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1011 _sdVec.reserve( allSolids.Extent());
1013 SMESH_Gen* gen = _mesh->GetGen();
1014 for ( int i = 1; i <= allSolids.Extent(); ++i )
1016 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1017 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1018 if ( !algo ) continue;
1019 // TODO: check if algo is hidden
1020 const list <const SMESHDS_Hypothesis *> & allHyps =
1021 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1022 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1023 const StdMeshers_ViscousLayers* viscHyp = 0;
1024 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1025 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1028 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1031 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, proxyMesh ));
1032 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1035 if ( _sdVec.empty() )
1037 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1042 //================================================================================
1046 //================================================================================
1048 bool _ViscousBuilder::findFacesWithLayers()
1050 // collect all faces to ignore defined by hyp
1051 vector<TopoDS_Shape> ignoreFaces;
1052 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1054 vector<TGeomID> ids = _sdVec[i]._hyp->GetIgnoreFaces();
1055 for ( unsigned i = 0; i < ids.size(); ++i )
1057 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
1058 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1060 _ignoreShapeIds.insert( ids[i] );
1061 ignoreFaces.push_back( s );
1066 // ignore internal faces
1067 SMESH_MesherHelper helper( *_mesh );
1068 TopExp_Explorer exp;
1069 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1071 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1072 for ( ; exp.More(); exp.Next() )
1074 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1075 if ( helper.NbAncestors( exp.Current(), *_mesh, TopAbs_SOLID ) > 1 )
1077 _ignoreShapeIds.insert( faceInd );
1078 ignoreFaces.push_back( exp.Current() );
1079 if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face( exp.Current() ), getMeshDS()))
1080 _sdVec[i]._reversedFaceIds.insert( faceInd );
1085 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1086 TopTools_IndexedMapOfShape shapes;
1087 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1090 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1091 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1093 const TopoDS_Shape& edge = shapes(iE);
1094 // find 2 faces sharing an edge
1096 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1097 while ( fIt->more())
1099 const TopoDS_Shape* f = fIt->next();
1100 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1101 FF[ int( !FF[0].IsNull()) ] = *f;
1103 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1104 // check presence of layers on them
1106 for ( int j = 0; j < 2; ++j )
1107 ignore[j] = _ignoreShapeIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1108 if ( ignore[0] == ignore[1] ) continue; // nothing interesting
1109 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1111 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1112 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1115 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1116 // the algo of the SOLID sharing the FACE does not support it
1117 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1118 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1120 TopTools_MapOfShape noShrinkVertices;
1121 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1122 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1124 const TopoDS_Shape& fWOL = e2f->second;
1125 TGeomID edgeID = e2f->first;
1126 bool notShrinkFace = false;
1127 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1128 while ( soIt->more())
1130 const TopoDS_Shape* solid = soIt->next();
1131 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1132 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1133 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1134 notShrinkFace = true;
1135 for ( unsigned j = 0; j < _sdVec.size(); ++j )
1137 if ( _sdVec[j]._solid.IsSame( *solid ) )
1138 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1139 notShrinkFace = false;
1142 if ( notShrinkFace )
1144 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1145 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1146 noShrinkVertices.Add( vExp.Current() );
1149 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1150 // to the found not shrinked fWOL's
1151 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1152 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1154 TGeomID edgeID = e2f->first;
1155 TopoDS_Vertex VV[2];
1156 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1157 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1159 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1160 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1169 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1171 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1174 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1175 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1177 const TopoDS_Shape& vertex = shapes(iV);
1178 // find faces WOL sharing the vertex
1179 vector< TopoDS_Shape > facesWOL;
1180 int totalNbFaces = 0;
1181 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1182 while ( fIt->more())
1184 const TopoDS_Shape* f = fIt->next();
1185 const int fID = getMeshDS()->ShapeToIndex( *f );
1186 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1189 if ( _ignoreShapeIds.count ( fID ) && ! _sdVec[i]._noShrinkFaces.count( fID ))
1190 facesWOL.push_back( *f );
1193 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1194 continue; // no layers at this vertex or no WOL
1195 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1196 switch ( facesWOL.size() )
1200 helper.SetSubShape( facesWOL[0] );
1201 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1203 TopoDS_Shape seamEdge;
1204 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1205 while ( eIt->more() && seamEdge.IsNull() )
1207 const TopoDS_Shape* e = eIt->next();
1208 if ( helper.IsRealSeam( *e ) )
1211 if ( !seamEdge.IsNull() )
1213 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1217 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1222 // find an edge shared by 2 faces
1223 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1224 while ( eIt->more())
1226 const TopoDS_Shape* e = eIt->next();
1227 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1228 helper.IsSubShape( *e, facesWOL[1]))
1230 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1236 return error("Not yet supported case", _sdVec[i]._index);
1244 //================================================================================
1246 * \brief Create the inner surface of the viscous layer and prepare data for infation
1248 //================================================================================
1250 bool _ViscousBuilder::makeLayer(_SolidData& data)
1252 // get all sub-shapes to make layers on
1253 set<TGeomID> subIds, faceIds;
1254 subIds = data._noShrinkFaces;
1255 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1256 for ( ; exp.More(); exp.Next() )
1257 if ( ! _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1259 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1260 faceIds.insert( fSubM->GetId() );
1261 SMESH_subMeshIteratorPtr subIt =
1262 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1263 while ( subIt->more() )
1264 subIds.insert( subIt->next()->GetId() );
1267 // make a map to find new nodes on sub-shapes shared with other SOLID
1268 map< TGeomID, TNode2Edge* > s2neMap;
1269 map< TGeomID, TNode2Edge* >::iterator s2ne;
1270 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1271 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1273 TGeomID shapeInd = s2s->first;
1274 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1276 if ( _sdVec[i]._index == data._index ) continue;
1277 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1278 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1279 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1281 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1287 // Create temporary faces and _LayerEdge's
1289 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1291 data._stepSize = Precision::Infinite();
1292 data._stepSizeNodes[0] = 0;
1294 SMESH_MesherHelper helper( *_mesh );
1295 helper.SetSubShape( data._solid );
1296 helper.SetElementsOnShape(true);
1298 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1299 TNode2Edge::iterator n2e2;
1301 // collect _LayerEdge's of shapes they are based on
1302 const int nbShapes = getMeshDS()->MaxShapeIndex();
1303 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1305 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1307 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1308 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1310 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1311 SMESH_ProxyMesh::SubMesh* proxySub =
1312 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1314 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1315 while ( eIt->more() )
1317 const SMDS_MeshElement* face = eIt->next();
1318 newNodes.resize( face->NbCornerNodes() );
1319 double faceMaxCosin = -1;
1320 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1322 const SMDS_MeshNode* n = face->GetNode(i);
1323 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1324 if ( !(*n2e).second )
1327 _LayerEdge* edge = new _LayerEdge();
1329 edge->_nodes.push_back( n );
1330 const int shapeID = n->getshapeId();
1331 edgesByGeom[ shapeID ].push_back( edge );
1333 // set edge data or find already refined _LayerEdge and get data from it
1334 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1335 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1336 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1338 _LayerEdge* foundEdge = (*n2e2).second;
1339 edge->Copy( *foundEdge, helper );
1340 // location of the last node is modified but we can restore
1341 // it by node position on _sWOL stored by the node
1342 const_cast< SMDS_MeshNode* >
1343 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1347 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1348 if ( !setEdgeData( *edge, subIds, helper, data ))
1351 dumpMove(edge->_nodes.back());
1352 if ( edge->_cosin > 0.01 )
1354 if ( edge->_cosin > faceMaxCosin )
1355 faceMaxCosin = edge->_cosin;
1358 newNodes[ i ] = n2e->second->_nodes.back();
1360 // create a temporary face
1361 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1362 proxySub->AddElement( newFace );
1364 // compute inflation step size by min size of element on a convex surface
1365 if ( faceMaxCosin > 0.1 )
1366 limitStepSize( data, face, faceMaxCosin );
1367 } // loop on 2D elements on a FACE
1368 } // loop on FACEs of a SOLID
1370 data._epsilon = 1e-7;
1371 if ( data._stepSize < 1. )
1372 data._epsilon *= data._stepSize;
1374 // Put _LayerEdge's into a vector
1376 if ( !sortEdges( data, edgesByGeom ))
1379 // Set target nodes into _Simplex and _2NearEdges
1380 TNode2Edge::iterator n2e;
1381 for ( unsigned i = 0; i < data._edges.size(); ++i )
1383 if ( data._edges[i]->IsOnEdge())
1384 for ( int j = 0; j < 2; ++j )
1386 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1387 break; // _LayerEdge is shared by two _SolidData's
1388 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1389 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1390 return error("_LayerEdge not found by src node", data._index);
1391 n = (*n2e).second->_nodes.back();
1392 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1395 for ( unsigned j = 0; j < data._edges[i]->_simplices.size(); ++j )
1397 _Simplex& s = data._edges[i]->_simplices[j];
1398 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1399 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1407 //================================================================================
1409 * \brief Compute inflation step size by min size of element on a convex surface
1411 //================================================================================
1413 void _ViscousBuilder::limitStepSize( _SolidData& data,
1414 const SMDS_MeshElement* face,
1418 double minSize = 10 * data._stepSize;
1419 const int nbNodes = face->NbCornerNodes();
1420 for ( int i = 0; i < nbNodes; ++i )
1422 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1423 const SMDS_MeshNode* curN = face->GetNode( i );
1424 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1425 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1427 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1428 if ( dist < minSize )
1429 minSize = dist, iN = i;
1432 double newStep = 0.8 * minSize / cosin;
1433 if ( newStep < data._stepSize )
1435 data._stepSize = newStep;
1436 data._stepSizeCoeff = 0.8 / cosin;
1437 data._stepSizeNodes[0] = face->GetNode( iN );
1438 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1442 //================================================================================
1444 * \brief Compute inflation step size by min size of element on a convex surface
1446 //================================================================================
1448 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1450 if ( minSize < data._stepSize )
1452 data._stepSize = minSize;
1453 if ( data._stepSizeNodes[0] )
1456 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1457 data._stepSizeCoeff = data._stepSize / dist;
1462 //================================================================================
1464 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1466 //================================================================================
1468 bool _ViscousBuilder::sortEdges( _SolidData& data,
1469 vector< vector<_LayerEdge*> >& edgesByGeom)
1471 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1472 // boundry inclined at a sharp angle to the shape
1474 list< TGeomID > shapesToSmooth;
1476 SMESH_MesherHelper helper( *_mesh );
1479 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1481 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1482 if ( eS.empty() ) continue;
1483 TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1484 bool needSmooth = false;
1485 switch ( S.ShapeType() )
1489 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1490 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1492 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1493 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1494 if ( eV.empty() ) continue;
1495 double cosin = eV[0]->_cosin;
1497 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1501 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1502 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1504 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1505 eV[0]->_nodes[0], helper, ok);
1506 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1507 double angle = dir1.Angle( dir2 );
1508 cosin = cos( angle );
1510 needSmooth = ( cosin > 0.1 );
1516 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1518 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1519 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1520 if ( eE.empty() ) continue;
1521 if ( eE[0]->_sWOL.IsNull() )
1523 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1524 needSmooth = ( eE[i]->_cosin > 0.1 );
1528 const TopoDS_Face& F1 = TopoDS::Face( S );
1529 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1530 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1531 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1533 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1534 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1535 double angle = dir1.Angle( dir2 );
1536 double cosin = cos( angle );
1537 needSmooth = ( cosin > 0.1 );
1549 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1550 else shapesToSmooth.push_back ( iS );
1553 } // loop on edgesByGeom
1555 data._edges.reserve( data._n2eMap.size() );
1556 data._endEdgeToSmooth.clear();
1558 // first we put _LayerEdge's on shapes to smooth
1559 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1560 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1562 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1563 if ( eVec.empty() ) continue;
1564 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1565 data._endEdgeToSmooth.push_back( data._edges.size() );
1569 // then the rest _LayerEdge's
1570 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1572 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1573 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1580 //================================================================================
1582 * \brief Set data of _LayerEdge needed for smoothing
1583 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1585 //================================================================================
1587 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1588 const set<TGeomID>& subIds,
1589 SMESH_MesherHelper& helper,
1592 SMESH_MeshEditor editor(_mesh);
1594 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1595 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1599 edge._curvature = 0;
1601 // --------------------------
1602 // Compute _normal and _cosin
1603 // --------------------------
1606 edge._normal.SetCoord(0,0,0);
1608 int totalNbFaces = 0;
1610 gp_Vec du, dv, geomNorm;
1613 TGeomID shapeInd = node->getshapeId();
1614 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1615 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1616 TopoDS_Shape vertEdge;
1618 if ( onShrinkShape ) // one of faces the node is on has no layers
1620 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1621 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1623 // inflate from VERTEX along EDGE
1624 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1626 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1628 // inflate from VERTEX along FACE
1629 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1630 node, helper, normOK, &edge._cosin);
1634 // inflate from EDGE along FACE
1635 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1636 node, helper, normOK);
1639 else // layers are on all faces of SOLID the node is on
1641 // find indices of geom faces the node lies on
1642 set<TGeomID> faceIds;
1643 if ( posType == SMDS_TOP_FACE )
1645 faceIds.insert( node->getshapeId() );
1649 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1650 while ( fIt->more() )
1651 faceIds.insert( editor.FindShape(fIt->next()));
1654 set<TGeomID>::iterator id = faceIds.begin();
1656 for ( ; id != faceIds.end(); ++id )
1658 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1659 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1662 //nbLayerFaces += subIds.count( *id );
1663 F = TopoDS::Face( s );
1665 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1666 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1667 surface->D1( uv.X(),uv.Y(), p, du,dv );
1669 double size2 = geomNorm.SquareMagnitude();
1670 if ( size2 > numeric_limits<double>::min() )
1671 geomNorm /= sqrt( size2 );
1674 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1676 edge._normal += geomNorm.XYZ();
1678 if ( totalNbFaces == 0 )
1679 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1681 edge._normal /= totalNbFaces;
1686 edge._cosin = 0; break;
1688 case SMDS_TOP_EDGE: {
1689 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1690 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1691 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1692 edge._cosin = cos( angle );
1693 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1696 case SMDS_TOP_VERTEX: {
1697 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1698 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK);
1699 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1700 edge._cosin = cos( angle );
1701 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1705 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1709 double normSize = edge._normal.SquareModulus();
1710 if ( normSize < numeric_limits<double>::min() )
1711 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1713 edge._normal /= sqrt( normSize );
1715 // TODO: if ( !normOK ) then get normal by mesh faces
1717 // Set the rest data
1718 // --------------------
1719 if ( onShrinkShape )
1721 edge._sWOL = (*s2s).second;
1723 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1724 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1725 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1727 // set initial position which is parameters on _sWOL in this case
1728 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1730 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1731 edge._pos.push_back( gp_XYZ( u, 0, 0));
1732 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1736 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1737 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1738 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1743 edge._pos.push_back( SMESH_TNodeXYZ( node ));
1745 if ( posType == SMDS_TOP_FACE )
1747 getSimplices( node, edge._simplices, _ignoreShapeIds, &data );
1748 double avgNormProj = 0, avgLen = 0;
1749 for ( unsigned i = 0; i < edge._simplices.size(); ++i )
1751 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
1752 avgNormProj += edge._normal * vec;
1753 avgLen += vec.Modulus();
1755 avgNormProj /= edge._simplices.size();
1756 avgLen /= edge._simplices.size();
1757 edge._curvature = _Curvature::New( avgNormProj, avgLen );
1761 // Set neighbour nodes for a _LayerEdge based on EDGE
1763 if ( posType == SMDS_TOP_EDGE /*||
1764 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1766 edge._2neibors = new _2NearEdges;
1767 // target node instead of source ones will be set later
1768 if ( ! findNeiborsOnEdge( &edge,
1769 edge._2neibors->_nodes[0],
1770 edge._2neibors->_nodes[1],
1773 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1774 edge._2neibors->_nodes[1],
1778 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1783 //================================================================================
1785 * \brief Find 2 neigbor nodes of a node on EDGE
1787 //================================================================================
1789 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
1790 const SMDS_MeshNode*& n1,
1791 const SMDS_MeshNode*& n2,
1794 const SMDS_MeshNode* node = edge->_nodes[0];
1795 const int shapeInd = node->getshapeId();
1796 SMESHDS_SubMesh* edgeSM = 0;
1797 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
1800 edgeSM = getMeshDS()->MeshElements( shapeInd );
1801 if ( !edgeSM || edgeSM->NbElements() == 0 )
1802 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
1806 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
1807 while ( eIt->more() && !n2 )
1809 const SMDS_MeshElement* e = eIt->next();
1810 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
1811 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
1814 if (!edgeSM->Contains(e)) continue;
1818 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
1819 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
1821 ( iN++ ? n2 : n1 ) = nNeibor;
1824 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
1828 //================================================================================
1830 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
1832 //================================================================================
1834 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
1835 const SMDS_MeshNode* n2,
1836 SMESH_MesherHelper& helper)
1838 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1841 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
1842 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
1843 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
1847 double sumLen = vec1.Modulus() + vec2.Modulus();
1848 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
1849 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
1850 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
1851 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
1852 if ( _curvature ) delete _curvature;
1853 _curvature = _Curvature::New( avgNormProj, avgLen );
1855 // if ( _curvature )
1856 // cout << _nodes[0]->GetID()
1857 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
1858 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
1859 // << _curvature->lenDelta(0) << endl;
1864 if ( _sWOL.IsNull() )
1866 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
1867 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
1868 gp_XYZ plnNorm = dirE ^ _normal;
1869 double proj0 = plnNorm * vec1;
1870 double proj1 = plnNorm * vec2;
1871 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
1873 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
1874 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
1879 //================================================================================
1881 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
1882 * this and other _LayerEdge's are inflated along a FACE or an EDGE
1884 //================================================================================
1886 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
1888 _nodes = other._nodes;
1889 _normal = other._normal;
1891 _lenFactor = other._lenFactor;
1892 _cosin = other._cosin;
1893 _sWOL = other._sWOL;
1894 _2neibors = other._2neibors;
1895 _curvature = 0; std::swap( _curvature, other._curvature );
1896 _2neibors = 0; std::swap( _2neibors, other._2neibors );
1898 if ( _sWOL.ShapeType() == TopAbs_EDGE )
1900 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
1901 _pos.push_back( gp_XYZ( u, 0, 0));
1905 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
1906 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1910 //================================================================================
1912 * \brief Set _cosin and _lenFactor
1914 //================================================================================
1916 void _LayerEdge::SetCosin( double cosin )
1919 _lenFactor = ( _cosin > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
1922 //================================================================================
1924 * \brief Fills a vector<_Simplex >
1926 //================================================================================
1928 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
1929 vector<_Simplex>& simplices,
1930 const set<TGeomID>& ingnoreShapes,
1931 const _SolidData* dataToCheckOri,
1934 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1935 while ( fIt->more() )
1937 const SMDS_MeshElement* f = fIt->next();
1938 const TGeomID shapeInd = f->getshapeId();
1939 if ( ingnoreShapes.count( shapeInd )) continue;
1940 const int nbNodes = f->NbCornerNodes();
1941 int srcInd = f->GetNodeIndex( node );
1942 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
1943 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
1944 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
1945 std::swap( nPrev, nNext );
1946 simplices.push_back( _Simplex( nPrev, nNext ));
1951 vector<_Simplex> sortedSimplices( simplices.size() );
1952 sortedSimplices[0] = simplices[0];
1954 for ( size_t i = 1; i < simplices.size(); ++i )
1956 for ( size_t j = 1; j < simplices.size(); ++j )
1957 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
1959 sortedSimplices[i] = simplices[j];
1964 if ( nbFound == simplices.size() - 1 )
1965 simplices.swap( sortedSimplices );
1969 //================================================================================
1971 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
1973 //================================================================================
1975 void _ViscousBuilder::makeGroupOfLE()
1978 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
1980 if ( _sdVec[i]._edges.empty() ) continue;
1981 // string name = SMESH_Comment("_LayerEdge's_") << i;
1983 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
1984 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
1985 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
1987 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
1988 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
1990 _LayerEdge* le = _sdVec[i]._edges[j];
1991 for ( unsigned iN = 1; iN < le->_nodes.size(); ++iN )
1992 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
1993 << ", " << le->_nodes[iN]->GetID() <<"])");
1994 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
1998 dumpFunction( SMESH_Comment("makeNormals") << i );
1999 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2001 _LayerEdge& edge = *_sdVec[i]._edges[j];
2002 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2003 nXYZ += edge._normal * _sdVec[i]._stepSize;
2004 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2005 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2009 // name = SMESH_Comment("tmp_faces ") << i;
2010 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2011 // gDS = (SMESHDS_Group*)g->GetGroupDS();
2012 // SMESH_MeshEditor editor( _mesh );
2013 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2014 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2015 for ( ; fExp.More(); fExp.Next() )
2017 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2019 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2020 while ( fIt->more())
2022 const SMDS_MeshElement* e = fIt->next();
2023 SMESH_Comment cmd("mesh.AddFace([");
2024 for ( int j=0; j < e->NbCornerNodes(); ++j )
2025 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2027 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2028 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2037 //================================================================================
2039 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2041 //================================================================================
2043 bool _ViscousBuilder::inflate(_SolidData& data)
2045 SMESH_MesherHelper helper( *_mesh );
2047 // Limit inflation step size by geometry size found by itersecting
2048 // normals of _LayerEdge's with mesh faces
2049 double geomSize = Precision::Infinite(), intersecDist;
2050 SMESH_MeshEditor editor( _mesh );
2051 auto_ptr<SMESH_ElementSearcher> searcher
2052 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2053 for ( unsigned i = 0; i < data._edges.size(); ++i )
2055 if ( data._edges[i]->IsOnEdge() ) continue;
2056 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2057 if ( geomSize > intersecDist )
2058 geomSize = intersecDist;
2060 if ( data._stepSize > 0.3 * geomSize )
2061 limitStepSize( data, 0.3 * geomSize );
2063 const double tgtThick = data._hyp->GetTotalThickness();
2064 if ( data._stepSize > tgtThick )
2065 limitStepSize( data, tgtThick );
2067 if ( data._stepSize < 1. )
2068 data._epsilon = data._stepSize * 1e-7;
2071 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2074 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2075 int nbSteps = 0, nbRepeats = 0;
2076 while ( 1.01 * avgThick < tgtThick )
2078 // new target length
2079 curThick += data._stepSize;
2080 if ( curThick > tgtThick )
2082 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2086 // Elongate _LayerEdge's
2087 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2088 for ( unsigned i = 0; i < data._edges.size(); ++i )
2090 data._edges[i]->SetNewLength( curThick, helper );
2095 if ( !updateNormals( data, helper ) )
2098 // Improve and check quality
2099 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2103 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2104 for ( unsigned i = 0; i < data._edges.size(); ++i )
2106 data._edges[i]->InvalidateStep( nbSteps+1 );
2110 break; // no more inflating possible
2114 // Evaluate achieved thickness
2116 for ( unsigned i = 0; i < data._edges.size(); ++i )
2117 avgThick += data._edges[i]->_len;
2118 avgThick /= data._edges.size();
2120 cout << "-- Thickness " << avgThick << " reached" << endl;
2123 if ( distToIntersection < avgThick*1.5 )
2126 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2127 << avgThick << " ) * 1.5" << endl;
2132 limitStepSize( data, 0.25 * distToIntersection );
2133 if ( data._stepSizeNodes[0] )
2134 data._stepSize = data._stepSizeCoeff *
2135 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2139 return error("failed at the very first inflation step", data._index);
2144 //================================================================================
2146 * \brief Improve quality of layer inner surface and check intersection
2148 //================================================================================
2150 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2152 double & distToIntersection)
2154 if ( data._endEdgeToSmooth.empty() )
2155 return true; // no shapes needing smoothing
2157 bool moved, improved;
2159 SMESH_MesherHelper helper(*_mesh);
2160 Handle(Geom_Surface) surface;
2164 for ( unsigned iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2167 iEnd = data._endEdgeToSmooth[ iS ];
2169 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2170 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2172 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2173 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2174 helper.SetSubShape( F );
2175 surface = BRep_Tool::Surface( F );
2180 F.Nullify(); surface.Nullify();
2182 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2184 if ( data._edges[ iBeg ]->IsOnEdge() )
2186 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2188 // try a simple solution on an analytic EDGE
2189 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2195 for ( int i = iBeg; i < iEnd; ++i )
2197 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2199 dumpCmd( SMESH_Comment("# end step ")<<step);
2201 while ( moved && step++ < 5 );
2202 //cout << " NB STEPS: " << step << endl;
2209 int step = 0, badNb = 0; moved = true;
2210 while (( ++step <= 5 && moved ) || improved )
2212 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2213 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2214 int oldBadNb = badNb;
2217 for ( int i = iBeg; i < iEnd; ++i )
2218 moved |= data._edges[i]->Smooth(badNb);
2219 improved = ( badNb < oldBadNb );
2226 for ( int i = iBeg; i < iEnd; ++i )
2228 _LayerEdge* edge = data._edges[i];
2229 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2230 for ( unsigned j = 0; j < edge->_simplices.size(); ++j )
2231 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2233 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2234 << " "<< edge->_simplices[j]._nPrev->GetID()
2235 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2243 } // loop on shapes to smooth
2245 // Check if the last segments of _LayerEdge intersects 2D elements;
2246 // checked elements are either temporary faces or faces on surfaces w/o the layers
2248 SMESH_MeshEditor editor( _mesh );
2249 auto_ptr<SMESH_ElementSearcher> searcher
2250 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2252 distToIntersection = Precision::Infinite();
2254 const SMDS_MeshElement* intFace = 0;
2256 const SMDS_MeshElement* closestFace = 0;
2259 for ( unsigned i = 0; i < data._edges.size(); ++i )
2261 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2263 if ( distToIntersection > dist )
2265 distToIntersection = dist;
2268 closestFace = intFace;
2275 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2276 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2277 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2278 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2279 << ") distance = " << distToIntersection<< endl;
2286 //================================================================================
2288 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2289 * _LayerEdge's to be in a consequent order
2291 //================================================================================
2293 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2296 Handle(Geom_Surface)& surface,
2297 const TopoDS_Face& F,
2298 SMESH_MesherHelper& helper)
2300 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2302 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2304 if ( i2curve == _edge2curve.end() )
2306 // sort _LayerEdge's by position on the EDGE
2308 map< double, _LayerEdge* > u2edge;
2309 for ( int i = iFrom; i < iTo; ++i )
2310 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2312 ASSERT( u2edge.size() == iTo - iFrom );
2313 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2314 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2315 _edges[i] = u2e->second;
2317 // set _2neibors according to the new order
2318 for ( int i = iFrom; i < iTo-1; ++i )
2319 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2320 _edges[i]->_2neibors->reverse();
2321 if ( u2edge.size() > 1 &&
2322 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2323 _edges[iTo-1]->_2neibors->reverse();
2326 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2328 TopLoc_Location loc; double f,l;
2330 Handle(Geom_Line) line;
2331 Handle(Geom_Circle) circle;
2332 bool isLine, isCirc;
2333 if ( F.IsNull() ) // 3D case
2335 // check if the EDGE is a line
2336 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2337 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2338 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2340 line = Handle(Geom_Line)::DownCast( curve );
2341 circle = Handle(Geom_Circle)::DownCast( curve );
2342 isLine = (!line.IsNull());
2343 isCirc = (!circle.IsNull());
2345 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2348 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2349 while ( nIt->more() )
2350 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2351 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2353 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2354 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2355 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2356 for ( int i = 0; i < 3 && !isLine; ++i )
2357 isLine = ( size.Coord( i+1 ) <= lineTol );
2359 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2366 // check if the EDGE is a line
2367 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2368 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2369 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2371 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2372 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2373 isLine = (!line2d.IsNull());
2374 isCirc = (!circle2d.IsNull());
2376 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2379 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2380 while ( nIt->more() )
2381 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2382 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2384 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2385 for ( int i = 0; i < 2 && !isLine; ++i )
2386 isLine = ( size.Coord( i+1 ) <= lineTol );
2388 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2394 line = new Geom_Line( gp::OX() ); // only type does matter
2398 gp_Pnt2d p = circle2d->Location();
2399 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2400 circle = new Geom_Circle( ax, 1.); // only center position does matter
2404 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2412 return i2curve->second;
2415 //================================================================================
2417 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2419 //================================================================================
2421 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2424 Handle(Geom_Surface)& surface,
2425 const TopoDS_Face& F,
2426 SMESH_MesherHelper& helper)
2428 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2429 helper.GetMeshDS());
2430 TopoDS_Edge E = TopoDS::Edge( S );
2432 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2433 if ( curve.IsNull() ) return false;
2435 // compute a relative length of segments
2436 vector< double > len( iTo-iFrom+1 );
2438 double curLen, prevLen = len[0] = 1.0;
2439 for ( int i = iFrom; i < iTo; ++i )
2441 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2442 len[i-iFrom+1] = len[i-iFrom] + curLen;
2447 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2449 if ( F.IsNull() ) // 3D
2451 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2452 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2453 for ( int i = iFrom; i < iTo; ++i )
2455 double r = len[i-iFrom] / len.back();
2456 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2457 data._edges[i]->_pos.back() = newPos;
2458 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2459 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2460 dumpMove( tgtNode );
2465 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2466 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2467 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2468 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2470 int iPeriodic = helper.GetPeriodicIndex();
2471 if ( iPeriodic == 1 || iPeriodic == 2 )
2473 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2474 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2475 std::swap( uv0, uv1 );
2478 const gp_XY rangeUV = uv1 - uv0;
2479 for ( int i = iFrom; i < iTo; ++i )
2481 double r = len[i-iFrom] / len.back();
2482 gp_XY newUV = uv0 + r * rangeUV;
2483 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2485 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2486 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2487 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2488 dumpMove( tgtNode );
2490 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2491 pos->SetUParameter( newUV.X() );
2492 pos->SetVParameter( newUV.Y() );
2498 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2500 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2501 gp_Pnt center3D = circle->Location();
2503 if ( F.IsNull() ) // 3D
2505 return false; // TODO ???
2509 const gp_XY center( center3D.X(), center3D.Y() );
2511 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2512 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2513 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2514 gp_Vec2d vec0( center, uv0 );
2515 gp_Vec2d vecM( center, uvM );
2516 gp_Vec2d vec1( center, uv1 );
2517 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2518 double uMidl = vec0.Angle( vecM );
2519 if ( uLast * uMidl < 0. )
2520 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
2521 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2523 gp_Ax2d axis( center, vec0 );
2524 gp_Circ2d circ( axis, radius );
2525 for ( int i = iFrom; i < iTo; ++i )
2527 double newU = uLast * len[i-iFrom] / len.back();
2528 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2529 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2531 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2532 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2533 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2534 dumpMove( tgtNode );
2536 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2537 pos->SetUParameter( newUV.X() );
2538 pos->SetVParameter( newUV.Y() );
2547 //================================================================================
2549 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2550 * _LayerEdge's on neighbor EDGE's
2552 //================================================================================
2554 bool _ViscousBuilder::updateNormals( _SolidData& data,
2555 SMESH_MesherHelper& helper )
2557 // make temporary quadrangles got by extrusion of
2558 // mesh edges along _LayerEdge._normal's
2560 vector< const SMDS_MeshElement* > tmpFaces;
2562 set< SMESH_TLink > extrudedLinks; // contains target nodes
2563 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2565 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2566 for ( unsigned i = 0; i < data._edges.size(); ++i )
2568 _LayerEdge* edge = data._edges[i];
2569 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2570 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2571 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2573 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2574 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2575 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2576 if ( !link_isnew.second )
2578 extrudedLinks.erase( link_isnew.first );
2579 continue; // already extruded and will no more encounter
2581 // look for a _LayerEdge containg tgt2
2582 // _LayerEdge* neiborEdge = 0;
2583 // unsigned di = 0; // check _edges[i+di] and _edges[i-di]
2584 // while ( !neiborEdge && ++di <= data._edges.size() )
2586 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2587 // neiborEdge = data._edges[i+di];
2588 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2589 // neiborEdge = data._edges[i-di];
2591 // if ( !neiborEdge )
2592 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2593 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2595 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2596 tmpFaces.push_back( f );
2598 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2599 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2600 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2605 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2606 // Perform two loops on _LayerEdge on EDGE's:
2607 // 1) to find and fix intersection
2608 // 2) to check that no new intersection appears as result of 1)
2610 SMESH_MeshEditor editor( _mesh );
2611 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2613 auto_ptr<SMESH_ElementSearcher> searcher ( editor.GetElementSearcher( fIt ));
2615 // 1) Find intersections
2617 const SMDS_MeshElement* face;
2618 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2619 TLEdge2LEdgeSet edge2CloseEdge;
2621 const double eps = data._epsilon * data._epsilon;
2622 for ( unsigned i = 0; i < data._edges.size(); ++i )
2624 _LayerEdge* edge = data._edges[i];
2625 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2626 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2628 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2629 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2630 ee.insert( f->_le1 );
2631 ee.insert( f->_le2 );
2632 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
2633 edge2CloseEdge[ f->_le1 ].insert( edge );
2634 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
2635 edge2CloseEdge[ f->_le2 ].insert( edge );
2639 // Set _LayerEdge._normal
2641 if ( !edge2CloseEdge.empty() )
2643 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2645 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2646 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2648 _LayerEdge* edge1 = e2ee->first;
2649 _LayerEdge* edge2 = 0;
2650 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
2652 // find EDGEs the edges reside
2654 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2655 if ( S.ShapeType() != TopAbs_EDGE )
2656 continue; // TODO: find EDGE by VERTEX
2657 E1 = TopoDS::Edge( S );
2658 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
2659 while ( E2.IsNull() && eIt != ee.end())
2661 _LayerEdge* e2 = *eIt++;
2662 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2663 if ( S.ShapeType() == TopAbs_EDGE )
2664 E2 = TopoDS::Edge( S ), edge2 = e2;
2666 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2668 // find 3 FACEs sharing 2 EDGEs
2670 TopoDS_Face FF1[2], FF2[2];
2671 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2672 while ( fIt->more() && FF1[1].IsNull())
2674 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2675 if ( helper.IsSubShape( *F, data._solid))
2676 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2678 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2679 while ( fIt->more() && FF2[1].IsNull())
2681 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2682 if ( helper.IsSubShape( *F, data._solid))
2683 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2685 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2686 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2687 std::swap( FF1[0], FF1[1] );
2688 if ( FF2[0].IsSame( FF1[0]) )
2689 std::swap( FF2[0], FF2[1] );
2690 if ( FF1[0].IsNull() || FF2[0].IsNull() )
2693 // // get a new normal for edge1
2695 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2696 if ( edge1->_cosin < 0 )
2697 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2698 if ( edge2->_cosin < 0 )
2699 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2700 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2701 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2702 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2703 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2704 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2705 // newNorm.Normalize();
2707 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2708 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2709 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2710 newNorm.Normalize();
2712 edge1->_normal = newNorm.XYZ();
2714 // update data of edge1 depending on _normal
2715 const SMDS_MeshNode *n1, *n2;
2716 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2717 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2718 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2720 edge1->SetDataByNeighbors( n1, n2, helper );
2722 if ( edge1->_cosin < 0 )
2725 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2726 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2727 edge1->SetCosin( cos( angle ));
2729 // limit data._stepSize
2730 if ( edge1->_cosin > 0.1 )
2732 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2733 while ( fIt->more() )
2734 limitStepSize( data, fIt->next(), edge1->_cosin );
2736 // set new XYZ of target node
2737 edge1->InvalidateStep( 1 );
2739 edge1->SetNewLength( data._stepSize, helper );
2742 // Update normals and other dependent data of not intersecting _LayerEdge's
2743 // neighboring the intersecting ones
2745 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2747 _LayerEdge* edge1 = e2ee->first;
2748 if ( !edge1->_2neibors )
2750 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2752 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2753 if ( edge2CloseEdge.count ( neighbor ))
2754 continue; // j-th neighbor is also intersected
2755 _LayerEdge* prevEdge = edge1;
2756 const int nbSteps = 6;
2757 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2759 if ( !neighbor->_2neibors )
2760 break; // neighbor is on VERTEX
2762 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2763 if ( nextEdge == prevEdge )
2764 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2765 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2766 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
2767 double r = double(step-1)/nbSteps;
2768 if ( !nextEdge->_2neibors )
2771 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2772 newNorm.Normalize();
2774 neighbor->_normal = newNorm;
2775 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2776 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2778 neighbor->InvalidateStep( 1 );
2780 neighbor->SetNewLength( data._stepSize, helper );
2782 // goto the next neighbor
2783 prevEdge = neighbor;
2784 neighbor = nextEdge;
2790 // 2) Check absence of intersections
2793 for ( unsigned i = 0 ; i < tmpFaces.size(); ++i )
2799 //================================================================================
2801 * \brief Looks for intersection of it's last segment with faces
2802 * \param distance - returns shortest distance from the last node to intersection
2804 //================================================================================
2806 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
2808 const double& epsilon,
2809 const SMDS_MeshElement** face)
2811 vector< const SMDS_MeshElement* > suspectFaces;
2813 gp_Ax1 lastSegment = LastSegment(segLen);
2814 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2816 bool segmentIntersected = false;
2817 distance = Precision::Infinite();
2818 int iFace = -1; // intersected face
2819 for ( unsigned j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
2821 const SMDS_MeshElement* face = suspectFaces[j];
2822 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
2823 face->GetNodeIndex( _nodes[0] ) >= 0 )
2824 continue; // face sharing _LayerEdge node
2825 const int nbNodes = face->NbCornerNodes();
2826 bool intFound = false;
2828 SMDS_MeshElement::iterator nIt = face->begin_nodes();
2831 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
2835 const SMDS_MeshNode* tria[3];
2838 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
2841 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
2847 if ( dist < segLen*(1.01))
2848 segmentIntersected = true;
2849 if ( distance > dist )
2850 distance = dist, iFace = j;
2853 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
2854 // if ( distance && iFace > -1 )
2856 // // distance is used to limit size of inflation step which depends on
2857 // // whether the intersected face bears viscous layers or not
2858 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
2862 if ( segmentIntersected )
2865 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
2866 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
2867 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
2868 << ", intersection with face ("
2869 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2870 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
2871 << ") distance = " << distance - segLen<< endl;
2877 return segmentIntersected;
2880 //================================================================================
2882 * \brief Returns size and direction of the last segment
2884 //================================================================================
2886 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
2888 // find two non-coincident positions
2889 gp_XYZ orig = _pos.back();
2891 int iPrev = _pos.size() - 2;
2892 while ( iPrev >= 0 )
2894 dir = orig - _pos[iPrev];
2895 if ( dir.SquareModulus() > 1e-100 )
2905 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
2906 segDir.SetDirection( _normal );
2911 gp_Pnt pPrev = _pos[ iPrev ];
2912 if ( !_sWOL.IsNull() )
2914 TopLoc_Location loc;
2915 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2918 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2919 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
2923 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2924 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
2926 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
2928 segDir.SetLocation( pPrev );
2929 segDir.SetDirection( dir );
2930 segLen = dir.Modulus();
2936 //================================================================================
2938 * \brief Test intersection of the last segment with a given triangle
2939 * using Moller-Trumbore algorithm
2940 * Intersection is detected if distance to intersection is less than _LayerEdge._len
2942 //================================================================================
2944 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
2945 const SMDS_MeshNode* n0,
2946 const SMDS_MeshNode* n1,
2947 const SMDS_MeshNode* n2,
2949 const double& EPSILON) const
2951 //const double EPSILON = 1e-6;
2953 gp_XYZ orig = lastSegment.Location().XYZ();
2954 gp_XYZ dir = lastSegment.Direction().XYZ();
2956 SMESH_TNodeXYZ vert0( n0 );
2957 SMESH_TNodeXYZ vert1( n1 );
2958 SMESH_TNodeXYZ vert2( n2 );
2960 /* calculate distance from vert0 to ray origin */
2961 gp_XYZ tvec = orig - vert0;
2963 if ( tvec * dir > EPSILON )
2964 // intersected face is at back side of the temporary face this _LayerEdge belongs to
2967 gp_XYZ edge1 = vert1 - vert0;
2968 gp_XYZ edge2 = vert2 - vert0;
2970 /* begin calculating determinant - also used to calculate U parameter */
2971 gp_XYZ pvec = dir ^ edge2;
2973 /* if determinant is near zero, ray lies in plane of triangle */
2974 double det = edge1 * pvec;
2976 if (det > -EPSILON && det < EPSILON)
2978 double inv_det = 1.0 / det;
2980 /* calculate U parameter and test bounds */
2981 double u = ( tvec * pvec ) * inv_det;
2982 if (u < 0.0 || u > 1.0)
2985 /* prepare to test V parameter */
2986 gp_XYZ qvec = tvec ^ edge1;
2988 /* calculate V parameter and test bounds */
2989 double v = (dir * qvec) * inv_det;
2990 if ( v < 0.0 || u + v > 1.0 )
2993 /* calculate t, ray intersects triangle */
2994 t = (edge2 * qvec) * inv_det;
2996 // if (det < EPSILON)
2999 // /* calculate distance from vert0 to ray origin */
3000 // gp_XYZ tvec = orig - vert0;
3002 // /* calculate U parameter and test bounds */
3003 // double u = tvec * pvec;
3004 // if (u < 0.0 || u > det)
3007 // /* prepare to test V parameter */
3008 // gp_XYZ qvec = tvec ^ edge1;
3010 // /* calculate V parameter and test bounds */
3011 // double v = dir * qvec;
3012 // if (v < 0.0 || u + v > det)
3015 // /* calculate t, scale parameters, ray intersects triangle */
3016 // double t = edge2 * qvec;
3017 // double inv_det = 1.0 / det;
3025 //================================================================================
3027 * \brief Perform smooth of _LayerEdge's based on EDGE's
3028 * \retval bool - true if node has been moved
3030 //================================================================================
3032 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3033 const TopoDS_Face& F,
3034 SMESH_MesherHelper& helper)
3036 ASSERT( IsOnEdge() );
3038 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3039 SMESH_TNodeXYZ oldPos( tgtNode );
3040 double dist01, distNewOld;
3042 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3043 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3044 dist01 = p0.Distance( _2neibors->_nodes[1] );
3046 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3047 double lenDelta = 0;
3050 lenDelta = _curvature->lenDelta( _len );
3051 newPos.ChangeCoord() += _normal * lenDelta;
3054 distNewOld = newPos.Distance( oldPos );
3058 if ( _2neibors->_plnNorm )
3060 // put newPos on the plane defined by source node and _plnNorm
3061 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3062 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3063 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3065 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3066 _pos.back() = newPos.XYZ();
3070 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3071 gp_XY uv( Precision::Infinite(), 0 );
3072 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3073 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3075 newPos = surface->Value( uv.X(), uv.Y() );
3076 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3079 if ( _curvature && lenDelta < 0 )
3081 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3082 _len -= prevPos.Distance( oldPos );
3083 _len += prevPos.Distance( newPos );
3085 bool moved = distNewOld > dist01/50;
3087 dumpMove( tgtNode ); // debug
3092 //================================================================================
3094 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3095 * \retval bool - true if _tgtNode has been moved
3097 //================================================================================
3099 bool _LayerEdge::Smooth(int& badNb)
3101 if ( _simplices.size() < 2 )
3102 return false; // _LayerEdge inflated along EDGE or FACE
3104 // compute new position for the last _pos
3105 gp_XYZ newPos (0,0,0);
3106 for ( unsigned i = 0; i < _simplices.size(); ++i )
3107 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3108 newPos /= _simplices.size();
3111 newPos += _normal * _curvature->lenDelta( _len );
3113 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3114 // if ( _cosin < -0.1)
3116 // // Avoid decreasing length of edge on concave surface
3117 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3118 // gp_Vec newMove( prevPos, newPos );
3119 // newPos = _pos.back() + newMove.XYZ();
3121 // else if ( _cosin > 0.3 )
3123 // // Avoid increasing length of edge too much
3126 // count quality metrics (orientation) of tetras around _tgtNode
3128 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3129 for ( unsigned i = 0; i < _simplices.size(); ++i )
3130 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3133 for ( unsigned i = 0; i < _simplices.size(); ++i )
3134 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3136 if ( nbOkAfter < nbOkBefore )
3139 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3141 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3142 _len += prevPos.Distance(newPos);
3144 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3145 _pos.back() = newPos;
3147 badNb += _simplices.size() - nbOkAfter;
3154 //================================================================================
3156 * \brief Add a new segment to _LayerEdge during inflation
3158 //================================================================================
3160 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3162 if ( _len - len > -1e-6 )
3164 _pos.push_back( _pos.back() );
3168 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3169 SMESH_TNodeXYZ oldXYZ( n );
3170 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3171 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3173 _pos.push_back( nXYZ );
3175 if ( !_sWOL.IsNull() )
3178 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3180 double u = Precision::Infinite(); // to force projection w/o distance check
3181 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3182 _pos.back().SetCoord( u, 0, 0 );
3183 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3184 pos->SetUParameter( u );
3188 gp_XY uv( Precision::Infinite(), 0 );
3189 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3190 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3191 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3192 pos->SetUParameter( uv.X() );
3193 pos->SetVParameter( uv.Y() );
3195 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3197 dumpMove( n ); //debug
3200 //================================================================================
3202 * \brief Remove last inflation step
3204 //================================================================================
3206 void _LayerEdge::InvalidateStep( int curStep )
3208 if ( _pos.size() > curStep )
3210 _pos.resize( curStep );
3211 gp_Pnt nXYZ = _pos.back();
3212 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3213 if ( !_sWOL.IsNull() )
3215 TopLoc_Location loc;
3216 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3218 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3219 pos->SetUParameter( nXYZ.X() );
3221 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3222 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3226 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3227 pos->SetUParameter( nXYZ.X() );
3228 pos->SetVParameter( nXYZ.Y() );
3229 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3230 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3233 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3238 //================================================================================
3240 * \brief Create layers of prisms
3242 //================================================================================
3244 bool _ViscousBuilder::refine(_SolidData& data)
3246 SMESH_MesherHelper helper( *_mesh );
3247 helper.SetSubShape( data._solid );
3248 helper.SetElementsOnShape(false);
3250 Handle(Geom_Curve) curve;
3251 Handle(Geom_Surface) surface;
3252 TopoDS_Edge geomEdge;
3253 TopoDS_Face geomFace;
3254 TopLoc_Location loc;
3255 double f,l, u/*, distXYZ[4]*/;
3259 for ( unsigned i = 0; i < data._edges.size(); ++i )
3261 _LayerEdge& edge = *data._edges[i];
3263 // get accumulated length of segments
3264 vector< double > segLen( edge._pos.size() );
3266 for ( unsigned j = 1; j < edge._pos.size(); ++j )
3267 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3269 // allocate memory for new nodes if it is not yet refined
3270 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3271 if ( edge._nodes.size() == 2 )
3273 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3275 edge._nodes.back() = tgtNode;
3277 if ( !edge._sWOL.IsNull() )
3279 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3280 // restore position of the last node
3284 geomEdge = TopoDS::Edge( edge._sWOL );
3285 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3286 // double u = helper.GetNodeU( tgtNode );
3287 // p = curve->Value( u );
3291 geomFace = TopoDS::Face( edge._sWOL );
3292 surface = BRep_Tool::Surface( geomFace, loc );
3293 // gp_XY uv = helper.GetNodeUV( tgtNode );
3294 // p = surface->Value( uv.X(), uv.Y() );
3296 // p.Transform( loc );
3297 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3299 // calculate height of the first layer
3301 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3302 const double f = data._hyp->GetStretchFactor();
3303 const int N = data._hyp->GetNumberLayers();
3304 const double fPowN = pow( f, N );
3305 if ( fPowN - 1 <= numeric_limits<double>::min() )
3308 h0 = T * ( f - 1 )/( fPowN - 1 );
3310 const double zeroLen = std::numeric_limits<double>::min();
3312 // create intermediate nodes
3313 double hSum = 0, hi = h0/f;
3315 for ( unsigned iStep = 1; iStep < edge._nodes.size(); ++iStep )
3317 // compute an intermediate position
3320 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3322 int iPrevSeg = iSeg-1;
3323 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3325 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3326 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3328 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3329 if ( !edge._sWOL.IsNull() )
3331 // compute XYZ by parameters <pos>
3335 pos = curve->Value( u ).Transformed(loc);
3339 uv.SetCoord( pos.X(), pos.Y() );
3340 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3343 // create or update the node
3346 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3347 if ( !edge._sWOL.IsNull() )
3350 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3352 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3356 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3361 if ( !edge._sWOL.IsNull() )
3363 // make average pos from new and current parameters
3366 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3367 pos = curve->Value( u ).Transformed(loc);
3371 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3372 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3375 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3380 // TODO: make quadratic prisms and polyhedrons(?)
3382 helper.SetElementsOnShape(true);
3384 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3385 for ( ; exp.More(); exp.Next() )
3387 if ( _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3389 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3390 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3391 vector< vector<const SMDS_MeshNode*>* > nnVec;
3392 while ( fIt->more() )
3394 const SMDS_MeshElement* face = fIt->next();
3395 int nbNodes = face->NbCornerNodes();
3396 nnVec.resize( nbNodes );
3397 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3398 for ( int iN = 0; iN < nbNodes; ++iN )
3400 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3401 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3404 int nbZ = nnVec[0]->size();
3408 for ( int iZ = 1; iZ < nbZ; ++iZ )
3409 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3410 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3413 for ( int iZ = 1; iZ < nbZ; ++iZ )
3414 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3415 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3416 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3417 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3420 return error("Not supported type of element", data._index);
3427 //================================================================================
3429 * \brief Shrink 2D mesh on faces to let space for inflated layers
3431 //================================================================================
3433 bool _ViscousBuilder::shrink()
3435 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3436 // inflated along FACE or EDGE)
3437 map< TGeomID, _SolidData* > f2sdMap;
3438 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
3440 _SolidData& data = _sdVec[i];
3441 TopTools_MapOfShape FFMap;
3442 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3443 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3444 if ( s2s->second.ShapeType() == TopAbs_FACE )
3446 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3448 if ( FFMap.Add( (*s2s).second ))
3449 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3450 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3451 // by StdMeshers_QuadToTriaAdaptor
3452 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3454 SMESH_ProxyMesh::SubMesh* proxySub =
3455 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3456 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3457 while ( fIt->more() )
3458 proxySub->AddElement( fIt->next() );
3459 // as a result 3D algo will use elements from proxySub and not from smDS
3464 SMESH_MesherHelper helper( *_mesh );
3465 helper.ToFixNodeParameters( true );
3468 map< int, _Shrinker1D > e2shrMap;
3470 // loop on FACES to srink mesh on
3471 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3472 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3474 _SolidData& data = *f2sd->second;
3475 TNode2Edge& n2eMap = data._n2eMap;
3476 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3478 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3480 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3481 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3483 helper.SetSubShape(F);
3485 // ===========================
3486 // Prepare data for shrinking
3487 // ===========================
3489 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3490 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3491 vector < const SMDS_MeshNode* > smoothNodes;
3493 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3494 while ( nIt->more() )
3496 const SMDS_MeshNode* n = nIt->next();
3497 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3498 smoothNodes.push_back( n );
3501 // Find out face orientation
3503 const set<TGeomID> ignoreShapes;
3505 if ( !smoothNodes.empty() )
3507 vector<_Simplex> simplices;
3508 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3509 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3510 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3511 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3512 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3516 // Find _LayerEdge's inflated along F
3517 vector< _LayerEdge* > lEdges;
3519 SMESH_subMeshIteratorPtr subIt =
3520 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3521 while ( subIt->more() )
3523 SMESH_subMesh* sub = subIt->next();
3524 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3525 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3527 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3528 while ( nIt->more() )
3530 _LayerEdge* edge = n2eMap[ nIt->next() ];
3531 lEdges.push_back( edge );
3532 prepareEdgeToShrink( *edge, F, helper, smDS );
3537 // Replace source nodes by target nodes in mesh faces to shrink
3538 const SMDS_MeshNode* nodes[20];
3539 for ( unsigned i = 0; i < lEdges.size(); ++i )
3541 _LayerEdge& edge = *lEdges[i];
3542 const SMDS_MeshNode* srcNode = edge._nodes[0];
3543 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3544 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3545 while ( fIt->more() )
3547 const SMDS_MeshElement* f = fIt->next();
3548 if ( !smDS->Contains( f ))
3550 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3551 for ( int iN = 0; iN < f->NbNodes(); ++iN )
3553 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3554 nodes[iN] = ( n == srcNode ? tgtNode : n );
3556 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3560 // find out if a FACE is concave
3561 const bool isConcaveFace = isConcave( F, helper );
3563 // Create _SmoothNode's on face F
3564 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3566 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3567 for ( unsigned i = 0; i < smoothNodes.size(); ++i )
3569 const SMDS_MeshNode* n = smoothNodes[i];
3570 nodesToSmooth[ i ]._node = n;
3571 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3572 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, isConcaveFace );
3573 // fix up incorrect uv of nodes on the FACE
3574 helper.GetNodeUV( F, n, 0, &isOkUV);
3579 //if ( nodesToSmooth.empty() ) continue;
3581 // Find EDGE's to shrink
3582 set< _Shrinker1D* > eShri1D;
3584 for ( unsigned i = 0; i < lEdges.size(); ++i )
3586 _LayerEdge* edge = lEdges[i];
3587 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3589 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3590 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3591 eShri1D.insert( & srinker );
3592 srinker.AddEdge( edge, helper );
3593 // restore params of nodes on EGDE if the EDGE has been already
3594 // srinked while srinking another FACE
3595 srinker.RestoreParams();
3600 // ==================
3601 // Perform shrinking
3602 // ==================
3604 bool shrinked = true;
3605 int badNb, shriStep=0, smooStep=0;
3608 // Move boundary nodes (actually just set new UV)
3609 // -----------------------------------------------
3610 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep++ ); // debug
3612 for ( unsigned i = 0; i < lEdges.size(); ++i )
3614 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3618 // Move nodes on EDGE's
3619 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3620 for ( ; shr != eShri1D.end(); ++shr )
3621 (*shr)->Compute( /*set3D=*/false, helper );
3624 // -----------------
3625 int nbNoImpSteps = 0;
3628 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3630 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3632 int oldBadNb = badNb;
3635 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3637 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3638 /*isCentroidal=*/isConcaveFace,/*set3D=*/false );
3640 if ( badNb < oldBadNb )
3648 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3650 // No wrongly shaped faces remain; final smooth. Set node XYZ.
3651 // First, find out a needed quality of smoothing (high for quadrangles only)
3654 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
3655 if ( hasTria != hasQuad )
3657 highQuality = hasQuad;
3661 set<int> nbNodesSet;
3662 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3663 while ( fIt->more() && nbNodesSet.size() < 2 )
3664 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
3665 highQuality = ( *nbNodesSet.begin() == 4 );
3668 if ( !highQuality && isConcaveFace )
3669 fixBadFaces( F, helper ); // fix narrow faces by swaping diagonals
3670 for ( int st = highQuality ? 10 : 3; st; --st )
3672 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3673 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3674 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3675 /*isCentroidal=*/isConcaveFace,/*set3D=*/st==1 );
3678 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
3679 _SrinkShapeListener::ToClearSubMeshWithSolid( sm, data._solid );
3681 } // loop on FACES to srink mesh on
3684 // Replace source nodes by target nodes in shrinked mesh edges
3686 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3687 for ( ; e2shr != e2shrMap.end(); ++e2shr )
3688 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3693 //================================================================================
3695 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3697 //================================================================================
3699 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
3700 const TopoDS_Face& F,
3701 SMESH_MesherHelper& helper,
3702 const SMESHDS_SubMesh* faceSubMesh)
3704 const SMDS_MeshNode* srcNode = edge._nodes[0];
3705 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3709 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3711 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3712 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3713 gp_Vec2d uvDir( srcUV, tgtUV );
3714 double uvLen = uvDir.Magnitude();
3716 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3718 // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3719 vector<const SMDS_MeshElement*> faces;
3720 multimap< double, const SMDS_MeshNode* > proj2node;
3721 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3722 while ( fIt->more() )
3724 const SMDS_MeshElement* f = fIt->next();
3725 if ( faceSubMesh->Contains( f ))
3726 faces.push_back( f );
3728 for ( unsigned i = 0; i < faces.size(); ++i )
3730 const int nbNodes = faces[i]->NbCornerNodes();
3731 for ( int j = 0; j < nbNodes; ++j )
3733 const SMDS_MeshNode* n = faces[i]->GetNode(j);
3734 if ( n == srcNode ) continue;
3735 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3736 ( faces.size() > 1 || nbNodes > 3 ))
3738 gp_Pnt2d uv = helper.GetNodeUV( F, n );
3739 gp_Vec2d uvDirN( srcUV, uv );
3740 double proj = uvDirN * uvDir;
3741 proj2node.insert( make_pair( proj, n ));
3745 multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
3746 const double minProj = p2n->first;
3747 const double projThreshold = 1.1 * uvLen;
3748 if ( minProj > projThreshold )
3750 // tgtNode is located so that it does not make faces with wrong orientation
3753 edge._pos.resize(1);
3754 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
3756 // store most risky nodes in _simplices
3757 p2nEnd = proj2node.lower_bound( projThreshold );
3758 int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
3759 edge._simplices.resize( nbSimpl );
3760 for ( int i = 0; i < nbSimpl; ++i )
3762 edge._simplices[i]._nPrev = p2n->second;
3763 if ( ++p2n != p2nEnd )
3764 edge._simplices[i]._nNext = p2n->second;
3766 // set UV of source node to target node
3767 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3768 pos->SetUParameter( srcUV.X() );
3769 pos->SetVParameter( srcUV.Y() );
3771 else // _sWOL is TopAbs_EDGE
3773 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
3774 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
3775 if ( !edgeSM || edgeSM->NbElements() == 0 )
3776 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3778 const SMDS_MeshNode* n2 = 0;
3779 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3780 while ( eIt->more() && !n2 )
3782 const SMDS_MeshElement* e = eIt->next();
3783 if ( !edgeSM->Contains(e)) continue;
3784 n2 = e->GetNode( 0 );
3785 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
3788 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3790 double uSrc = helper.GetNodeU( E, srcNode, n2 );
3791 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
3792 double u2 = helper.GetNodeU( E, n2, srcNode );
3794 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
3796 // tgtNode is located so that it does not make faces with wrong orientation
3799 edge._pos.resize(1);
3800 edge._pos[0].SetCoord( U_TGT, uTgt );
3801 edge._pos[0].SetCoord( U_SRC, uSrc );
3802 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
3804 edge._simplices.resize( 1 );
3805 edge._simplices[0]._nPrev = n2;
3807 // set UV of source node to target node
3808 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3809 pos->SetUParameter( uSrc );
3813 //================================================================================
3815 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
3817 //================================================================================
3819 // Compute UV to follow during shrinking
3821 // const SMDS_MeshNode* srcNode = edge._nodes[0];
3822 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
3824 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3825 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3826 // gp_Vec2d uvDir( srcUV, tgtUV );
3827 // double uvLen = uvDir.Magnitude();
3830 // // Select shrinking step such that not to make faces with wrong orientation.
3831 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3832 // const double minStepSize = uvLen / 20;
3833 // double stepSize = uvLen;
3834 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3835 // while ( fIt->more() )
3837 // const SMDS_MeshElement* f = fIt->next();
3838 // if ( !faceSubMesh->Contains( f )) continue;
3839 // const int nbNodes = f->NbCornerNodes();
3840 // for ( int i = 0; i < nbNodes; ++i )
3842 // const SMDS_MeshNode* n = f->GetNode(i);
3843 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
3845 // gp_XY uv = helper.GetNodeUV( F, n );
3846 // gp_Vec2d uvDirN( srcUV, uv );
3847 // double proj = uvDirN * uvDir;
3848 // if ( proj < stepSize && proj > minStepSize )
3854 // const int nbSteps = ceil( uvLen / stepSize );
3855 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
3856 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
3857 // edge._pos.resize( nbSteps );
3858 // edge._pos[0] = tgtUV0;
3859 // for ( int i = 1; i < nbSteps; ++i )
3861 // double r = i / double( nbSteps );
3862 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
3867 //================================================================================
3869 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
3871 //================================================================================
3873 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper)
3875 SMESH::Controls::AspectRatio qualifier;
3876 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
3877 const double maxAspectRatio = 4.;
3879 // find bad triangles
3881 vector< const SMDS_MeshElement* > badTrias;
3882 vector< double > badAspects;
3883 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
3884 SMDS_ElemIteratorPtr fIt = sm->GetElements();
3885 while ( fIt->more() )
3887 const SMDS_MeshElement * f = fIt->next();
3888 if ( f->NbCornerNodes() != 3 ) continue;
3889 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = SMESH_TNodeXYZ( f->GetNode(iP));
3890 double aspect = qualifier.GetValue( points );
3891 if ( aspect > maxAspectRatio )
3893 badTrias.push_back( f );
3894 badAspects.push_back( aspect );
3897 if ( badTrias.empty() )
3900 // find couples of faces to swap diagonal
3902 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
3903 vector< T2Trias > triaCouples;
3905 TIDSortedElemSet involvedFaces, emptySet;
3906 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
3909 double aspRatio [3];
3912 involvedFaces.insert( badTrias[iTia] );
3913 for ( int iP = 0; iP < 3; ++iP )
3914 points(iP+1) = SMESH_TNodeXYZ( badTrias[iTia]->GetNode(iP));
3916 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
3917 int bestCouple = -1;
3918 for ( int iSide = 0; iSide < 3; ++iSide )
3920 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
3921 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
3922 trias [iSide].first = badTrias[iTia];
3923 trias [iSide].second = SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, involvedFaces,
3925 if ( ! trias[iSide].second || trias[iSide].second->NbCornerNodes() != 3 )
3928 // aspect ratio of an adjacent tria
3929 for ( int iP = 0; iP < 3; ++iP )
3930 points2(iP+1) = SMESH_TNodeXYZ( trias[iSide].second->GetNode(iP));
3931 double aspectInit = qualifier.GetValue( points2 );
3933 // arrange nodes as after diag-swaping
3934 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
3935 i3 = helper.WrapIndex( i1-1, 3 );
3937 i3 = helper.WrapIndex( i1+1, 3 );
3939 points1( 1+ iSide ) = points2( 1+ i3 );
3940 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
3942 // aspect ratio after diag-swaping
3943 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
3944 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
3947 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
3951 if ( bestCouple >= 0 )
3953 triaCouples.push_back( trias[bestCouple] );
3954 involvedFaces.insert ( trias[bestCouple].second );
3958 involvedFaces.erase( badTrias[iTia] );
3961 if ( triaCouples.empty() )
3966 SMESH_MeshEditor editor( helper.GetMesh() );
3967 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
3968 for ( size_t i = 0; i < triaCouples.size(); ++i )
3970 dumpChangeNodes( triaCouples[i].first );
3971 dumpChangeNodes( triaCouples[i].second );
3972 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
3976 // just for debug dump resulting triangles
3977 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID());
3978 for ( size_t i = 0; i < triaCouples.size(); ++i )
3980 dumpChangeNodes( triaCouples[i].first );
3981 dumpChangeNodes( triaCouples[i].second );
3985 //================================================================================
3987 * \brief Move target node to it's final position on the FACE during shrinking
3989 //================================================================================
3991 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
3992 const TopoDS_Face& F,
3993 SMESH_MesherHelper& helper )
3996 return false; // already at the target position
3998 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
4000 if ( _sWOL.ShapeType() == TopAbs_FACE )
4002 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
4003 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y());
4004 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4005 const double uvLen = tgtUV.Distance( curUV );
4007 // Select shrinking step such that not to make faces with wrong orientation.
4008 const double kSafe = 0.8;
4009 const double minStepSize = uvLen / 10;
4010 double stepSize = uvLen;
4011 for ( unsigned i = 0; i < _simplices.size(); ++i )
4013 const SMDS_MeshNode* nn[2] = { _simplices[i]._nPrev, _simplices[i]._nNext };
4014 for ( int j = 0; j < 2; ++j )
4015 if ( const SMDS_MeshNode* n = nn[j] )
4017 gp_XY uv = helper.GetNodeUV( F, n );
4018 gp_Vec2d uvDirN( curUV, uv );
4019 double proj = uvDirN * uvDir * kSafe;
4020 if ( proj < stepSize && proj > minStepSize )
4026 if ( stepSize == uvLen )
4033 newUV = curUV + uvDir.XY() * stepSize;
4036 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4037 pos->SetUParameter( newUV.X() );
4038 pos->SetVParameter( newUV.Y() );
4041 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4042 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4043 dumpMove( tgtNode );
4046 else // _sWOL is TopAbs_EDGE
4048 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4049 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4051 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4052 const double uSrc = _pos[0].Coord( U_SRC );
4053 const double lenTgt = _pos[0].Coord( LEN_TGT );
4055 double newU = _pos[0].Coord( U_TGT );
4056 if ( lenTgt < 0.99 * fabs( uSrc-u2 ))
4062 newU = 0.1 * uSrc + 0.9 * u2;
4064 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4065 pos->SetUParameter( newU );
4067 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4068 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4069 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4070 dumpMove( tgtNode );
4076 //================================================================================
4078 * \brief Perform smooth on the FACE
4079 * \retval bool - true if the node has been moved
4081 //================================================================================
4083 bool _SmoothNode::Smooth(int& badNb,
4084 Handle(Geom_Surface)& surface,
4085 SMESH_MesherHelper& helper,
4086 const double refSign,
4090 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4092 // get uv of surrounding nodes
4093 vector<gp_XY> uv( _simplices.size() );
4094 for ( size_t i = 0; i < _simplices.size(); ++i )
4095 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4097 // compute new UV for the node
4099 if ( isCentroidal && _simplices.size() > 3 )
4101 // average centers of diagonals wieghted with their reciprocal lengths
4102 if ( _simplices.size() == 4 )
4104 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4105 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4106 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4110 double sumWeight = 0;
4111 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4112 for ( int i = 0; i < nb; ++i )
4115 int iTo = i + _simplices.size() - 1;
4116 for ( int j = iFrom; j < iTo; ++j )
4118 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4119 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4121 newPos += w * ( uv[i]+uv[i2] );
4124 newPos /= 2 * sumWeight;
4130 isCentroidal = false;
4131 for ( size_t i = 0; i < _simplices.size(); ++i )
4133 newPos /= _simplices.size();
4136 // count quality metrics (orientation) of triangles around the node
4138 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4139 for ( unsigned i = 0; i < _simplices.size(); ++i )
4140 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4143 for ( unsigned i = 0; i < _simplices.size(); ++i )
4144 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4146 if ( nbOkAfter < nbOkBefore )
4148 // if ( isCentroidal )
4149 // return Smooth( badNb, surface, helper, refSign, !isCentroidal, set3D );
4150 badNb += _simplices.size() - nbOkBefore;
4154 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4155 pos->SetUParameter( newPos.X() );
4156 pos->SetVParameter( newPos.Y() );
4163 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4164 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4168 badNb += _simplices.size() - nbOkAfter;
4169 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4172 //================================================================================
4174 * \brief Delete _SolidData
4176 //================================================================================
4178 _SolidData::~_SolidData()
4180 for ( unsigned i = 0; i < _edges.size(); ++i )
4182 if ( _edges[i] && _edges[i]->_2neibors )
4183 delete _edges[i]->_2neibors;
4188 //================================================================================
4190 * \brief Add a _LayerEdge inflated along the EDGE
4192 //================================================================================
4194 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4197 if ( _nodes.empty() )
4199 _edges[0] = _edges[1] = 0;
4203 if ( e == _edges[0] || e == _edges[1] )
4205 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4206 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4207 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4208 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4211 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4213 BRep_Tool::Range( E, f,l );
4214 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4215 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4219 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4220 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4222 if ( _nodes.empty() )
4224 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4225 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4227 TopLoc_Location loc;
4228 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4229 GeomAdaptor_Curve aCurve(C, f,l);
4230 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4232 int nbExpectNodes = eSubMesh->NbNodes();
4233 _initU .reserve( nbExpectNodes );
4234 _normPar.reserve( nbExpectNodes );
4235 _nodes .reserve( nbExpectNodes );
4236 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4237 while ( nIt->more() )
4239 const SMDS_MeshNode* node = nIt->next();
4240 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4241 node == tgtNode0 || node == tgtNode1 )
4242 continue; // refinement nodes
4243 _nodes.push_back( node );
4244 _initU.push_back( helper.GetNodeU( E, node ));
4245 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4246 _normPar.push_back( len / totLen );
4251 // remove target node of the _LayerEdge from _nodes
4253 for ( unsigned i = 0; i < _nodes.size(); ++i )
4254 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4255 _nodes[i] = 0, nbFound++;
4256 if ( nbFound == _nodes.size() )
4261 //================================================================================
4263 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4265 //================================================================================
4267 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4269 if ( _done || _nodes.empty())
4271 const _LayerEdge* e = _edges[0];
4272 if ( !e ) e = _edges[1];
4275 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4276 ( !_edges[1] || _edges[1]->_pos.empty() ));
4278 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4280 if ( set3D || _done )
4282 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4283 GeomAdaptor_Curve aCurve(C, f,l);
4286 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4288 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4289 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4291 for ( unsigned i = 0; i < _nodes.size(); ++i )
4293 if ( !_nodes[i] ) continue;
4294 double len = totLen * _normPar[i];
4295 GCPnts_AbscissaPoint discret( aCurve, len, f );
4296 if ( !discret.IsDone() )
4297 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4298 double u = discret.Parameter();
4299 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4300 pos->SetUParameter( u );
4301 gp_Pnt p = C->Value( u );
4302 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4307 BRep_Tool::Range( E, f,l );
4309 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4311 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4313 for ( unsigned i = 0; i < _nodes.size(); ++i )
4315 if ( !_nodes[i] ) continue;
4316 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4317 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4318 pos->SetUParameter( u );
4323 //================================================================================
4325 * \brief Restore initial parameters of nodes on EDGE
4327 //================================================================================
4329 void _Shrinker1D::RestoreParams()
4332 for ( unsigned i = 0; i < _nodes.size(); ++i )
4334 if ( !_nodes[i] ) continue;
4335 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4336 pos->SetUParameter( _initU[i] );
4341 //================================================================================
4343 * \brief Replace source nodes by target nodes in shrinked mesh edges
4345 //================================================================================
4347 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4349 const SMDS_MeshNode* nodes[3];
4350 for ( int i = 0; i < 2; ++i )
4352 if ( !_edges[i] ) continue;
4354 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4355 if ( !eSubMesh ) return;
4356 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4357 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4358 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4359 while ( eIt->more() )
4361 const SMDS_MeshElement* e = eIt->next();
4362 if ( !eSubMesh->Contains( e ))
4364 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4365 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4367 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4368 nodes[iN] = ( n == srcNode ? tgtNode : n );
4370 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4375 //================================================================================
4377 * \brief Creates 2D and 1D elements on boundaries of new prisms
4379 //================================================================================
4381 bool _ViscousBuilder::addBoundaryElements()
4383 SMESH_MesherHelper helper( *_mesh );
4385 for ( unsigned i = 0; i < _sdVec.size(); ++i )
4387 _SolidData& data = _sdVec[i];
4388 TopTools_IndexedMapOfShape geomEdges;
4389 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4390 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4392 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4394 // Get _LayerEdge's based on E
4396 map< double, const SMDS_MeshNode* > u2nodes;
4397 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4400 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
4401 TNode2Edge & n2eMap = data._n2eMap;
4402 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4404 //check if 2D elements are needed on E
4405 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
4406 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
4407 ledges.push_back( n2e->second );
4409 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
4410 continue; // no layers on E
4411 ledges.push_back( n2eMap[ u2n->second ]);
4413 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
4414 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
4415 int nbSharedPyram = 0;
4416 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
4417 while ( vIt->more() )
4419 const SMDS_MeshElement* v = vIt->next();
4420 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
4422 if ( nbSharedPyram > 1 )
4423 continue; // not free border of the pyramid
4425 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
4426 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
4427 continue; // faces already created
4429 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
4430 ledges.push_back( n2eMap[ u2n->second ]);
4432 // Find out orientation and type of face to create
4434 bool reverse = false, isOnFace;
4436 map< TGeomID, TopoDS_Shape >::iterator e2f =
4437 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
4439 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
4441 F = e2f->second.Oriented( TopAbs_FORWARD );
4442 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
4443 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
4444 reverse = !reverse, F.Reverse();
4445 if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face(F), getMeshDS() ))
4450 // find FACE with layers sharing E
4451 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
4452 while ( fIt->more() && F.IsNull() )
4454 const TopoDS_Shape* pF = fIt->next();
4455 if ( helper.IsSubShape( *pF, data._solid) &&
4456 !_ignoreShapeIds.count( e2f->first ))
4460 // Find the sub-mesh to add new faces
4461 SMESHDS_SubMesh* sm = 0;
4463 sm = getMeshDS()->MeshElements( F );
4465 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
4467 return error("error in addBoundaryElements()", data._index);
4470 const int dj1 = reverse ? 0 : 1;
4471 const int dj2 = reverse ? 1 : 0;
4472 for ( unsigned j = 1; j < ledges.size(); ++j )
4474 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
4475 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
4477 for ( size_t z = 1; z < nn1.size(); ++z )
4478 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
4480 for ( size_t z = 1; z < nn1.size(); ++z )
4481 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
4485 for ( int isFirst = 0; isFirst < 2; ++isFirst )
4487 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
4488 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
4490 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
4491 if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
4493 helper.SetSubShape( edge->_sWOL );
4494 helper.SetElementsOnShape( true );
4495 for ( size_t z = 1; z < nn.size(); ++z )
4496 helper.AddEdge( nn[z-1], nn[z] );