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 _ShrinkShapeListener : SMESH_subMeshEventListener
126 _ShrinkShapeListener()
127 : SMESH_subMeshEventListener(/*isDeletable=*/false,
128 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
130 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener 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);
143 //--------------------------------------------------------------------------------
145 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
146 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
147 * delete the data as soon as it has been used
149 class _ViscousListener : SMESH_subMeshEventListener
152 SMESH_subMeshEventListener(/*isDeletable=*/false,
153 "StdMeshers_ViscousLayers::_ViscousListener") {}
154 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
156 virtual void ProcessEvent(const int event,
158 SMESH_subMesh* subMesh,
159 SMESH_subMeshEventListenerData* data,
160 const SMESH_Hypothesis* hyp)
162 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
164 // delete SMESH_ProxyMesh containing temporary faces
165 subMesh->DeleteEventListener( this );
168 // Finds or creates proxy mesh of the solid
169 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
170 const TopoDS_Shape& solid,
173 if ( !mesh ) return 0;
174 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
175 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
176 if ( !data && toCreate )
178 data = new _MeshOfSolid(mesh);
179 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
180 sm->SetEventListener( Get(), data, sm );
184 // Removes proxy mesh of the solid
185 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
187 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
191 //================================================================================
193 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
194 * the main shape when sub-mesh of the main shape is cleared,
195 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
198 //================================================================================
200 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
202 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
203 SMESH_subMeshEventListenerData* data =
204 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
207 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
208 data->mySubMeshes.end())
209 data->mySubMeshes.push_back( sub );
213 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
214 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
217 //--------------------------------------------------------------------------------
219 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
220 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
221 * The class is used to check validity of face or volumes around a smoothed node;
222 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
226 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
227 _Simplex(const SMDS_MeshNode* nPrev=0, const SMDS_MeshNode* nNext=0)
228 : _nPrev(nPrev), _nNext(nNext) {}
229 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
231 const double M[3][3] =
232 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
233 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
234 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
235 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
236 + M[0][1]*M[1][2]*M[2][0]
237 + M[0][2]*M[1][0]*M[2][1]
238 - M[0][0]*M[1][2]*M[2][1]
239 - M[0][1]*M[1][0]*M[2][2]
240 - M[0][2]*M[1][1]*M[2][0]);
241 return determinant > 1e-100;
243 bool IsForward(const gp_XY& tgtUV,
244 const SMDS_MeshNode* smoothedNode,
245 const TopoDS_Face& face,
246 SMESH_MesherHelper& helper,
247 const double refSign) const
249 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
250 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
251 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
253 return d*refSign > 1e-100;
255 bool IsNeighbour(const _Simplex& other) const
257 return _nPrev == other._nNext || _nNext == other._nPrev;
260 //--------------------------------------------------------------------------------
262 * Structure used to take into account surface curvature while smoothing
267 double _k; // factor to correct node smoothed position
269 static _Curvature* New( double avgNormProj, double avgDist )
272 if ( fabs( avgNormProj / avgDist ) > 1./200 )
275 c->_r = avgDist * avgDist / avgNormProj;
276 c->_k = avgDist * avgDist / c->_r / c->_r;
277 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
281 double lenDelta(double len) const { return _k * ( _r + len ); }
284 //--------------------------------------------------------------------------------
286 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
290 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
291 const SMDS_MeshNode* _nodes[2];
292 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
294 double _wgt[2]; // weights of _nodes
295 _LayerEdge* _edges[2];
297 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
300 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
302 std::swap( _nodes[0], _nodes[1] );
303 std::swap( _wgt[0], _wgt[1] );
306 //--------------------------------------------------------------------------------
308 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
309 * and a node of the most internal layer (_nodes.back())
313 vector< const SMDS_MeshNode*> _nodes;
315 gp_XYZ _normal; // to solid surface
316 vector<gp_XYZ> _pos; // points computed during inflation
317 double _len; // length achived with the last step
318 double _cosin; // of angle (_normal ^ surface)
319 double _lenFactor; // to compute _len taking _cosin into account
321 // face or edge w/o layer along or near which _LayerEdge is inflated
323 // simplices connected to the source node (_nodes[0]);
324 // used for smoothing and quality check of _LayerEdge's based on the FACE
325 vector<_Simplex> _simplices;
326 // data for smoothing of _LayerEdge's based on the EDGE
327 _2NearEdges* _2neibors;
329 _Curvature* _curvature;
330 // TODO:: detele _Curvature, _plnNorm
332 void SetNewLength( double len, SMESH_MesherHelper& helper );
333 bool SetNewLength2d( Handle(Geom_Surface)& surface,
334 const TopoDS_Face& F,
335 SMESH_MesherHelper& helper );
336 void SetDataByNeighbors( const SMDS_MeshNode* n1,
337 const SMDS_MeshNode* n2,
338 SMESH_MesherHelper& helper);
339 void InvalidateStep( int curStep );
340 bool Smooth(int& badNb);
341 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
342 const TopoDS_Face& F,
343 SMESH_MesherHelper& helper);
344 bool FindIntersection( SMESH_ElementSearcher& searcher,
346 const double& epsilon,
347 const SMDS_MeshElement** face = 0);
348 bool SegTriaInter( const gp_Ax1& lastSegment,
349 const SMDS_MeshNode* n0,
350 const SMDS_MeshNode* n1,
351 const SMDS_MeshNode* n2,
353 const double& epsilon) const;
354 gp_Ax1 LastSegment(double& segLen) const;
355 bool IsOnEdge() const { return _2neibors; }
356 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
357 void SetCosin( double cosin );
361 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
363 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
364 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
367 //--------------------------------------------------------------------------------
369 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
371 //--------------------------------------------------------------------------------
373 * \brief Data of a SOLID
378 const StdMeshers_ViscousLayers* _hyp;
379 _MeshOfSolid* _proxyMesh;
380 set<TGeomID> _reversedFaceIds;
382 double _stepSize, _stepSizeCoeff;
383 const SMDS_MeshNode* _stepSizeNodes[2];
386 // edges of _n2eMap. We keep same data in two containers because
387 // iteration over the map is 5 time longer than over the vector
388 vector< _LayerEdge* > _edges;
390 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
391 // layers and a FACE w/o layers
392 // value: the shape (FACE or EDGE) to shrink mesh on.
393 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
394 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
396 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
397 set< TGeomID > _noShrinkFaces;
399 // <EDGE to smooth on> to <it's curve>
400 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
402 // end indices in _edges of _LayerEdge on one shape to smooth
403 vector< int > _endEdgeToSmooth;
405 double _epsilon; // precision for SegTriaInter()
407 int _index; // for debug
409 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
410 const StdMeshers_ViscousLayers* h=0,
411 _MeshOfSolid* m=0) :_solid(s), _hyp(h), _proxyMesh(m) {}
414 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
417 Handle(Geom_Surface)& surface,
418 const TopoDS_Face& F,
419 SMESH_MesherHelper& helper);
421 //--------------------------------------------------------------------------------
423 * \brief Data of node on a shrinked FACE
427 const SMDS_MeshNode* _node;
428 //vector<const SMDS_MeshNode*> _nodesAround;
429 vector<_Simplex> _simplices; // for quality check
431 bool Smooth(int& badNb,
432 Handle(Geom_Surface)& surface,
433 SMESH_MesherHelper& helper,
434 const double refSign,
438 //--------------------------------------------------------------------------------
440 * \brief Builder of viscous layers
442 class _ViscousBuilder
447 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
448 const TopoDS_Shape& shape);
450 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
451 void RestoreListeners();
453 // computes SMESH_ProxyMesh::SubMesh::_n2n;
454 bool MakeN2NMap( _MeshOfSolid* pm );
458 bool findSolidsWithLayers();
459 bool findFacesWithLayers();
460 bool makeLayer(_SolidData& data);
461 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
462 SMESH_MesherHelper& helper, _SolidData& data);
463 bool findNeiborsOnEdge(const _LayerEdge* edge,
464 const SMDS_MeshNode*& n1,
465 const SMDS_MeshNode*& n2,
467 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
468 const set<TGeomID>& ingnoreShapes,
469 const _SolidData* dataToCheckOri = 0,
470 const bool toSort = false);
471 bool sortEdges( _SolidData& data,
472 vector< vector<_LayerEdge*> >& edgesByGeom);
473 void limitStepSize( _SolidData& data,
474 const SMDS_MeshElement* face,
476 void limitStepSize( _SolidData& data, const double minSize);
477 bool inflate(_SolidData& data);
478 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
479 bool smoothAnalyticEdge( _SolidData& data,
482 Handle(Geom_Surface)& surface,
483 const TopoDS_Face& F,
484 SMESH_MesherHelper& helper);
485 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
486 bool refine(_SolidData& data);
488 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
489 SMESH_MesherHelper& helper,
490 const SMESHDS_SubMesh* faceSubMesh );
491 void fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper);
492 bool addBoundaryElements();
494 bool error( const string& text, int solidID=-1 );
495 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
498 void makeGroupOfLE();
501 SMESH_ComputeErrorPtr _error;
503 vector< _SolidData > _sdVec;
504 set<TGeomID> _ignoreShapeIds;
507 //--------------------------------------------------------------------------------
509 * \brief Shrinker of nodes on the EDGE
513 vector<double> _initU;
514 vector<double> _normPar;
515 vector<const SMDS_MeshNode*> _nodes;
516 const _LayerEdge* _edges[2];
519 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
520 void Compute(bool set3D, SMESH_MesherHelper& helper);
521 void RestoreParams();
522 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
524 //--------------------------------------------------------------------------------
526 * \brief Class of temporary mesh face.
527 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
528 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
530 struct TmpMeshFace : public SMDS_MeshElement
532 vector<const SMDS_MeshNode* > _nn;
533 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
534 SMDS_MeshElement(id), _nn(nodes) {}
535 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
536 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
537 virtual vtkIdType GetVtkType() const { return -1; }
538 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
539 virtual SMDSAbs_GeometryType GetGeomType() const { return SMDSGeom_TRIANGLE; }
540 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const
541 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
543 //--------------------------------------------------------------------------------
545 * \brief Class of temporary mesh face storing _LayerEdge it's based on
547 struct TmpMeshFaceOnEdge : public TmpMeshFace
549 _LayerEdge *_le1, *_le2;
550 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
551 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
553 _nn[0]=_le1->_nodes[0];
554 _nn[1]=_le1->_nodes.back();
555 _nn[2]=_le2->_nodes.back();
556 _nn[3]=_le2->_nodes[0];
559 } // namespace VISCOUS_3D
561 //================================================================================
562 // StdMeshers_ViscousLayers hypothesis
564 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
565 :SMESH_Hypothesis(hypId, studyId, gen),
566 _nbLayers(1), _thickness(1), _stretchFactor(1)
568 _name = StdMeshers_ViscousLayers::GetHypType();
569 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
570 } // --------------------------------------------------------------------------------
571 void StdMeshers_ViscousLayers::SetBndShapesToIgnore(const std::vector<int>& faceIds)
573 if ( faceIds != _ignoreBndShapeIds )
574 _ignoreBndShapeIds = faceIds, NotifySubMeshesHypothesisModification();
575 } // --------------------------------------------------------------------------------
576 bool StdMeshers_ViscousLayers::IsIgnoredShape(const int shapeID) const
578 return ( find( _ignoreBndShapeIds.begin(), _ignoreBndShapeIds.end(), shapeID )
579 != _ignoreBndShapeIds.end() );
580 } // --------------------------------------------------------------------------------
581 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
583 if ( thickness != _thickness )
584 _thickness = thickness, NotifySubMeshesHypothesisModification();
585 } // --------------------------------------------------------------------------------
586 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
588 if ( _nbLayers != nb )
589 _nbLayers = nb, NotifySubMeshesHypothesisModification();
590 } // --------------------------------------------------------------------------------
591 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
593 if ( _stretchFactor != factor )
594 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
595 } // --------------------------------------------------------------------------------
597 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
598 const TopoDS_Shape& theShape,
599 const bool toMakeN2NMap) const
601 using namespace VISCOUS_3D;
602 _ViscousBuilder bulder;
603 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
604 if ( err && !err->IsOK() )
605 return SMESH_ProxyMesh::Ptr();
607 vector<SMESH_ProxyMesh::Ptr> components;
608 TopExp_Explorer exp( theShape, TopAbs_SOLID );
609 for ( ; exp.More(); exp.Next() )
611 if ( _MeshOfSolid* pm =
612 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
614 if ( toMakeN2NMap && !pm->_n2nMapComputed )
615 if ( !bulder.MakeN2NMap( pm ))
616 return SMESH_ProxyMesh::Ptr();
617 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
618 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
620 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
622 switch ( components.size() )
626 case 1: return components[0];
628 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
630 return SMESH_ProxyMesh::Ptr();
631 } // --------------------------------------------------------------------------------
632 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
634 save << " " << _nbLayers
636 << " " << _stretchFactor
637 << " " << _ignoreBndShapeIds.size();
638 for ( unsigned i = 0; i < _ignoreBndShapeIds.size(); ++i )
639 save << " " << _ignoreBndShapeIds[i];
641 } // --------------------------------------------------------------------------------
642 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
645 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
646 while ( _ignoreBndShapeIds.size() < nbFaces && load >> faceID )
647 _ignoreBndShapeIds.push_back( faceID );
649 } // --------------------------------------------------------------------------------
650 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
651 const TopoDS_Shape& theShape)
656 // END StdMeshers_ViscousLayers hypothesis
657 //================================================================================
661 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
665 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
666 gp_Pnt p = BRep_Tool::Pnt( fromV );
667 double distF = p.SquareDistance( c->Value( f ));
668 double distL = p.SquareDistance( c->Value( l ));
669 c->D1(( distF < distL ? f : l), p, dir );
670 if ( distL < distF ) dir.Reverse();
673 //--------------------------------------------------------------------------------
674 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
675 SMESH_MesherHelper& helper)
678 double f,l; gp_Pnt p;
679 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
680 double u = helper.GetNodeU( E, atNode );
684 //--------------------------------------------------------------------------------
685 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
686 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
688 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
689 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
690 gp_Pnt p; gp_Vec du, dv, norm;
691 surface->D1( uv.X(),uv.Y(), p, du,dv );
695 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
696 double u = helper.GetNodeU( fromE, node, 0, &ok );
698 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
699 if ( o == TopAbs_REVERSED )
702 gp_Vec dir = norm ^ du;
704 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
705 helper.IsClosedEdge( fromE ))
707 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
708 else c->D1( f, p, dv );
709 if ( o == TopAbs_REVERSED )
711 gp_Vec dir2 = norm ^ dv;
712 dir = dir.Normalized() + dir2.Normalized();
716 //--------------------------------------------------------------------------------
717 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
718 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
719 bool& ok, double* cosin=0)
721 double f,l; TopLoc_Location loc;
722 vector< TopoDS_Edge > edges; // sharing a vertex
723 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
726 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
727 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
728 edges.push_back( *e );
731 if ( !( ok = ( edges.size() > 0 ))) return dir;
732 // get average dir of edges going fromV
734 for ( unsigned i = 0; i < edges.size(); ++i )
736 edgeDir = getEdgeDir( edges[i], fromV );
737 double size2 = edgeDir.SquareMagnitude();
738 if ( size2 > numeric_limits<double>::min() )
739 edgeDir /= sqrt( size2 );
742 dir += edgeDir.XYZ();
744 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
745 if ( edges.size() == 1 || dir.SquareModulus() < 1e-10)
747 else if ( dir * fromEdgeDir < 0 )
751 //dir /= edges.size();
753 double angle = edgeDir.Angle( dir );
754 *cosin = cos( angle );
759 //================================================================================
761 * \brief Returns true if a FACE is bound by a concave EDGE
763 //================================================================================
765 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
769 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
770 for ( ; eExp.More(); eExp.Next() )
772 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
773 if ( BRep_Tool::Degenerated( E )) continue;
774 // check if 2D curve is concave
775 BRepAdaptor_Curve2d curve( E, F );
776 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
777 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
778 curve.Intervals( intervals, GeomAbs_C2 );
779 bool isConvex = true;
780 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
782 double u1 = intervals( i );
783 double u2 = intervals( i+1 );
784 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
785 double cross = drv2 ^ drv1;
786 if ( E.Orientation() == TopAbs_REVERSED )
788 isConvex = ( cross < 1e-9 );
790 // check if concavity is strong enough to care about it
791 //const double maxAngle = 5 * Standard_PI180;
794 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
796 // map< double, const SMDS_MeshNode* > u2nodes;
797 // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
798 // /*ignoreMedium=*/true, u2nodes))
800 // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
801 // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
802 // double uPrev = u2n->first;
803 // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
805 // gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
806 // gp_Vec2d segmentDir( uvPrev, uv );
807 // curve.D1( uPrev, p, drv1 );
809 // if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
814 // uPrev = u2n->first;
820 //--------------------------------------------------------------------------------
821 // DEBUG. Dump intermediate node positions into a python script
826 const char* fname = "/tmp/viscous.py";
827 cout << "execfile('"<<fname<<"')"<<endl;
828 py = new ofstream(fname);
829 *py << "from smesh import *" << endl
830 << "meshSO = GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
831 << "mesh = Mesh( meshSO.GetObject() )"<<endl;
835 *py << "mesh.MakeGroup('Viscous Prisms',VOLUME,FT_ElemGeomType,'=',Geom_PENTA)"<<endl;
838 ~PyDump() { Finish(); }
840 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
841 #define dumpMove(n) { _dumpMove(n, __LINE__);}
842 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
843 void _dumpFunction(const string& fun, int ln)
844 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
845 void _dumpMove(const SMDS_MeshNode* n, int ln)
846 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
847 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
848 void _dumpCmd(const string& txt, int ln)
849 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
850 void dumpFunctionEnd()
851 { if (py) *py<< " return"<< endl; }
852 void dumpChangeNodes( const SMDS_MeshElement* f )
853 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
854 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
855 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
857 struct PyDump { void Finish() {} };
858 #define dumpFunction(f) f
861 #define dumpFunctionEnd()
862 #define dumpChangeNodes(f)
866 using namespace VISCOUS_3D;
868 //================================================================================
870 * \brief Constructor of _ViscousBuilder
872 //================================================================================
874 _ViscousBuilder::_ViscousBuilder()
876 _error = SMESH_ComputeError::New(COMPERR_OK);
880 //================================================================================
882 * \brief Stores error description and returns false
884 //================================================================================
886 bool _ViscousBuilder::error(const string& text, int solidId )
888 _error->myName = COMPERR_ALGO_FAILED;
889 _error->myComment = string("Viscous layers builder: ") + text;
892 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
893 if ( !sm && !_sdVec.empty() )
894 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
895 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
897 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
898 if ( smError && smError->myAlgo )
899 _error->myAlgo = smError->myAlgo;
903 makeGroupOfLE(); // debug
908 //================================================================================
910 * \brief At study restoration, restore event listeners used to clear an inferior
911 * dim sub-mesh modified by viscous layers
913 //================================================================================
915 void _ViscousBuilder::RestoreListeners()
920 //================================================================================
922 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
924 //================================================================================
926 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
928 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
929 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
930 for ( ; fExp.More(); fExp.Next() )
932 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
933 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
935 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
937 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
940 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
941 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
943 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
944 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
945 while( prxIt->more() )
947 const SMDS_MeshElement* fSrc = srcIt->next();
948 const SMDS_MeshElement* fPrx = prxIt->next();
949 if ( fSrc->NbNodes() != fPrx->NbNodes())
950 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
951 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
952 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
955 pm->_n2nMapComputed = true;
959 //================================================================================
961 * \brief Does its job
963 //================================================================================
965 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
966 const TopoDS_Shape& theShape)
968 // TODO: set priority of solids during Gen::Compute()
972 // check if proxy mesh already computed
973 TopExp_Explorer exp( theShape, TopAbs_SOLID );
975 return error("No SOLID's in theShape"), _error;
977 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
978 return SMESH_ComputeErrorPtr(); // everything already computed
982 // TODO: ignore already computed SOLIDs
983 if ( !findSolidsWithLayers())
986 if ( !findFacesWithLayers() )
989 for ( unsigned i = 0; i < _sdVec.size(); ++i )
991 if ( ! makeLayer(_sdVec[i]) )
994 if ( _sdVec[i]._edges.size() == 0 )
997 if ( ! inflate(_sdVec[i]) )
1000 if ( ! refine(_sdVec[i]) )
1006 addBoundaryElements();
1008 makeGroupOfLE(); // debug
1014 //================================================================================
1016 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1018 //================================================================================
1020 bool _ViscousBuilder::findSolidsWithLayers()
1023 TopTools_IndexedMapOfShape allSolids;
1024 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1025 _sdVec.reserve( allSolids.Extent());
1027 SMESH_Gen* gen = _mesh->GetGen();
1028 for ( int i = 1; i <= allSolids.Extent(); ++i )
1030 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1031 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1032 if ( !algo ) continue;
1033 // TODO: check if algo is hidden
1034 const list <const SMESHDS_Hypothesis *> & allHyps =
1035 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1036 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1037 const StdMeshers_ViscousLayers* viscHyp = 0;
1038 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1039 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1042 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1045 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, proxyMesh ));
1046 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1049 if ( _sdVec.empty() )
1051 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1056 //================================================================================
1060 //================================================================================
1062 bool _ViscousBuilder::findFacesWithLayers()
1064 // collect all faces to ignore defined by hyp
1065 vector<TopoDS_Shape> ignoreFaces;
1066 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1068 vector<TGeomID> ids = _sdVec[i]._hyp->GetBndShapesToIgnore();
1069 for ( unsigned i = 0; i < ids.size(); ++i )
1071 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
1072 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1074 _ignoreShapeIds.insert( ids[i] );
1075 ignoreFaces.push_back( s );
1080 // ignore internal faces
1081 SMESH_MesherHelper helper( *_mesh );
1082 TopExp_Explorer exp;
1083 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1085 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1086 for ( ; exp.More(); exp.Next() )
1088 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1089 if ( helper.NbAncestors( exp.Current(), *_mesh, TopAbs_SOLID ) > 1 )
1091 _ignoreShapeIds.insert( faceInd );
1092 ignoreFaces.push_back( exp.Current() );
1093 if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face( exp.Current() ), getMeshDS()))
1094 _sdVec[i]._reversedFaceIds.insert( faceInd );
1099 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1100 TopTools_IndexedMapOfShape shapes;
1101 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1104 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1105 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1107 const TopoDS_Shape& edge = shapes(iE);
1108 // find 2 faces sharing an edge
1110 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1111 while ( fIt->more())
1113 const TopoDS_Shape* f = fIt->next();
1114 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1115 FF[ int( !FF[0].IsNull()) ] = *f;
1117 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1118 // check presence of layers on them
1120 for ( int j = 0; j < 2; ++j )
1121 ignore[j] = _ignoreShapeIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1122 if ( ignore[0] == ignore[1] ) continue; // nothing interesting
1123 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1125 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1126 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1129 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1130 // the algo of the SOLID sharing the FACE does not support it
1131 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1132 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1134 TopTools_MapOfShape noShrinkVertices;
1135 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1136 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1138 const TopoDS_Shape& fWOL = e2f->second;
1139 TGeomID edgeID = e2f->first;
1140 bool notShrinkFace = false;
1141 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1142 while ( soIt->more())
1144 const TopoDS_Shape* solid = soIt->next();
1145 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1146 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1147 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1148 notShrinkFace = true;
1149 for ( unsigned j = 0; j < _sdVec.size(); ++j )
1151 if ( _sdVec[j]._solid.IsSame( *solid ) )
1152 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1153 notShrinkFace = false;
1156 if ( notShrinkFace )
1158 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1159 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1160 noShrinkVertices.Add( vExp.Current() );
1163 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1164 // to the found not shrinked fWOL's
1165 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1166 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1168 TGeomID edgeID = e2f->first;
1169 TopoDS_Vertex VV[2];
1170 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1171 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1173 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1174 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1183 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1185 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1188 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1189 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1191 const TopoDS_Shape& vertex = shapes(iV);
1192 // find faces WOL sharing the vertex
1193 vector< TopoDS_Shape > facesWOL;
1194 int totalNbFaces = 0;
1195 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1196 while ( fIt->more())
1198 const TopoDS_Shape* f = fIt->next();
1199 const int fID = getMeshDS()->ShapeToIndex( *f );
1200 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1203 if ( _ignoreShapeIds.count ( fID ) && ! _sdVec[i]._noShrinkFaces.count( fID ))
1204 facesWOL.push_back( *f );
1207 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1208 continue; // no layers at this vertex or no WOL
1209 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1210 switch ( facesWOL.size() )
1214 helper.SetSubShape( facesWOL[0] );
1215 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1217 TopoDS_Shape seamEdge;
1218 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1219 while ( eIt->more() && seamEdge.IsNull() )
1221 const TopoDS_Shape* e = eIt->next();
1222 if ( helper.IsRealSeam( *e ) )
1225 if ( !seamEdge.IsNull() )
1227 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1231 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1236 // find an edge shared by 2 faces
1237 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1238 while ( eIt->more())
1240 const TopoDS_Shape* e = eIt->next();
1241 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1242 helper.IsSubShape( *e, facesWOL[1]))
1244 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1250 return error("Not yet supported case", _sdVec[i]._index);
1258 //================================================================================
1260 * \brief Create the inner surface of the viscous layer and prepare data for infation
1262 //================================================================================
1264 bool _ViscousBuilder::makeLayer(_SolidData& data)
1266 // get all sub-shapes to make layers on
1267 set<TGeomID> subIds, faceIds;
1268 subIds = data._noShrinkFaces;
1269 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1270 for ( ; exp.More(); exp.Next() )
1271 if ( ! _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1273 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1274 faceIds.insert( fSubM->GetId() );
1275 SMESH_subMeshIteratorPtr subIt =
1276 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1277 while ( subIt->more() )
1278 subIds.insert( subIt->next()->GetId() );
1281 // make a map to find new nodes on sub-shapes shared with other SOLID
1282 map< TGeomID, TNode2Edge* > s2neMap;
1283 map< TGeomID, TNode2Edge* >::iterator s2ne;
1284 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1285 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1287 TGeomID shapeInd = s2s->first;
1288 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1290 if ( _sdVec[i]._index == data._index ) continue;
1291 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1292 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1293 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1295 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1301 // Create temporary faces and _LayerEdge's
1303 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1305 data._stepSize = Precision::Infinite();
1306 data._stepSizeNodes[0] = 0;
1308 SMESH_MesherHelper helper( *_mesh );
1309 helper.SetSubShape( data._solid );
1310 helper.SetElementsOnShape(true);
1312 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1313 TNode2Edge::iterator n2e2;
1315 // collect _LayerEdge's of shapes they are based on
1316 const int nbShapes = getMeshDS()->MaxShapeIndex();
1317 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1319 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1321 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1322 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1324 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1325 SMESH_ProxyMesh::SubMesh* proxySub =
1326 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1328 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1329 while ( eIt->more() )
1331 const SMDS_MeshElement* face = eIt->next();
1332 newNodes.resize( face->NbCornerNodes() );
1333 double faceMaxCosin = -1;
1334 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1336 const SMDS_MeshNode* n = face->GetNode(i);
1337 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1338 if ( !(*n2e).second )
1341 _LayerEdge* edge = new _LayerEdge();
1343 edge->_nodes.push_back( n );
1344 const int shapeID = n->getshapeId();
1345 edgesByGeom[ shapeID ].push_back( edge );
1347 // set edge data or find already refined _LayerEdge and get data from it
1348 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1349 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1350 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1352 _LayerEdge* foundEdge = (*n2e2).second;
1353 edge->Copy( *foundEdge, helper );
1354 // location of the last node is modified but we can restore
1355 // it by node position on _sWOL stored by the node
1356 const_cast< SMDS_MeshNode* >
1357 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1361 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1362 if ( !setEdgeData( *edge, subIds, helper, data ))
1365 dumpMove(edge->_nodes.back());
1366 if ( edge->_cosin > 0.01 )
1368 if ( edge->_cosin > faceMaxCosin )
1369 faceMaxCosin = edge->_cosin;
1372 newNodes[ i ] = n2e->second->_nodes.back();
1374 // create a temporary face
1375 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1376 proxySub->AddElement( newFace );
1378 // compute inflation step size by min size of element on a convex surface
1379 if ( faceMaxCosin > 0.1 )
1380 limitStepSize( data, face, faceMaxCosin );
1381 } // loop on 2D elements on a FACE
1382 } // loop on FACEs of a SOLID
1384 data._epsilon = 1e-7;
1385 if ( data._stepSize < 1. )
1386 data._epsilon *= data._stepSize;
1388 // Put _LayerEdge's into a vector
1390 if ( !sortEdges( data, edgesByGeom ))
1393 // Set target nodes into _Simplex and _2NearEdges
1394 TNode2Edge::iterator n2e;
1395 for ( unsigned i = 0; i < data._edges.size(); ++i )
1397 if ( data._edges[i]->IsOnEdge())
1398 for ( int j = 0; j < 2; ++j )
1400 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1401 break; // _LayerEdge is shared by two _SolidData's
1402 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1403 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1404 return error("_LayerEdge not found by src node", data._index);
1405 n = (*n2e).second->_nodes.back();
1406 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1409 for ( unsigned j = 0; j < data._edges[i]->_simplices.size(); ++j )
1411 _Simplex& s = data._edges[i]->_simplices[j];
1412 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1413 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1421 //================================================================================
1423 * \brief Compute inflation step size by min size of element on a convex surface
1425 //================================================================================
1427 void _ViscousBuilder::limitStepSize( _SolidData& data,
1428 const SMDS_MeshElement* face,
1432 double minSize = 10 * data._stepSize;
1433 const int nbNodes = face->NbCornerNodes();
1434 for ( int i = 0; i < nbNodes; ++i )
1436 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1437 const SMDS_MeshNode* curN = face->GetNode( i );
1438 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1439 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1441 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1442 if ( dist < minSize )
1443 minSize = dist, iN = i;
1446 double newStep = 0.8 * minSize / cosin;
1447 if ( newStep < data._stepSize )
1449 data._stepSize = newStep;
1450 data._stepSizeCoeff = 0.8 / cosin;
1451 data._stepSizeNodes[0] = face->GetNode( iN );
1452 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1456 //================================================================================
1458 * \brief Compute inflation step size by min size of element on a convex surface
1460 //================================================================================
1462 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1464 if ( minSize < data._stepSize )
1466 data._stepSize = minSize;
1467 if ( data._stepSizeNodes[0] )
1470 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1471 data._stepSizeCoeff = data._stepSize / dist;
1476 //================================================================================
1478 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1480 //================================================================================
1482 bool _ViscousBuilder::sortEdges( _SolidData& data,
1483 vector< vector<_LayerEdge*> >& edgesByGeom)
1485 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1486 // boundry inclined at a sharp angle to the shape
1488 list< TGeomID > shapesToSmooth;
1490 SMESH_MesherHelper helper( *_mesh );
1493 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1495 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1496 if ( eS.empty() ) continue;
1497 TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1498 bool needSmooth = false;
1499 switch ( S.ShapeType() )
1503 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1504 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1506 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1507 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1508 if ( eV.empty() ) continue;
1509 double cosin = eV[0]->_cosin;
1511 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1515 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1516 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1518 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1519 eV[0]->_nodes[0], helper, ok);
1520 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1521 double angle = dir1.Angle( dir2 );
1522 cosin = cos( angle );
1524 needSmooth = ( cosin > 0.1 );
1530 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1532 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1533 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1534 if ( eE.empty() ) continue;
1535 if ( eE[0]->_sWOL.IsNull() )
1537 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1538 needSmooth = ( eE[i]->_cosin > 0.1 );
1542 const TopoDS_Face& F1 = TopoDS::Face( S );
1543 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1544 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1545 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1547 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1548 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1549 double angle = dir1.Angle( dir2 );
1550 double cosin = cos( angle );
1551 needSmooth = ( cosin > 0.1 );
1563 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1564 else shapesToSmooth.push_back ( iS );
1567 } // loop on edgesByGeom
1569 data._edges.reserve( data._n2eMap.size() );
1570 data._endEdgeToSmooth.clear();
1572 // first we put _LayerEdge's on shapes to smooth
1573 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1574 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1576 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1577 if ( eVec.empty() ) continue;
1578 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1579 data._endEdgeToSmooth.push_back( data._edges.size() );
1583 // then the rest _LayerEdge's
1584 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1586 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1587 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1594 //================================================================================
1596 * \brief Set data of _LayerEdge needed for smoothing
1597 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1599 //================================================================================
1601 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1602 const set<TGeomID>& subIds,
1603 SMESH_MesherHelper& helper,
1606 SMESH_MeshEditor editor(_mesh);
1608 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1609 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1613 edge._curvature = 0;
1615 // --------------------------
1616 // Compute _normal and _cosin
1617 // --------------------------
1620 edge._normal.SetCoord(0,0,0);
1622 int totalNbFaces = 0;
1624 gp_Vec du, dv, geomNorm;
1627 TGeomID shapeInd = node->getshapeId();
1628 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1629 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1630 TopoDS_Shape vertEdge;
1632 if ( onShrinkShape ) // one of faces the node is on has no layers
1634 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1635 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1637 // inflate from VERTEX along EDGE
1638 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1640 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1642 // inflate from VERTEX along FACE
1643 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1644 node, helper, normOK, &edge._cosin);
1648 // inflate from EDGE along FACE
1649 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1650 node, helper, normOK);
1653 else // layers are on all faces of SOLID the node is on
1655 // find indices of geom faces the node lies on
1656 set<TGeomID> faceIds;
1657 if ( posType == SMDS_TOP_FACE )
1659 faceIds.insert( node->getshapeId() );
1663 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1664 while ( fIt->more() )
1665 faceIds.insert( editor.FindShape(fIt->next()));
1668 set<TGeomID>::iterator id = faceIds.begin();
1670 for ( ; id != faceIds.end(); ++id )
1672 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1673 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1676 //nbLayerFaces += subIds.count( *id );
1677 F = TopoDS::Face( s );
1679 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1680 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1681 surface->D1( uv.X(),uv.Y(), p, du,dv );
1683 double size2 = geomNorm.SquareMagnitude();
1684 if ( size2 > numeric_limits<double>::min() )
1685 geomNorm /= sqrt( size2 );
1688 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1690 edge._normal += geomNorm.XYZ();
1692 if ( totalNbFaces == 0 )
1693 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1695 edge._normal /= totalNbFaces;
1700 edge._cosin = 0; break;
1702 case SMDS_TOP_EDGE: {
1703 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1704 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1705 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1706 edge._cosin = cos( angle );
1707 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1710 case SMDS_TOP_VERTEX: {
1711 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1712 gp_Vec inFaceDir = getFaceDir( F, V, node, helper, normOK);
1713 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1714 edge._cosin = cos( angle );
1715 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1719 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1723 double normSize = edge._normal.SquareModulus();
1724 if ( normSize < numeric_limits<double>::min() )
1725 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1727 edge._normal /= sqrt( normSize );
1729 // TODO: if ( !normOK ) then get normal by mesh faces
1731 // Set the rest data
1732 // --------------------
1733 if ( onShrinkShape )
1735 edge._sWOL = (*s2s).second;
1737 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1738 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1739 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1741 // set initial position which is parameters on _sWOL in this case
1742 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1744 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1745 edge._pos.push_back( gp_XYZ( u, 0, 0));
1746 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1750 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1751 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1752 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1757 edge._pos.push_back( SMESH_TNodeXYZ( node ));
1759 if ( posType == SMDS_TOP_FACE )
1761 getSimplices( node, edge._simplices, _ignoreShapeIds, &data );
1762 double avgNormProj = 0, avgLen = 0;
1763 for ( unsigned i = 0; i < edge._simplices.size(); ++i )
1765 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
1766 avgNormProj += edge._normal * vec;
1767 avgLen += vec.Modulus();
1769 avgNormProj /= edge._simplices.size();
1770 avgLen /= edge._simplices.size();
1771 edge._curvature = _Curvature::New( avgNormProj, avgLen );
1775 // Set neighbour nodes for a _LayerEdge based on EDGE
1777 if ( posType == SMDS_TOP_EDGE /*||
1778 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1780 edge._2neibors = new _2NearEdges;
1781 // target node instead of source ones will be set later
1782 if ( ! findNeiborsOnEdge( &edge,
1783 edge._2neibors->_nodes[0],
1784 edge._2neibors->_nodes[1],
1787 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1788 edge._2neibors->_nodes[1],
1792 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1797 //================================================================================
1799 * \brief Find 2 neigbor nodes of a node on EDGE
1801 //================================================================================
1803 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
1804 const SMDS_MeshNode*& n1,
1805 const SMDS_MeshNode*& n2,
1808 const SMDS_MeshNode* node = edge->_nodes[0];
1809 const int shapeInd = node->getshapeId();
1810 SMESHDS_SubMesh* edgeSM = 0;
1811 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
1814 edgeSM = getMeshDS()->MeshElements( shapeInd );
1815 if ( !edgeSM || edgeSM->NbElements() == 0 )
1816 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
1820 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
1821 while ( eIt->more() && !n2 )
1823 const SMDS_MeshElement* e = eIt->next();
1824 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
1825 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
1828 if (!edgeSM->Contains(e)) continue;
1832 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
1833 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
1835 ( iN++ ? n2 : n1 ) = nNeibor;
1838 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
1842 //================================================================================
1844 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
1846 //================================================================================
1848 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
1849 const SMDS_MeshNode* n2,
1850 SMESH_MesherHelper& helper)
1852 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1855 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
1856 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
1857 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
1861 double sumLen = vec1.Modulus() + vec2.Modulus();
1862 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
1863 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
1864 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
1865 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
1866 if ( _curvature ) delete _curvature;
1867 _curvature = _Curvature::New( avgNormProj, avgLen );
1869 // if ( _curvature )
1870 // cout << _nodes[0]->GetID()
1871 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
1872 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
1873 // << _curvature->lenDelta(0) << endl;
1878 if ( _sWOL.IsNull() )
1880 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
1881 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
1882 gp_XYZ plnNorm = dirE ^ _normal;
1883 double proj0 = plnNorm * vec1;
1884 double proj1 = plnNorm * vec2;
1885 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
1887 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
1888 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
1893 //================================================================================
1895 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
1896 * this and other _LayerEdge's are inflated along a FACE or an EDGE
1898 //================================================================================
1900 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
1902 _nodes = other._nodes;
1903 _normal = other._normal;
1905 _lenFactor = other._lenFactor;
1906 _cosin = other._cosin;
1907 _sWOL = other._sWOL;
1908 _2neibors = other._2neibors;
1909 _curvature = 0; std::swap( _curvature, other._curvature );
1910 _2neibors = 0; std::swap( _2neibors, other._2neibors );
1912 if ( _sWOL.ShapeType() == TopAbs_EDGE )
1914 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
1915 _pos.push_back( gp_XYZ( u, 0, 0));
1919 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
1920 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1924 //================================================================================
1926 * \brief Set _cosin and _lenFactor
1928 //================================================================================
1930 void _LayerEdge::SetCosin( double cosin )
1933 _lenFactor = ( _cosin > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
1936 //================================================================================
1938 * \brief Fills a vector<_Simplex >
1940 //================================================================================
1942 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
1943 vector<_Simplex>& simplices,
1944 const set<TGeomID>& ingnoreShapes,
1945 const _SolidData* dataToCheckOri,
1948 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1949 while ( fIt->more() )
1951 const SMDS_MeshElement* f = fIt->next();
1952 const TGeomID shapeInd = f->getshapeId();
1953 if ( ingnoreShapes.count( shapeInd )) continue;
1954 const int nbNodes = f->NbCornerNodes();
1955 int srcInd = f->GetNodeIndex( node );
1956 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
1957 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
1958 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
1959 std::swap( nPrev, nNext );
1960 simplices.push_back( _Simplex( nPrev, nNext ));
1965 vector<_Simplex> sortedSimplices( simplices.size() );
1966 sortedSimplices[0] = simplices[0];
1968 for ( size_t i = 1; i < simplices.size(); ++i )
1970 for ( size_t j = 1; j < simplices.size(); ++j )
1971 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
1973 sortedSimplices[i] = simplices[j];
1978 if ( nbFound == simplices.size() - 1 )
1979 simplices.swap( sortedSimplices );
1983 //================================================================================
1985 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
1987 //================================================================================
1989 void _ViscousBuilder::makeGroupOfLE()
1992 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
1994 if ( _sdVec[i]._edges.empty() ) continue;
1995 // string name = SMESH_Comment("_LayerEdge's_") << i;
1997 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
1998 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
1999 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
2001 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
2002 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2004 _LayerEdge* le = _sdVec[i]._edges[j];
2005 for ( unsigned iN = 1; iN < le->_nodes.size(); ++iN )
2006 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
2007 << ", " << le->_nodes[iN]->GetID() <<"])");
2008 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
2012 dumpFunction( SMESH_Comment("makeNormals") << i );
2013 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2015 _LayerEdge& edge = *_sdVec[i]._edges[j];
2016 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2017 nXYZ += edge._normal * _sdVec[i]._stepSize;
2018 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2019 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2023 // name = SMESH_Comment("tmp_faces ") << i;
2024 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2025 // gDS = (SMESHDS_Group*)g->GetGroupDS();
2026 // SMESH_MeshEditor editor( _mesh );
2027 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2028 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2029 for ( ; fExp.More(); fExp.Next() )
2031 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2033 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2034 while ( fIt->more())
2036 const SMDS_MeshElement* e = fIt->next();
2037 SMESH_Comment cmd("mesh.AddFace([");
2038 for ( int j=0; j < e->NbCornerNodes(); ++j )
2039 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2041 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2042 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2051 //================================================================================
2053 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2055 //================================================================================
2057 bool _ViscousBuilder::inflate(_SolidData& data)
2059 SMESH_MesherHelper helper( *_mesh );
2061 // Limit inflation step size by geometry size found by itersecting
2062 // normals of _LayerEdge's with mesh faces
2063 double geomSize = Precision::Infinite(), intersecDist;
2064 SMESH_MeshEditor editor( _mesh );
2065 auto_ptr<SMESH_ElementSearcher> searcher
2066 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2067 for ( unsigned i = 0; i < data._edges.size(); ++i )
2069 if ( data._edges[i]->IsOnEdge() ) continue;
2070 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2071 if ( geomSize > intersecDist )
2072 geomSize = intersecDist;
2074 if ( data._stepSize > 0.3 * geomSize )
2075 limitStepSize( data, 0.3 * geomSize );
2077 const double tgtThick = data._hyp->GetTotalThickness();
2078 if ( data._stepSize > tgtThick )
2079 limitStepSize( data, tgtThick );
2081 if ( data._stepSize < 1. )
2082 data._epsilon = data._stepSize * 1e-7;
2085 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2088 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2089 int nbSteps = 0, nbRepeats = 0;
2090 while ( 1.01 * avgThick < tgtThick )
2092 // new target length
2093 curThick += data._stepSize;
2094 if ( curThick > tgtThick )
2096 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2100 // Elongate _LayerEdge's
2101 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2102 for ( unsigned i = 0; i < data._edges.size(); ++i )
2104 data._edges[i]->SetNewLength( curThick, helper );
2109 if ( !updateNormals( data, helper ) )
2112 // Improve and check quality
2113 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2117 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2118 for ( unsigned i = 0; i < data._edges.size(); ++i )
2120 data._edges[i]->InvalidateStep( nbSteps+1 );
2124 break; // no more inflating possible
2128 // Evaluate achieved thickness
2130 for ( unsigned i = 0; i < data._edges.size(); ++i )
2131 avgThick += data._edges[i]->_len;
2132 avgThick /= data._edges.size();
2134 cout << "-- Thickness " << avgThick << " reached" << endl;
2137 if ( distToIntersection < avgThick*1.5 )
2140 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2141 << avgThick << " ) * 1.5" << endl;
2146 limitStepSize( data, 0.25 * distToIntersection );
2147 if ( data._stepSizeNodes[0] )
2148 data._stepSize = data._stepSizeCoeff *
2149 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2153 return error("failed at the very first inflation step", data._index);
2158 //================================================================================
2160 * \brief Improve quality of layer inner surface and check intersection
2162 //================================================================================
2164 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2166 double & distToIntersection)
2168 if ( data._endEdgeToSmooth.empty() )
2169 return true; // no shapes needing smoothing
2171 bool moved, improved;
2173 SMESH_MesherHelper helper(*_mesh);
2174 Handle(Geom_Surface) surface;
2178 for ( unsigned iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2181 iEnd = data._endEdgeToSmooth[ iS ];
2183 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2184 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2186 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2187 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2188 helper.SetSubShape( F );
2189 surface = BRep_Tool::Surface( F );
2194 F.Nullify(); surface.Nullify();
2196 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2198 if ( data._edges[ iBeg ]->IsOnEdge() )
2200 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2202 // try a simple solution on an analytic EDGE
2203 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2209 for ( int i = iBeg; i < iEnd; ++i )
2211 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2213 dumpCmd( SMESH_Comment("# end step ")<<step);
2215 while ( moved && step++ < 5 );
2216 //cout << " NB STEPS: " << step << endl;
2223 int step = 0, badNb = 0; moved = true;
2224 while (( ++step <= 5 && moved ) || improved )
2226 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2227 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2228 int oldBadNb = badNb;
2231 for ( int i = iBeg; i < iEnd; ++i )
2232 moved |= data._edges[i]->Smooth(badNb);
2233 improved = ( badNb < oldBadNb );
2240 for ( int i = iBeg; i < iEnd; ++i )
2242 _LayerEdge* edge = data._edges[i];
2243 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2244 for ( unsigned j = 0; j < edge->_simplices.size(); ++j )
2245 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2247 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2248 << " "<< edge->_simplices[j]._nPrev->GetID()
2249 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2257 } // loop on shapes to smooth
2259 // Check if the last segments of _LayerEdge intersects 2D elements;
2260 // checked elements are either temporary faces or faces on surfaces w/o the layers
2262 SMESH_MeshEditor editor( _mesh );
2263 auto_ptr<SMESH_ElementSearcher> searcher
2264 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2266 distToIntersection = Precision::Infinite();
2268 const SMDS_MeshElement* intFace = 0;
2270 const SMDS_MeshElement* closestFace = 0;
2273 for ( unsigned i = 0; i < data._edges.size(); ++i )
2275 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2277 if ( distToIntersection > dist )
2279 distToIntersection = dist;
2282 closestFace = intFace;
2289 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2290 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2291 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2292 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2293 << ") distance = " << distToIntersection<< endl;
2300 //================================================================================
2302 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2303 * _LayerEdge's to be in a consequent order
2305 //================================================================================
2307 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2310 Handle(Geom_Surface)& surface,
2311 const TopoDS_Face& F,
2312 SMESH_MesherHelper& helper)
2314 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2316 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2318 if ( i2curve == _edge2curve.end() )
2320 // sort _LayerEdge's by position on the EDGE
2322 map< double, _LayerEdge* > u2edge;
2323 for ( int i = iFrom; i < iTo; ++i )
2324 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2326 ASSERT( u2edge.size() == iTo - iFrom );
2327 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2328 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2329 _edges[i] = u2e->second;
2331 // set _2neibors according to the new order
2332 for ( int i = iFrom; i < iTo-1; ++i )
2333 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2334 _edges[i]->_2neibors->reverse();
2335 if ( u2edge.size() > 1 &&
2336 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2337 _edges[iTo-1]->_2neibors->reverse();
2340 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2342 TopLoc_Location loc; double f,l;
2344 Handle(Geom_Line) line;
2345 Handle(Geom_Circle) circle;
2346 bool isLine, isCirc;
2347 if ( F.IsNull() ) // 3D case
2349 // check if the EDGE is a line
2350 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2351 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2352 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2354 line = Handle(Geom_Line)::DownCast( curve );
2355 circle = Handle(Geom_Circle)::DownCast( curve );
2356 isLine = (!line.IsNull());
2357 isCirc = (!circle.IsNull());
2359 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2362 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2363 while ( nIt->more() )
2364 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2365 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2367 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2368 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2369 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2370 for ( int i = 0; i < 3 && !isLine; ++i )
2371 isLine = ( size.Coord( i+1 ) <= lineTol );
2373 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2380 // check if the EDGE is a line
2381 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2382 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2383 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2385 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2386 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2387 isLine = (!line2d.IsNull());
2388 isCirc = (!circle2d.IsNull());
2390 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2393 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2394 while ( nIt->more() )
2395 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2396 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2398 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2399 for ( int i = 0; i < 2 && !isLine; ++i )
2400 isLine = ( size.Coord( i+1 ) <= lineTol );
2402 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2408 line = new Geom_Line( gp::OX() ); // only type does matter
2412 gp_Pnt2d p = circle2d->Location();
2413 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2414 circle = new Geom_Circle( ax, 1.); // only center position does matter
2418 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2426 return i2curve->second;
2429 //================================================================================
2431 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2433 //================================================================================
2435 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2438 Handle(Geom_Surface)& surface,
2439 const TopoDS_Face& F,
2440 SMESH_MesherHelper& helper)
2442 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2443 helper.GetMeshDS());
2444 TopoDS_Edge E = TopoDS::Edge( S );
2446 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2447 if ( curve.IsNull() ) return false;
2449 // compute a relative length of segments
2450 vector< double > len( iTo-iFrom+1 );
2452 double curLen, prevLen = len[0] = 1.0;
2453 for ( int i = iFrom; i < iTo; ++i )
2455 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2456 len[i-iFrom+1] = len[i-iFrom] + curLen;
2461 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2463 if ( F.IsNull() ) // 3D
2465 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2466 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2467 for ( int i = iFrom; i < iTo; ++i )
2469 double r = len[i-iFrom] / len.back();
2470 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2471 data._edges[i]->_pos.back() = newPos;
2472 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2473 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2474 dumpMove( tgtNode );
2479 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2480 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2481 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2482 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2484 int iPeriodic = helper.GetPeriodicIndex();
2485 if ( iPeriodic == 1 || iPeriodic == 2 )
2487 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2488 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2489 std::swap( uv0, uv1 );
2492 const gp_XY rangeUV = uv1 - uv0;
2493 for ( int i = iFrom; i < iTo; ++i )
2495 double r = len[i-iFrom] / len.back();
2496 gp_XY newUV = uv0 + r * rangeUV;
2497 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2499 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2500 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2501 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2502 dumpMove( tgtNode );
2504 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2505 pos->SetUParameter( newUV.X() );
2506 pos->SetVParameter( newUV.Y() );
2512 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2514 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2515 gp_Pnt center3D = circle->Location();
2517 if ( F.IsNull() ) // 3D
2519 return false; // TODO ???
2523 const gp_XY center( center3D.X(), center3D.Y() );
2525 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2526 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2527 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2528 gp_Vec2d vec0( center, uv0 );
2529 gp_Vec2d vecM( center, uvM );
2530 gp_Vec2d vec1( center, uv1 );
2531 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2532 double uMidl = vec0.Angle( vecM );
2533 if ( uLast * uMidl < 0. )
2534 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
2535 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2537 gp_Ax2d axis( center, vec0 );
2538 gp_Circ2d circ( axis, radius );
2539 for ( int i = iFrom; i < iTo; ++i )
2541 double newU = uLast * len[i-iFrom] / len.back();
2542 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2543 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2545 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2546 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2547 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2548 dumpMove( tgtNode );
2550 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2551 pos->SetUParameter( newUV.X() );
2552 pos->SetVParameter( newUV.Y() );
2561 //================================================================================
2563 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2564 * _LayerEdge's on neighbor EDGE's
2566 //================================================================================
2568 bool _ViscousBuilder::updateNormals( _SolidData& data,
2569 SMESH_MesherHelper& helper )
2571 // make temporary quadrangles got by extrusion of
2572 // mesh edges along _LayerEdge._normal's
2574 vector< const SMDS_MeshElement* > tmpFaces;
2576 set< SMESH_TLink > extrudedLinks; // contains target nodes
2577 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2579 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2580 for ( unsigned i = 0; i < data._edges.size(); ++i )
2582 _LayerEdge* edge = data._edges[i];
2583 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2584 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2585 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2587 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2588 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2589 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2590 if ( !link_isnew.second )
2592 extrudedLinks.erase( link_isnew.first );
2593 continue; // already extruded and will no more encounter
2595 // look for a _LayerEdge containg tgt2
2596 // _LayerEdge* neiborEdge = 0;
2597 // unsigned di = 0; // check _edges[i+di] and _edges[i-di]
2598 // while ( !neiborEdge && ++di <= data._edges.size() )
2600 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2601 // neiborEdge = data._edges[i+di];
2602 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2603 // neiborEdge = data._edges[i-di];
2605 // if ( !neiborEdge )
2606 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2607 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2609 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2610 tmpFaces.push_back( f );
2612 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2613 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2614 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2619 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2620 // Perform two loops on _LayerEdge on EDGE's:
2621 // 1) to find and fix intersection
2622 // 2) to check that no new intersection appears as result of 1)
2624 SMESH_MeshEditor editor( _mesh );
2625 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2627 auto_ptr<SMESH_ElementSearcher> searcher ( editor.GetElementSearcher( fIt ));
2629 // 1) Find intersections
2631 const SMDS_MeshElement* face;
2632 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2633 TLEdge2LEdgeSet edge2CloseEdge;
2635 const double eps = data._epsilon * data._epsilon;
2636 for ( unsigned i = 0; i < data._edges.size(); ++i )
2638 _LayerEdge* edge = data._edges[i];
2639 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2640 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2642 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2643 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2644 ee.insert( f->_le1 );
2645 ee.insert( f->_le2 );
2646 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
2647 edge2CloseEdge[ f->_le1 ].insert( edge );
2648 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
2649 edge2CloseEdge[ f->_le2 ].insert( edge );
2653 // Set _LayerEdge._normal
2655 if ( !edge2CloseEdge.empty() )
2657 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2659 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2660 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2662 _LayerEdge* edge1 = e2ee->first;
2663 _LayerEdge* edge2 = 0;
2664 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
2666 // find EDGEs the edges reside
2668 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2669 if ( S.ShapeType() != TopAbs_EDGE )
2670 continue; // TODO: find EDGE by VERTEX
2671 E1 = TopoDS::Edge( S );
2672 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
2673 while ( E2.IsNull() && eIt != ee.end())
2675 _LayerEdge* e2 = *eIt++;
2676 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2677 if ( S.ShapeType() == TopAbs_EDGE )
2678 E2 = TopoDS::Edge( S ), edge2 = e2;
2680 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2682 // find 3 FACEs sharing 2 EDGEs
2684 TopoDS_Face FF1[2], FF2[2];
2685 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2686 while ( fIt->more() && FF1[1].IsNull())
2688 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2689 if ( helper.IsSubShape( *F, data._solid))
2690 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2692 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2693 while ( fIt->more() && FF2[1].IsNull())
2695 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2696 if ( helper.IsSubShape( *F, data._solid))
2697 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2699 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2700 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2701 std::swap( FF1[0], FF1[1] );
2702 if ( FF2[0].IsSame( FF1[0]) )
2703 std::swap( FF2[0], FF2[1] );
2704 if ( FF1[0].IsNull() || FF2[0].IsNull() )
2707 // // get a new normal for edge1
2709 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2710 if ( edge1->_cosin < 0 )
2711 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2712 if ( edge2->_cosin < 0 )
2713 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2714 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2715 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2716 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2717 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2718 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2719 // newNorm.Normalize();
2721 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2722 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2723 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2724 newNorm.Normalize();
2726 edge1->_normal = newNorm.XYZ();
2728 // update data of edge1 depending on _normal
2729 const SMDS_MeshNode *n1, *n2;
2730 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2731 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2732 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2734 edge1->SetDataByNeighbors( n1, n2, helper );
2736 if ( edge1->_cosin < 0 )
2739 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2740 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2741 edge1->SetCosin( cos( angle ));
2743 // limit data._stepSize
2744 if ( edge1->_cosin > 0.1 )
2746 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2747 while ( fIt->more() )
2748 limitStepSize( data, fIt->next(), edge1->_cosin );
2750 // set new XYZ of target node
2751 edge1->InvalidateStep( 1 );
2753 edge1->SetNewLength( data._stepSize, helper );
2756 // Update normals and other dependent data of not intersecting _LayerEdge's
2757 // neighboring the intersecting ones
2759 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2761 _LayerEdge* edge1 = e2ee->first;
2762 if ( !edge1->_2neibors )
2764 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2766 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2767 if ( edge2CloseEdge.count ( neighbor ))
2768 continue; // j-th neighbor is also intersected
2769 _LayerEdge* prevEdge = edge1;
2770 const int nbSteps = 6;
2771 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2773 if ( !neighbor->_2neibors )
2774 break; // neighbor is on VERTEX
2776 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2777 if ( nextEdge == prevEdge )
2778 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2779 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2780 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
2781 double r = double(step-1)/nbSteps;
2782 if ( !nextEdge->_2neibors )
2785 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2786 newNorm.Normalize();
2788 neighbor->_normal = newNorm;
2789 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2790 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2792 neighbor->InvalidateStep( 1 );
2794 neighbor->SetNewLength( data._stepSize, helper );
2796 // goto the next neighbor
2797 prevEdge = neighbor;
2798 neighbor = nextEdge;
2804 // 2) Check absence of intersections
2807 for ( unsigned i = 0 ; i < tmpFaces.size(); ++i )
2813 //================================================================================
2815 * \brief Looks for intersection of it's last segment with faces
2816 * \param distance - returns shortest distance from the last node to intersection
2818 //================================================================================
2820 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
2822 const double& epsilon,
2823 const SMDS_MeshElement** face)
2825 vector< const SMDS_MeshElement* > suspectFaces;
2827 gp_Ax1 lastSegment = LastSegment(segLen);
2828 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2830 bool segmentIntersected = false;
2831 distance = Precision::Infinite();
2832 int iFace = -1; // intersected face
2833 for ( unsigned j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
2835 const SMDS_MeshElement* face = suspectFaces[j];
2836 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
2837 face->GetNodeIndex( _nodes[0] ) >= 0 )
2838 continue; // face sharing _LayerEdge node
2839 const int nbNodes = face->NbCornerNodes();
2840 bool intFound = false;
2842 SMDS_MeshElement::iterator nIt = face->begin_nodes();
2845 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
2849 const SMDS_MeshNode* tria[3];
2852 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
2855 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
2861 if ( dist < segLen*(1.01))
2862 segmentIntersected = true;
2863 if ( distance > dist )
2864 distance = dist, iFace = j;
2867 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
2868 // if ( distance && iFace > -1 )
2870 // // distance is used to limit size of inflation step which depends on
2871 // // whether the intersected face bears viscous layers or not
2872 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
2876 if ( segmentIntersected )
2879 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
2880 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
2881 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
2882 << ", intersection with face ("
2883 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2884 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
2885 << ") distance = " << distance - segLen<< endl;
2891 return segmentIntersected;
2894 //================================================================================
2896 * \brief Returns size and direction of the last segment
2898 //================================================================================
2900 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
2902 // find two non-coincident positions
2903 gp_XYZ orig = _pos.back();
2905 int iPrev = _pos.size() - 2;
2906 while ( iPrev >= 0 )
2908 dir = orig - _pos[iPrev];
2909 if ( dir.SquareModulus() > 1e-100 )
2919 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
2920 segDir.SetDirection( _normal );
2925 gp_Pnt pPrev = _pos[ iPrev ];
2926 if ( !_sWOL.IsNull() )
2928 TopLoc_Location loc;
2929 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2932 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2933 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
2937 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2938 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
2940 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
2942 segDir.SetLocation( pPrev );
2943 segDir.SetDirection( dir );
2944 segLen = dir.Modulus();
2950 //================================================================================
2952 * \brief Test intersection of the last segment with a given triangle
2953 * using Moller-Trumbore algorithm
2954 * Intersection is detected if distance to intersection is less than _LayerEdge._len
2956 //================================================================================
2958 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
2959 const SMDS_MeshNode* n0,
2960 const SMDS_MeshNode* n1,
2961 const SMDS_MeshNode* n2,
2963 const double& EPSILON) const
2965 //const double EPSILON = 1e-6;
2967 gp_XYZ orig = lastSegment.Location().XYZ();
2968 gp_XYZ dir = lastSegment.Direction().XYZ();
2970 SMESH_TNodeXYZ vert0( n0 );
2971 SMESH_TNodeXYZ vert1( n1 );
2972 SMESH_TNodeXYZ vert2( n2 );
2974 /* calculate distance from vert0 to ray origin */
2975 gp_XYZ tvec = orig - vert0;
2977 if ( tvec * dir > EPSILON )
2978 // intersected face is at back side of the temporary face this _LayerEdge belongs to
2981 gp_XYZ edge1 = vert1 - vert0;
2982 gp_XYZ edge2 = vert2 - vert0;
2984 /* begin calculating determinant - also used to calculate U parameter */
2985 gp_XYZ pvec = dir ^ edge2;
2987 /* if determinant is near zero, ray lies in plane of triangle */
2988 double det = edge1 * pvec;
2990 if (det > -EPSILON && det < EPSILON)
2992 double inv_det = 1.0 / det;
2994 /* calculate U parameter and test bounds */
2995 double u = ( tvec * pvec ) * inv_det;
2996 if (u < 0.0 || u > 1.0)
2999 /* prepare to test V parameter */
3000 gp_XYZ qvec = tvec ^ edge1;
3002 /* calculate V parameter and test bounds */
3003 double v = (dir * qvec) * inv_det;
3004 if ( v < 0.0 || u + v > 1.0 )
3007 /* calculate t, ray intersects triangle */
3008 t = (edge2 * qvec) * inv_det;
3010 // if (det < EPSILON)
3013 // /* calculate distance from vert0 to ray origin */
3014 // gp_XYZ tvec = orig - vert0;
3016 // /* calculate U parameter and test bounds */
3017 // double u = tvec * pvec;
3018 // if (u < 0.0 || u > det)
3021 // /* prepare to test V parameter */
3022 // gp_XYZ qvec = tvec ^ edge1;
3024 // /* calculate V parameter and test bounds */
3025 // double v = dir * qvec;
3026 // if (v < 0.0 || u + v > det)
3029 // /* calculate t, scale parameters, ray intersects triangle */
3030 // double t = edge2 * qvec;
3031 // double inv_det = 1.0 / det;
3039 //================================================================================
3041 * \brief Perform smooth of _LayerEdge's based on EDGE's
3042 * \retval bool - true if node has been moved
3044 //================================================================================
3046 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3047 const TopoDS_Face& F,
3048 SMESH_MesherHelper& helper)
3050 ASSERT( IsOnEdge() );
3052 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3053 SMESH_TNodeXYZ oldPos( tgtNode );
3054 double dist01, distNewOld;
3056 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3057 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3058 dist01 = p0.Distance( _2neibors->_nodes[1] );
3060 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3061 double lenDelta = 0;
3064 lenDelta = _curvature->lenDelta( _len );
3065 newPos.ChangeCoord() += _normal * lenDelta;
3068 distNewOld = newPos.Distance( oldPos );
3072 if ( _2neibors->_plnNorm )
3074 // put newPos on the plane defined by source node and _plnNorm
3075 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3076 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3077 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3079 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3080 _pos.back() = newPos.XYZ();
3084 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3085 gp_XY uv( Precision::Infinite(), 0 );
3086 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3087 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3089 newPos = surface->Value( uv.X(), uv.Y() );
3090 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3093 if ( _curvature && lenDelta < 0 )
3095 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3096 _len -= prevPos.Distance( oldPos );
3097 _len += prevPos.Distance( newPos );
3099 bool moved = distNewOld > dist01/50;
3101 dumpMove( tgtNode ); // debug
3106 //================================================================================
3108 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3109 * \retval bool - true if _tgtNode has been moved
3111 //================================================================================
3113 bool _LayerEdge::Smooth(int& badNb)
3115 if ( _simplices.size() < 2 )
3116 return false; // _LayerEdge inflated along EDGE or FACE
3118 // compute new position for the last _pos
3119 gp_XYZ newPos (0,0,0);
3120 for ( unsigned i = 0; i < _simplices.size(); ++i )
3121 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3122 newPos /= _simplices.size();
3125 newPos += _normal * _curvature->lenDelta( _len );
3127 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3128 // if ( _cosin < -0.1)
3130 // // Avoid decreasing length of edge on concave surface
3131 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3132 // gp_Vec newMove( prevPos, newPos );
3133 // newPos = _pos.back() + newMove.XYZ();
3135 // else if ( _cosin > 0.3 )
3137 // // Avoid increasing length of edge too much
3140 // count quality metrics (orientation) of tetras around _tgtNode
3142 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3143 for ( unsigned i = 0; i < _simplices.size(); ++i )
3144 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3147 for ( unsigned i = 0; i < _simplices.size(); ++i )
3148 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3150 if ( nbOkAfter < nbOkBefore )
3153 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3155 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3156 _len += prevPos.Distance(newPos);
3158 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3159 _pos.back() = newPos;
3161 badNb += _simplices.size() - nbOkAfter;
3168 //================================================================================
3170 * \brief Add a new segment to _LayerEdge during inflation
3172 //================================================================================
3174 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3176 if ( _len - len > -1e-6 )
3178 _pos.push_back( _pos.back() );
3182 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3183 SMESH_TNodeXYZ oldXYZ( n );
3184 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3185 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3187 _pos.push_back( nXYZ );
3189 if ( !_sWOL.IsNull() )
3192 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3194 double u = Precision::Infinite(); // to force projection w/o distance check
3195 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3196 _pos.back().SetCoord( u, 0, 0 );
3197 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3198 pos->SetUParameter( u );
3202 gp_XY uv( Precision::Infinite(), 0 );
3203 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3204 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3205 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3206 pos->SetUParameter( uv.X() );
3207 pos->SetVParameter( uv.Y() );
3209 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3211 dumpMove( n ); //debug
3214 //================================================================================
3216 * \brief Remove last inflation step
3218 //================================================================================
3220 void _LayerEdge::InvalidateStep( int curStep )
3222 if ( _pos.size() > curStep )
3224 _pos.resize( curStep );
3225 gp_Pnt nXYZ = _pos.back();
3226 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3227 if ( !_sWOL.IsNull() )
3229 TopLoc_Location loc;
3230 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3232 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3233 pos->SetUParameter( nXYZ.X() );
3235 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3236 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3240 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3241 pos->SetUParameter( nXYZ.X() );
3242 pos->SetVParameter( nXYZ.Y() );
3243 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3244 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3247 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3252 //================================================================================
3254 * \brief Create layers of prisms
3256 //================================================================================
3258 bool _ViscousBuilder::refine(_SolidData& data)
3260 SMESH_MesherHelper helper( *_mesh );
3261 helper.SetSubShape( data._solid );
3262 helper.SetElementsOnShape(false);
3264 Handle(Geom_Curve) curve;
3265 Handle(Geom_Surface) surface;
3266 TopoDS_Edge geomEdge;
3267 TopoDS_Face geomFace;
3268 TopLoc_Location loc;
3269 double f,l, u/*, distXYZ[4]*/;
3273 for ( unsigned i = 0; i < data._edges.size(); ++i )
3275 _LayerEdge& edge = *data._edges[i];
3277 // get accumulated length of segments
3278 vector< double > segLen( edge._pos.size() );
3280 for ( unsigned j = 1; j < edge._pos.size(); ++j )
3281 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3283 // allocate memory for new nodes if it is not yet refined
3284 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3285 if ( edge._nodes.size() == 2 )
3287 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3289 edge._nodes.back() = tgtNode;
3291 if ( !edge._sWOL.IsNull() )
3293 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3294 // restore position of the last node
3298 geomEdge = TopoDS::Edge( edge._sWOL );
3299 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3300 // double u = helper.GetNodeU( tgtNode );
3301 // p = curve->Value( u );
3305 geomFace = TopoDS::Face( edge._sWOL );
3306 surface = BRep_Tool::Surface( geomFace, loc );
3307 // gp_XY uv = helper.GetNodeUV( tgtNode );
3308 // p = surface->Value( uv.X(), uv.Y() );
3310 // p.Transform( loc );
3311 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3313 // calculate height of the first layer
3315 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3316 const double f = data._hyp->GetStretchFactor();
3317 const int N = data._hyp->GetNumberLayers();
3318 const double fPowN = pow( f, N );
3319 if ( fPowN - 1 <= numeric_limits<double>::min() )
3322 h0 = T * ( f - 1 )/( fPowN - 1 );
3324 const double zeroLen = std::numeric_limits<double>::min();
3326 // create intermediate nodes
3327 double hSum = 0, hi = h0/f;
3329 for ( unsigned iStep = 1; iStep < edge._nodes.size(); ++iStep )
3331 // compute an intermediate position
3334 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3336 int iPrevSeg = iSeg-1;
3337 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3339 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3340 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3342 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3343 if ( !edge._sWOL.IsNull() )
3345 // compute XYZ by parameters <pos>
3349 pos = curve->Value( u ).Transformed(loc);
3353 uv.SetCoord( pos.X(), pos.Y() );
3354 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3357 // create or update the node
3360 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3361 if ( !edge._sWOL.IsNull() )
3364 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3366 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3370 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3375 if ( !edge._sWOL.IsNull() )
3377 // make average pos from new and current parameters
3380 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3381 pos = curve->Value( u ).Transformed(loc);
3385 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3386 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3389 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3394 if ( !getMeshDS()->IsEmbeddedMode() )
3395 // Log node movement
3396 for ( unsigned i = 0; i < data._edges.size(); ++i )
3398 _LayerEdge& edge = *data._edges[i];
3399 SMESH_TNodeXYZ p ( edge._nodes.back() );
3400 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
3403 // TODO: make quadratic prisms and polyhedrons(?)
3405 helper.SetElementsOnShape(true);
3407 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3408 for ( ; exp.More(); exp.Next() )
3410 if ( _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3412 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3413 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3414 vector< vector<const SMDS_MeshNode*>* > nnVec;
3415 while ( fIt->more() )
3417 const SMDS_MeshElement* face = fIt->next();
3418 int nbNodes = face->NbCornerNodes();
3419 nnVec.resize( nbNodes );
3420 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3421 for ( int iN = 0; iN < nbNodes; ++iN )
3423 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3424 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3427 int nbZ = nnVec[0]->size();
3431 for ( int iZ = 1; iZ < nbZ; ++iZ )
3432 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3433 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3436 for ( int iZ = 1; iZ < nbZ; ++iZ )
3437 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3438 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3439 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3440 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3443 return error("Not supported type of element", data._index);
3450 //================================================================================
3452 * \brief Shrink 2D mesh on faces to let space for inflated layers
3454 //================================================================================
3456 bool _ViscousBuilder::shrink()
3458 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3459 // inflated along FACE or EDGE)
3460 map< TGeomID, _SolidData* > f2sdMap;
3461 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
3463 _SolidData& data = _sdVec[i];
3464 TopTools_MapOfShape FFMap;
3465 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3466 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3467 if ( s2s->second.ShapeType() == TopAbs_FACE )
3469 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3471 if ( FFMap.Add( (*s2s).second ))
3472 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3473 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3474 // by StdMeshers_QuadToTriaAdaptor
3475 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3477 SMESH_ProxyMesh::SubMesh* proxySub =
3478 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3479 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3480 while ( fIt->more() )
3481 proxySub->AddElement( fIt->next() );
3482 // as a result 3D algo will use elements from proxySub and not from smDS
3487 SMESH_MesherHelper helper( *_mesh );
3488 helper.ToFixNodeParameters( true );
3491 map< TGeomID, _Shrinker1D > e2shrMap;
3493 // loop on FACES to srink mesh on
3494 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3495 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3497 _SolidData& data = *f2sd->second;
3498 TNode2Edge& n2eMap = data._n2eMap;
3499 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3501 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3503 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3504 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3506 helper.SetSubShape(F);
3508 // ===========================
3509 // Prepare data for shrinking
3510 // ===========================
3512 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3513 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3514 vector < const SMDS_MeshNode* > smoothNodes;
3516 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3517 while ( nIt->more() )
3519 const SMDS_MeshNode* n = nIt->next();
3520 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3521 smoothNodes.push_back( n );
3524 // Find out face orientation
3526 const set<TGeomID> ignoreShapes;
3528 if ( !smoothNodes.empty() )
3530 vector<_Simplex> simplices;
3531 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3532 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3533 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3534 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3535 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3539 // Find _LayerEdge's inflated along F
3540 vector< _LayerEdge* > lEdges;
3542 SMESH_subMeshIteratorPtr subIt =
3543 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3544 while ( subIt->more() )
3546 SMESH_subMesh* sub = subIt->next();
3547 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3548 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3550 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3551 while ( nIt->more() )
3553 _LayerEdge* edge = n2eMap[ nIt->next() ];
3554 lEdges.push_back( edge );
3555 prepareEdgeToShrink( *edge, F, helper, smDS );
3560 // Replace source nodes by target nodes in mesh faces to shrink
3561 const SMDS_MeshNode* nodes[20];
3562 for ( unsigned i = 0; i < lEdges.size(); ++i )
3564 _LayerEdge& edge = *lEdges[i];
3565 const SMDS_MeshNode* srcNode = edge._nodes[0];
3566 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3567 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3568 while ( fIt->more() )
3570 const SMDS_MeshElement* f = fIt->next();
3571 if ( !smDS->Contains( f ))
3573 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3574 for ( int iN = 0; iN < f->NbNodes(); ++iN )
3576 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3577 nodes[iN] = ( n == srcNode ? tgtNode : n );
3579 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3583 // find out if a FACE is concave
3584 const bool isConcaveFace = isConcave( F, helper );
3586 // Create _SmoothNode's on face F
3587 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3589 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3590 for ( unsigned i = 0; i < smoothNodes.size(); ++i )
3592 const SMDS_MeshNode* n = smoothNodes[i];
3593 nodesToSmooth[ i ]._node = n;
3594 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3595 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, isConcaveFace );
3596 // fix up incorrect uv of nodes on the FACE
3597 helper.GetNodeUV( F, n, 0, &isOkUV);
3602 //if ( nodesToSmooth.empty() ) continue;
3604 // Find EDGE's to shrink
3605 set< _Shrinker1D* > eShri1D;
3607 for ( unsigned i = 0; i < lEdges.size(); ++i )
3609 _LayerEdge* edge = lEdges[i];
3610 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3612 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3613 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3614 eShri1D.insert( & srinker );
3615 srinker.AddEdge( edge, helper );
3616 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
3617 // restore params of nodes on EGDE if the EDGE has been already
3618 // srinked while srinking another FACE
3619 srinker.RestoreParams();
3624 // ==================
3625 // Perform shrinking
3626 // ==================
3628 bool shrinked = true;
3629 int badNb, shriStep=0, smooStep=0;
3632 // Move boundary nodes (actually just set new UV)
3633 // -----------------------------------------------
3634 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep++ ); // debug
3636 for ( unsigned i = 0; i < lEdges.size(); ++i )
3638 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3642 // Move nodes on EDGE's
3643 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3644 for ( ; shr != eShri1D.end(); ++shr )
3645 (*shr)->Compute( /*set3D=*/false, helper );
3648 // -----------------
3649 int nbNoImpSteps = 0;
3652 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3654 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3656 int oldBadNb = badNb;
3659 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3661 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3662 /*isCentroidal=*/isConcaveFace,
3663 /*set3D=*/isConcaveFace);
3665 if ( badNb < oldBadNb )
3673 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3675 // No wrongly shaped faces remain; final smooth. Set node XYZ.
3676 // First, find out a needed quality of smoothing (high for quadrangles only)
3679 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
3680 if ( hasTria != hasQuad ) {
3681 highQuality = hasQuad;
3684 set<int> nbNodesSet;
3685 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3686 while ( fIt->more() && nbNodesSet.size() < 2 )
3687 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
3688 highQuality = ( *nbNodesSet.begin() == 4 );
3691 if ( !highQuality && isConcaveFace )
3692 fixBadFaces( F, helper ); // fix narrow faces by swaping diagonals
3693 for ( int st = highQuality ? 10 : 3; st; --st )
3695 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3696 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3697 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3698 /*isCentroidal=*/isConcaveFace,/*set3D=*/st==1 );
3701 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
3702 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
3704 if ( !getMeshDS()->IsEmbeddedMode() )
3705 // Log node movement
3706 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3708 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
3709 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
3712 } // loop on FACES to srink mesh on
3715 // Replace source nodes by target nodes in shrinked mesh edges
3717 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3718 for ( ; e2shr != e2shrMap.end(); ++e2shr )
3719 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3724 //================================================================================
3726 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3728 //================================================================================
3730 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
3731 const TopoDS_Face& F,
3732 SMESH_MesherHelper& helper,
3733 const SMESHDS_SubMesh* faceSubMesh)
3735 const SMDS_MeshNode* srcNode = edge._nodes[0];
3736 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3740 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3742 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3743 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3744 gp_Vec2d uvDir( srcUV, tgtUV );
3745 double uvLen = uvDir.Magnitude();
3747 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3749 // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3750 vector<const SMDS_MeshElement*> faces;
3751 multimap< double, const SMDS_MeshNode* > proj2node;
3752 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3753 while ( fIt->more() )
3755 const SMDS_MeshElement* f = fIt->next();
3756 if ( faceSubMesh->Contains( f ))
3757 faces.push_back( f );
3759 for ( unsigned i = 0; i < faces.size(); ++i )
3761 const int nbNodes = faces[i]->NbCornerNodes();
3762 for ( int j = 0; j < nbNodes; ++j )
3764 const SMDS_MeshNode* n = faces[i]->GetNode(j);
3765 if ( n == srcNode ) continue;
3766 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3767 ( faces.size() > 1 || nbNodes > 3 ))
3769 gp_Pnt2d uv = helper.GetNodeUV( F, n );
3770 gp_Vec2d uvDirN( srcUV, uv );
3771 double proj = uvDirN * uvDir;
3772 proj2node.insert( make_pair( proj, n ));
3776 multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
3777 const double minProj = p2n->first;
3778 const double projThreshold = 1.1 * uvLen;
3779 if ( minProj > projThreshold )
3781 // tgtNode is located so that it does not make faces with wrong orientation
3784 edge._pos.resize(1);
3785 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
3787 // store most risky nodes in _simplices
3788 p2nEnd = proj2node.lower_bound( projThreshold );
3789 int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
3790 edge._simplices.resize( nbSimpl );
3791 for ( int i = 0; i < nbSimpl; ++i )
3793 edge._simplices[i]._nPrev = p2n->second;
3794 if ( ++p2n != p2nEnd )
3795 edge._simplices[i]._nNext = p2n->second;
3797 // set UV of source node to target node
3798 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3799 pos->SetUParameter( srcUV.X() );
3800 pos->SetVParameter( srcUV.Y() );
3802 else // _sWOL is TopAbs_EDGE
3804 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
3805 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
3806 if ( !edgeSM || edgeSM->NbElements() == 0 )
3807 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3809 const SMDS_MeshNode* n2 = 0;
3810 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3811 while ( eIt->more() && !n2 )
3813 const SMDS_MeshElement* e = eIt->next();
3814 if ( !edgeSM->Contains(e)) continue;
3815 n2 = e->GetNode( 0 );
3816 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
3819 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3821 double uSrc = helper.GetNodeU( E, srcNode, n2 );
3822 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
3823 double u2 = helper.GetNodeU( E, n2, srcNode );
3825 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
3827 // tgtNode is located so that it does not make faces with wrong orientation
3830 edge._pos.resize(1);
3831 edge._pos[0].SetCoord( U_TGT, uTgt );
3832 edge._pos[0].SetCoord( U_SRC, uSrc );
3833 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
3835 edge._simplices.resize( 1 );
3836 edge._simplices[0]._nPrev = n2;
3838 // set UV of source node to target node
3839 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3840 pos->SetUParameter( uSrc );
3844 //================================================================================
3846 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
3848 //================================================================================
3850 // Compute UV to follow during shrinking
3852 // const SMDS_MeshNode* srcNode = edge._nodes[0];
3853 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
3855 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3856 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3857 // gp_Vec2d uvDir( srcUV, tgtUV );
3858 // double uvLen = uvDir.Magnitude();
3861 // // Select shrinking step such that not to make faces with wrong orientation.
3862 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3863 // const double minStepSize = uvLen / 20;
3864 // double stepSize = uvLen;
3865 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3866 // while ( fIt->more() )
3868 // const SMDS_MeshElement* f = fIt->next();
3869 // if ( !faceSubMesh->Contains( f )) continue;
3870 // const int nbNodes = f->NbCornerNodes();
3871 // for ( int i = 0; i < nbNodes; ++i )
3873 // const SMDS_MeshNode* n = f->GetNode(i);
3874 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
3876 // gp_XY uv = helper.GetNodeUV( F, n );
3877 // gp_Vec2d uvDirN( srcUV, uv );
3878 // double proj = uvDirN * uvDir;
3879 // if ( proj < stepSize && proj > minStepSize )
3885 // const int nbSteps = ceil( uvLen / stepSize );
3886 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
3887 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
3888 // edge._pos.resize( nbSteps );
3889 // edge._pos[0] = tgtUV0;
3890 // for ( int i = 1; i < nbSteps; ++i )
3892 // double r = i / double( nbSteps );
3893 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
3898 //================================================================================
3900 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
3902 //================================================================================
3904 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper)
3906 SMESH::Controls::AspectRatio qualifier;
3907 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
3908 const double maxAspectRatio = 4.;
3910 // find bad triangles
3912 vector< const SMDS_MeshElement* > badTrias;
3913 vector< double > badAspects;
3914 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
3915 SMDS_ElemIteratorPtr fIt = sm->GetElements();
3916 while ( fIt->more() )
3918 const SMDS_MeshElement * f = fIt->next();
3919 if ( f->NbCornerNodes() != 3 ) continue;
3920 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = SMESH_TNodeXYZ( f->GetNode(iP));
3921 double aspect = qualifier.GetValue( points );
3922 if ( aspect > maxAspectRatio )
3924 badTrias.push_back( f );
3925 badAspects.push_back( aspect );
3928 if ( badTrias.empty() )
3931 // find couples of faces to swap diagonal
3933 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
3934 vector< T2Trias > triaCouples;
3936 TIDSortedElemSet involvedFaces, emptySet;
3937 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
3940 double aspRatio [3];
3943 involvedFaces.insert( badTrias[iTia] );
3944 for ( int iP = 0; iP < 3; ++iP )
3945 points(iP+1) = SMESH_TNodeXYZ( badTrias[iTia]->GetNode(iP));
3947 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
3948 int bestCouple = -1;
3949 for ( int iSide = 0; iSide < 3; ++iSide )
3951 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
3952 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
3953 trias [iSide].first = badTrias[iTia];
3954 trias [iSide].second = SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, involvedFaces,
3956 if ( ! trias[iSide].second || trias[iSide].second->NbCornerNodes() != 3 )
3959 // aspect ratio of an adjacent tria
3960 for ( int iP = 0; iP < 3; ++iP )
3961 points2(iP+1) = SMESH_TNodeXYZ( trias[iSide].second->GetNode(iP));
3962 double aspectInit = qualifier.GetValue( points2 );
3964 // arrange nodes as after diag-swaping
3965 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
3966 i3 = helper.WrapIndex( i1-1, 3 );
3968 i3 = helper.WrapIndex( i1+1, 3 );
3970 points1( 1+ iSide ) = points2( 1+ i3 );
3971 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
3973 // aspect ratio after diag-swaping
3974 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
3975 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
3978 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
3982 if ( bestCouple >= 0 )
3984 triaCouples.push_back( trias[bestCouple] );
3985 involvedFaces.insert ( trias[bestCouple].second );
3989 involvedFaces.erase( badTrias[iTia] );
3992 if ( triaCouples.empty() )
3997 SMESH_MeshEditor editor( helper.GetMesh() );
3998 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
3999 for ( size_t i = 0; i < triaCouples.size(); ++i )
4001 dumpChangeNodes( triaCouples[i].first );
4002 dumpChangeNodes( triaCouples[i].second );
4003 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
4007 // just for debug dump resulting triangles
4008 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID());
4009 for ( size_t i = 0; i < triaCouples.size(); ++i )
4011 dumpChangeNodes( triaCouples[i].first );
4012 dumpChangeNodes( triaCouples[i].second );
4016 //================================================================================
4018 * \brief Move target node to it's final position on the FACE during shrinking
4020 //================================================================================
4022 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
4023 const TopoDS_Face& F,
4024 SMESH_MesherHelper& helper )
4027 return false; // already at the target position
4029 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
4031 if ( _sWOL.ShapeType() == TopAbs_FACE )
4033 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
4034 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y());
4035 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4036 const double uvLen = tgtUV.Distance( curUV );
4038 // Select shrinking step such that not to make faces with wrong orientation.
4039 const double kSafe = 0.8;
4040 const double minStepSize = uvLen / 10;
4041 double stepSize = uvLen;
4042 for ( unsigned i = 0; i < _simplices.size(); ++i )
4044 const SMDS_MeshNode* nn[2] = { _simplices[i]._nPrev, _simplices[i]._nNext };
4045 for ( int j = 0; j < 2; ++j )
4046 if ( const SMDS_MeshNode* n = nn[j] )
4048 gp_XY uv = helper.GetNodeUV( F, n );
4049 gp_Vec2d uvDirN( curUV, uv );
4050 double proj = uvDirN * uvDir * kSafe;
4051 if ( proj < stepSize && proj > minStepSize )
4057 if ( stepSize == uvLen )
4064 newUV = curUV + uvDir.XY() * stepSize;
4067 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4068 pos->SetUParameter( newUV.X() );
4069 pos->SetVParameter( newUV.Y() );
4072 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4073 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4074 dumpMove( tgtNode );
4077 else // _sWOL is TopAbs_EDGE
4079 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4080 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4082 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4083 const double uSrc = _pos[0].Coord( U_SRC );
4084 const double lenTgt = _pos[0].Coord( LEN_TGT );
4086 double newU = _pos[0].Coord( U_TGT );
4087 if ( lenTgt < 0.99 * fabs( uSrc-u2 ))
4093 newU = 0.1 * uSrc + 0.9 * u2;
4095 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4096 pos->SetUParameter( newU );
4098 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4099 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4100 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4101 dumpMove( tgtNode );
4107 //================================================================================
4109 * \brief Perform smooth on the FACE
4110 * \retval bool - true if the node has been moved
4112 //================================================================================
4114 bool _SmoothNode::Smooth(int& badNb,
4115 Handle(Geom_Surface)& surface,
4116 SMESH_MesherHelper& helper,
4117 const double refSign,
4121 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4123 // get uv of surrounding nodes
4124 vector<gp_XY> uv( _simplices.size() );
4125 for ( size_t i = 0; i < _simplices.size(); ++i )
4126 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4128 // compute new UV for the node
4130 if ( isCentroidal && _simplices.size() > 3 )
4132 // average centers of diagonals wieghted with their reciprocal lengths
4133 if ( _simplices.size() == 4 )
4135 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4136 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4137 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4141 double sumWeight = 0;
4142 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4143 for ( int i = 0; i < nb; ++i )
4146 int iTo = i + _simplices.size() - 1;
4147 for ( int j = iFrom; j < iTo; ++j )
4149 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4150 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4152 newPos += w * ( uv[i]+uv[i2] );
4155 newPos /= 2 * sumWeight;
4161 isCentroidal = false;
4162 for ( size_t i = 0; i < _simplices.size(); ++i )
4164 newPos /= _simplices.size();
4167 // count quality metrics (orientation) of triangles around the node
4169 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4170 for ( unsigned i = 0; i < _simplices.size(); ++i )
4171 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4174 for ( unsigned i = 0; i < _simplices.size(); ++i )
4175 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4177 if ( nbOkAfter < nbOkBefore )
4179 // if ( isCentroidal )
4180 // return Smooth( badNb, surface, helper, refSign, !isCentroidal, set3D );
4181 badNb += _simplices.size() - nbOkBefore;
4185 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4186 pos->SetUParameter( newPos.X() );
4187 pos->SetVParameter( newPos.Y() );
4194 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4195 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4199 badNb += _simplices.size() - nbOkAfter;
4200 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4203 //================================================================================
4205 * \brief Delete _SolidData
4207 //================================================================================
4209 _SolidData::~_SolidData()
4211 for ( unsigned i = 0; i < _edges.size(); ++i )
4213 if ( _edges[i] && _edges[i]->_2neibors )
4214 delete _edges[i]->_2neibors;
4219 //================================================================================
4221 * \brief Add a _LayerEdge inflated along the EDGE
4223 //================================================================================
4225 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4228 if ( _nodes.empty() )
4230 _edges[0] = _edges[1] = 0;
4234 if ( e == _edges[0] || e == _edges[1] )
4236 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4237 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4238 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4239 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4242 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4244 BRep_Tool::Range( E, f,l );
4245 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4246 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4250 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4251 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4253 if ( _nodes.empty() )
4255 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4256 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4258 TopLoc_Location loc;
4259 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4260 GeomAdaptor_Curve aCurve(C, f,l);
4261 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4263 int nbExpectNodes = eSubMesh->NbNodes();
4264 _initU .reserve( nbExpectNodes );
4265 _normPar.reserve( nbExpectNodes );
4266 _nodes .reserve( nbExpectNodes );
4267 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4268 while ( nIt->more() )
4270 const SMDS_MeshNode* node = nIt->next();
4271 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4272 node == tgtNode0 || node == tgtNode1 )
4273 continue; // refinement nodes
4274 _nodes.push_back( node );
4275 _initU.push_back( helper.GetNodeU( E, node ));
4276 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4277 _normPar.push_back( len / totLen );
4282 // remove target node of the _LayerEdge from _nodes
4284 for ( unsigned i = 0; i < _nodes.size(); ++i )
4285 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4286 _nodes[i] = 0, nbFound++;
4287 if ( nbFound == _nodes.size() )
4292 //================================================================================
4294 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4296 //================================================================================
4298 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4300 if ( _done || _nodes.empty())
4302 const _LayerEdge* e = _edges[0];
4303 if ( !e ) e = _edges[1];
4306 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4307 ( !_edges[1] || _edges[1]->_pos.empty() ));
4309 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4311 if ( set3D || _done )
4313 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4314 GeomAdaptor_Curve aCurve(C, f,l);
4317 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4319 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4320 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4322 for ( unsigned i = 0; i < _nodes.size(); ++i )
4324 if ( !_nodes[i] ) continue;
4325 double len = totLen * _normPar[i];
4326 GCPnts_AbscissaPoint discret( aCurve, len, f );
4327 if ( !discret.IsDone() )
4328 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4329 double u = discret.Parameter();
4330 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4331 pos->SetUParameter( u );
4332 gp_Pnt p = C->Value( u );
4333 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4338 BRep_Tool::Range( E, f,l );
4340 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4342 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4344 for ( unsigned i = 0; i < _nodes.size(); ++i )
4346 if ( !_nodes[i] ) continue;
4347 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4348 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4349 pos->SetUParameter( u );
4354 //================================================================================
4356 * \brief Restore initial parameters of nodes on EDGE
4358 //================================================================================
4360 void _Shrinker1D::RestoreParams()
4363 for ( unsigned i = 0; i < _nodes.size(); ++i )
4365 if ( !_nodes[i] ) continue;
4366 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4367 pos->SetUParameter( _initU[i] );
4372 //================================================================================
4374 * \brief Replace source nodes by target nodes in shrinked mesh edges
4376 //================================================================================
4378 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4380 const SMDS_MeshNode* nodes[3];
4381 for ( int i = 0; i < 2; ++i )
4383 if ( !_edges[i] ) continue;
4385 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4386 if ( !eSubMesh ) return;
4387 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4388 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4389 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4390 while ( eIt->more() )
4392 const SMDS_MeshElement* e = eIt->next();
4393 if ( !eSubMesh->Contains( e ))
4395 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4396 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4398 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4399 nodes[iN] = ( n == srcNode ? tgtNode : n );
4401 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4406 //================================================================================
4408 * \brief Creates 2D and 1D elements on boundaries of new prisms
4410 //================================================================================
4412 bool _ViscousBuilder::addBoundaryElements()
4414 SMESH_MesherHelper helper( *_mesh );
4416 for ( unsigned i = 0; i < _sdVec.size(); ++i )
4418 _SolidData& data = _sdVec[i];
4419 TopTools_IndexedMapOfShape geomEdges;
4420 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4421 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4423 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4425 // Get _LayerEdge's based on E
4427 map< double, const SMDS_MeshNode* > u2nodes;
4428 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4431 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
4432 TNode2Edge & n2eMap = data._n2eMap;
4433 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4435 //check if 2D elements are needed on E
4436 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
4437 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
4438 ledges.push_back( n2e->second );
4440 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
4441 continue; // no layers on E
4442 ledges.push_back( n2eMap[ u2n->second ]);
4444 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
4445 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
4446 int nbSharedPyram = 0;
4447 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
4448 while ( vIt->more() )
4450 const SMDS_MeshElement* v = vIt->next();
4451 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
4453 if ( nbSharedPyram > 1 )
4454 continue; // not free border of the pyramid
4456 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
4457 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
4458 continue; // faces already created
4460 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
4461 ledges.push_back( n2eMap[ u2n->second ]);
4463 // Find out orientation and type of face to create
4465 bool reverse = false, isOnFace;
4467 map< TGeomID, TopoDS_Shape >::iterator e2f =
4468 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
4470 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
4472 F = e2f->second.Oriented( TopAbs_FORWARD );
4473 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
4474 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
4475 reverse = !reverse, F.Reverse();
4476 if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face(F), getMeshDS() ))
4481 // find FACE with layers sharing E
4482 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
4483 while ( fIt->more() && F.IsNull() )
4485 const TopoDS_Shape* pF = fIt->next();
4486 if ( helper.IsSubShape( *pF, data._solid) &&
4487 !_ignoreShapeIds.count( e2f->first ))
4491 // Find the sub-mesh to add new faces
4492 SMESHDS_SubMesh* sm = 0;
4494 sm = getMeshDS()->MeshElements( F );
4496 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
4498 return error("error in addBoundaryElements()", data._index);
4501 const int dj1 = reverse ? 0 : 1;
4502 const int dj2 = reverse ? 1 : 0;
4503 for ( unsigned j = 1; j < ledges.size(); ++j )
4505 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
4506 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
4508 for ( size_t z = 1; z < nn1.size(); ++z )
4509 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
4511 for ( size_t z = 1; z < nn1.size(); ++z )
4512 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
4516 for ( int isFirst = 0; isFirst < 2; ++isFirst )
4518 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
4519 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
4521 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
4522 if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
4524 helper.SetSubShape( edge->_sWOL );
4525 helper.SetElementsOnShape( true );
4526 for ( size_t z = 1; z < nn.size(); ++z )
4527 helper.AddEdge( nn[z-1], nn[z] );