1 // Copyright (C) 2007-2013 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_MeshAlgos.hxx"
40 #include "SMESH_MesherHelper.hxx"
41 #include "SMESH_ProxyMesh.hxx"
42 #include "SMESH_subMesh.hxx"
43 #include "SMESH_subMeshEventListener.hxx"
45 #include <BRepAdaptor_Curve2d.hxx>
46 #include <BRep_Tool.hxx>
47 #include <Bnd_B2d.hxx>
48 #include <Bnd_B3d.hxx>
50 #include <GCPnts_AbscissaPoint.hxx>
51 #include <Geom2d_Circle.hxx>
52 #include <Geom2d_Line.hxx>
53 #include <Geom2d_TrimmedCurve.hxx>
54 #include <GeomAdaptor_Curve.hxx>
55 #include <Geom_Circle.hxx>
56 #include <Geom_Curve.hxx>
57 #include <Geom_Line.hxx>
58 #include <Geom_TrimmedCurve.hxx>
59 #include <Precision.hxx>
60 #include <Standard_ErrorHandler.hxx>
61 #include <TColStd_Array1OfReal.hxx>
63 #include <TopExp_Explorer.hxx>
64 #include <TopTools_IndexedMapOfShape.hxx>
65 #include <TopTools_MapOfShape.hxx>
67 #include <TopoDS_Edge.hxx>
68 #include <TopoDS_Face.hxx>
69 #include <TopoDS_Vertex.hxx>
83 //================================================================================
88 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
91 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
92 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
94 struct _MeshOfSolid : public SMESH_ProxyMesh,
95 public SMESH_subMeshEventListenerData
99 _MeshOfSolid( SMESH_Mesh* mesh)
100 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
102 SMESH_ProxyMesh::setMesh( *mesh );
105 // returns submesh for a geom face
106 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
108 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
109 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
111 void setNode2Node(const SMDS_MeshNode* srcNode,
112 const SMDS_MeshNode* proxyNode,
113 const SMESH_ProxyMesh::SubMesh* subMesh)
115 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
118 //--------------------------------------------------------------------------------
120 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
121 * It is used to clear an inferior dim sub-meshes modified by viscous layers
123 class _ShrinkShapeListener : SMESH_subMeshEventListener
125 _ShrinkShapeListener()
126 : SMESH_subMeshEventListener(/*isDeletable=*/false,
127 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
129 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
130 virtual void ProcessEvent(const int event,
132 SMESH_subMesh* solidSM,
133 SMESH_subMeshEventListenerData* data,
134 const SMESH_Hypothesis* hyp)
136 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
138 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
142 //--------------------------------------------------------------------------------
144 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
145 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
146 * delete the data as soon as it has been used
148 class _ViscousListener : SMESH_subMeshEventListener
151 SMESH_subMeshEventListener(/*isDeletable=*/false,
152 "StdMeshers_ViscousLayers::_ViscousListener") {}
153 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
155 virtual void ProcessEvent(const int event,
157 SMESH_subMesh* subMesh,
158 SMESH_subMeshEventListenerData* data,
159 const SMESH_Hypothesis* hyp)
161 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
163 // delete SMESH_ProxyMesh containing temporary faces
164 subMesh->DeleteEventListener( this );
167 // Finds or creates proxy mesh of the solid
168 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
169 const TopoDS_Shape& solid,
172 if ( !mesh ) return 0;
173 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
174 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
175 if ( !data && toCreate )
177 data = new _MeshOfSolid(mesh);
178 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
179 sm->SetEventListener( Get(), data, sm );
183 // Removes proxy mesh of the solid
184 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
186 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
190 //================================================================================
192 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
193 * the main shape when sub-mesh of the main shape is cleared,
194 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
197 //================================================================================
199 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
201 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
202 SMESH_subMeshEventListenerData* data =
203 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
206 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
207 data->mySubMeshes.end())
208 data->mySubMeshes.push_back( sub );
212 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
213 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
216 //--------------------------------------------------------------------------------
218 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
219 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
220 * The class is used to check validity of face or volumes around a smoothed node;
221 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
225 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
226 const SMDS_MeshNode *_nOpp; // in 2D case, a node opposite to a smoothed node in QUAD
227 _Simplex(const SMDS_MeshNode* nPrev=0,
228 const SMDS_MeshNode* nNext=0,
229 const SMDS_MeshNode* nOpp=0)
230 : _nPrev(nPrev), _nNext(nNext), _nOpp(nOpp) {}
231 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
233 const double M[3][3] =
234 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
235 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
236 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
237 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
238 + M[0][1]*M[1][2]*M[2][0]
239 + M[0][2]*M[1][0]*M[2][1]
240 - M[0][0]*M[1][2]*M[2][1]
241 - M[0][1]*M[1][0]*M[2][2]
242 - M[0][2]*M[1][1]*M[2][0]);
243 return determinant > 1e-100;
245 bool IsForward(const gp_XY& tgtUV,
246 const SMDS_MeshNode* smoothedNode,
247 const TopoDS_Face& face,
248 SMESH_MesherHelper& helper,
249 const double refSign) const
251 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
252 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
253 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
255 return d*refSign > 1e-100;
257 bool IsNeighbour(const _Simplex& other) const
259 return _nPrev == other._nNext || _nNext == other._nPrev;
262 //--------------------------------------------------------------------------------
264 * Structure used to take into account surface curvature while smoothing
269 double _k; // factor to correct node smoothed position
270 double _h2lenRatio; // avgNormProj / (2*avgDist)
272 static _Curvature* New( double avgNormProj, double avgDist )
275 if ( fabs( avgNormProj / avgDist ) > 1./200 )
278 c->_r = avgDist * avgDist / avgNormProj;
279 c->_k = avgDist * avgDist / c->_r / c->_r;
280 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
281 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
285 double lenDelta(double len) const { return _k * ( _r + len ); }
286 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
289 //--------------------------------------------------------------------------------
291 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
295 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
296 const SMDS_MeshNode* _nodes[2];
297 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
299 double _wgt[2]; // weights of _nodes
300 _LayerEdge* _edges[2];
302 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
305 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
307 std::swap( _nodes[0], _nodes[1] );
308 std::swap( _wgt[0], _wgt[1] );
311 //--------------------------------------------------------------------------------
313 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
314 * and a node of the most internal layer (_nodes.back())
318 vector< const SMDS_MeshNode*> _nodes;
320 gp_XYZ _normal; // to solid surface
321 vector<gp_XYZ> _pos; // points computed during inflation
322 double _len; // length achived with the last step
323 double _cosin; // of angle (_normal ^ surface)
324 double _lenFactor; // to compute _len taking _cosin into account
326 // face or edge w/o layer along or near which _LayerEdge is inflated
328 // simplices connected to the source node (_nodes[0]);
329 // used for smoothing and quality check of _LayerEdge's based on the FACE
330 vector<_Simplex> _simplices;
331 // data for smoothing of _LayerEdge's based on the EDGE
332 _2NearEdges* _2neibors;
334 _Curvature* _curvature;
335 // TODO:: detele _Curvature, _plnNorm
337 void SetNewLength( double len, SMESH_MesherHelper& helper );
338 bool SetNewLength2d( Handle(Geom_Surface)& surface,
339 const TopoDS_Face& F,
340 SMESH_MesherHelper& helper );
341 void SetDataByNeighbors( const SMDS_MeshNode* n1,
342 const SMDS_MeshNode* n2,
343 SMESH_MesherHelper& helper);
344 void InvalidateStep( int curStep );
345 bool Smooth(int& badNb);
346 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
347 const TopoDS_Face& F,
348 SMESH_MesherHelper& helper);
349 bool FindIntersection( SMESH_ElementSearcher& searcher,
351 const double& epsilon,
352 const SMDS_MeshElement** face = 0);
353 bool SegTriaInter( const gp_Ax1& lastSegment,
354 const SMDS_MeshNode* n0,
355 const SMDS_MeshNode* n1,
356 const SMDS_MeshNode* n2,
358 const double& epsilon) const;
359 gp_Ax1 LastSegment(double& segLen) const;
360 bool IsOnEdge() const { return _2neibors; }
361 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
362 void SetCosin( double cosin );
366 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
368 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
369 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
372 //--------------------------------------------------------------------------------
374 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
376 //--------------------------------------------------------------------------------
378 * \brief Data of a SOLID
383 const StdMeshers_ViscousLayers* _hyp;
384 _MeshOfSolid* _proxyMesh;
385 set<TGeomID> _reversedFaceIds;
387 double _stepSize, _stepSizeCoeff;
388 const SMDS_MeshNode* _stepSizeNodes[2];
391 // edges of _n2eMap. We keep same data in two containers because
392 // iteration over the map is 5 time longer than over the vector
393 vector< _LayerEdge* > _edges;
395 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
396 // layers and a FACE w/o layers
397 // value: the shape (FACE or EDGE) to shrink mesh on.
398 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
399 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
401 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
402 set< TGeomID > _noShrinkFaces;
404 // <EDGE to smooth on> to <it's curve>
405 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
407 // end indices in _edges of _LayerEdge on one shape to smooth
408 vector< int > _endEdgeToSmooth;
410 double _epsilon; // precision for SegTriaInter()
412 int _index; // for debug
414 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
415 const StdMeshers_ViscousLayers* h=0,
416 _MeshOfSolid* m=0) :_solid(s), _hyp(h), _proxyMesh(m) {}
419 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
422 Handle(Geom_Surface)& surface,
423 const TopoDS_Face& F,
424 SMESH_MesherHelper& helper);
426 //--------------------------------------------------------------------------------
428 * \brief Data of node on a shrinked FACE
432 const SMDS_MeshNode* _node;
433 //vector<const SMDS_MeshNode*> _nodesAround;
434 vector<_Simplex> _simplices; // for quality check
436 enum SmoothType { LAPLACIAN, CENTROIDAL, ANGULAR };
438 bool Smooth(int& badNb,
439 Handle(Geom_Surface)& surface,
440 SMESH_MesherHelper& helper,
441 const double refSign,
445 gp_XY computeAngularPos(vector<gp_XY>& uv,
446 const gp_XY& uvToFix,
447 const double refSign );
449 //--------------------------------------------------------------------------------
451 * \brief Builder of viscous layers
453 class _ViscousBuilder
458 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
459 const TopoDS_Shape& shape);
461 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
462 void RestoreListeners();
464 // computes SMESH_ProxyMesh::SubMesh::_n2n;
465 bool MakeN2NMap( _MeshOfSolid* pm );
469 bool findSolidsWithLayers();
470 bool findFacesWithLayers();
471 bool makeLayer(_SolidData& data);
472 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
473 SMESH_MesherHelper& helper, _SolidData& data);
474 bool findNeiborsOnEdge(const _LayerEdge* edge,
475 const SMDS_MeshNode*& n1,
476 const SMDS_MeshNode*& n2,
478 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
479 const set<TGeomID>& ingnoreShapes,
480 const _SolidData* dataToCheckOri = 0,
481 const bool toSort = false);
482 bool sortEdges( _SolidData& data,
483 vector< vector<_LayerEdge*> >& edgesByGeom);
484 void limitStepSize( _SolidData& data,
485 const SMDS_MeshElement* face,
487 void limitStepSize( _SolidData& data, const double minSize);
488 bool inflate(_SolidData& data);
489 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
490 bool smoothAnalyticEdge( _SolidData& data,
493 Handle(Geom_Surface)& surface,
494 const TopoDS_Face& F,
495 SMESH_MesherHelper& helper);
496 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
497 bool refine(_SolidData& data);
499 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
500 SMESH_MesherHelper& helper,
501 const SMESHDS_SubMesh* faceSubMesh );
502 void fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper);
503 bool addBoundaryElements();
505 bool error( const string& text, int solidID=-1 );
506 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
509 void makeGroupOfLE();
512 SMESH_ComputeErrorPtr _error;
514 vector< _SolidData > _sdVec;
515 set<TGeomID> _ignoreShapeIds;
518 //--------------------------------------------------------------------------------
520 * \brief Shrinker of nodes on the EDGE
524 vector<double> _initU;
525 vector<double> _normPar;
526 vector<const SMDS_MeshNode*> _nodes;
527 const _LayerEdge* _edges[2];
530 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
531 void Compute(bool set3D, SMESH_MesherHelper& helper);
532 void RestoreParams();
533 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
535 //--------------------------------------------------------------------------------
537 * \brief Class of temporary mesh face.
538 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
539 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
541 struct TmpMeshFace : public SMDS_MeshElement
543 vector<const SMDS_MeshNode* > _nn;
544 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
545 SMDS_MeshElement(id), _nn(nodes) {}
546 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
547 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
548 virtual vtkIdType GetVtkType() const { return -1; }
549 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
550 virtual SMDSAbs_GeometryType GetGeomType() const { return SMDSGeom_TRIANGLE; }
551 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const
552 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
554 //--------------------------------------------------------------------------------
556 * \brief Class of temporary mesh face storing _LayerEdge it's based on
558 struct TmpMeshFaceOnEdge : public TmpMeshFace
560 _LayerEdge *_le1, *_le2;
561 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
562 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
564 _nn[0]=_le1->_nodes[0];
565 _nn[1]=_le1->_nodes.back();
566 _nn[2]=_le2->_nodes.back();
567 _nn[3]=_le2->_nodes[0];
570 } // namespace VISCOUS_3D
572 //================================================================================
573 // StdMeshers_ViscousLayers hypothesis
575 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
576 :SMESH_Hypothesis(hypId, studyId, gen),
577 _isToIgnoreShapes(18), _nbLayers(1), _thickness(1), _stretchFactor(1)
579 _name = StdMeshers_ViscousLayers::GetHypType();
580 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
581 } // --------------------------------------------------------------------------------
582 void StdMeshers_ViscousLayers::SetBndShapes(const std::vector<int>& faceIds, bool toIgnore)
584 if ( faceIds != _shapeIds )
585 _shapeIds = faceIds, NotifySubMeshesHypothesisModification();
586 if ( _isToIgnoreShapes != toIgnore )
587 _isToIgnoreShapes = toIgnore, NotifySubMeshesHypothesisModification();
588 } // --------------------------------------------------------------------------------
589 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
591 if ( thickness != _thickness )
592 _thickness = thickness, NotifySubMeshesHypothesisModification();
593 } // --------------------------------------------------------------------------------
594 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
596 if ( _nbLayers != nb )
597 _nbLayers = nb, NotifySubMeshesHypothesisModification();
598 } // --------------------------------------------------------------------------------
599 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
601 if ( _stretchFactor != factor )
602 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
603 } // --------------------------------------------------------------------------------
605 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
606 const TopoDS_Shape& theShape,
607 const bool toMakeN2NMap) const
609 using namespace VISCOUS_3D;
610 _ViscousBuilder bulder;
611 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
612 if ( err && !err->IsOK() )
613 return SMESH_ProxyMesh::Ptr();
615 vector<SMESH_ProxyMesh::Ptr> components;
616 TopExp_Explorer exp( theShape, TopAbs_SOLID );
617 for ( ; exp.More(); exp.Next() )
619 if ( _MeshOfSolid* pm =
620 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
622 if ( toMakeN2NMap && !pm->_n2nMapComputed )
623 if ( !bulder.MakeN2NMap( pm ))
624 return SMESH_ProxyMesh::Ptr();
625 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
626 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
628 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
630 switch ( components.size() )
634 case 1: return components[0];
636 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
638 return SMESH_ProxyMesh::Ptr();
639 } // --------------------------------------------------------------------------------
640 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
642 save << " " << _nbLayers
644 << " " << _stretchFactor
645 << " " << _shapeIds.size();
646 for ( unsigned i = 0; i < _shapeIds.size(); ++i )
647 save << " " << _shapeIds[i];
648 save << " " << !_isToIgnoreShapes; // negate to keep the behavior in old studies.
650 } // --------------------------------------------------------------------------------
651 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
653 int nbFaces, faceID, shapeToTreat;
654 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
655 while ( _shapeIds.size() < nbFaces && load >> faceID )
656 _shapeIds.push_back( faceID );
657 if ( load >> shapeToTreat )
658 _isToIgnoreShapes = !shapeToTreat;
660 _isToIgnoreShapes = true; // old behavior
662 } // --------------------------------------------------------------------------------
663 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
664 const TopoDS_Shape& theShape)
669 // END StdMeshers_ViscousLayers hypothesis
670 //================================================================================
674 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
678 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
679 gp_Pnt p = BRep_Tool::Pnt( fromV );
680 double distF = p.SquareDistance( c->Value( f ));
681 double distL = p.SquareDistance( c->Value( l ));
682 c->D1(( distF < distL ? f : l), p, dir );
683 if ( distL < distF ) dir.Reverse();
686 //--------------------------------------------------------------------------------
687 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
688 SMESH_MesherHelper& helper)
691 double f,l; gp_Pnt p;
692 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
693 double u = helper.GetNodeU( E, atNode );
697 //--------------------------------------------------------------------------------
698 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
699 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
701 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
702 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
703 gp_Pnt p; gp_Vec du, dv, norm;
704 surface->D1( uv.X(),uv.Y(), p, du,dv );
708 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
709 double u = helper.GetNodeU( fromE, node, 0, &ok );
711 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
712 if ( o == TopAbs_REVERSED )
715 gp_Vec dir = norm ^ du;
717 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
718 helper.IsClosedEdge( fromE ))
720 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
721 else c->D1( f, p, dv );
722 if ( o == TopAbs_REVERSED )
724 gp_Vec dir2 = norm ^ dv;
725 dir = dir.Normalized() + dir2.Normalized();
729 //--------------------------------------------------------------------------------
730 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
731 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
732 bool& ok, double* cosin=0)
734 double f,l; TopLoc_Location loc;
735 vector< TopoDS_Edge > edges; // sharing a vertex
736 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
739 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
740 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
741 edges.push_back( *e );
744 if ( !( ok = ( edges.size() > 0 ))) return dir;
745 // get average dir of edges going fromV
747 //if ( edges.size() > 1 )
748 for ( unsigned i = 0; i < edges.size(); ++i )
750 edgeDir = getEdgeDir( edges[i], fromV );
751 double size2 = edgeDir.SquareModulus();
752 if ( size2 > numeric_limits<double>::min() )
753 edgeDir /= sqrt( size2 );
758 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
759 if ( edges.size() == 1 )
761 else if ( dir.SquareModulus() < 0.1 ) // ~< 20 degrees
762 dir = fromEdgeDir + getFaceDir( F, edges[1], node, helper, ok );
763 else if ( dir * fromEdgeDir < 0 )
767 //dir /= edges.size();
769 double angle = gp_Vec( edgeDir ).Angle( dir );
770 *cosin = cos( angle );
775 //================================================================================
777 * \brief Returns true if a FACE is bound by a concave EDGE
779 //================================================================================
781 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
785 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
786 for ( ; eExp.More(); eExp.Next() )
788 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
789 if ( SMESH_Algo::isDegenerated( E )) continue;
790 // check if 2D curve is concave
791 BRepAdaptor_Curve2d curve( E, F );
792 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
793 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
794 curve.Intervals( intervals, GeomAbs_C2 );
795 bool isConvex = true;
796 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
798 double u1 = intervals( i );
799 double u2 = intervals( i+1 );
800 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
801 double cross = drv2 ^ drv1;
802 if ( E.Orientation() == TopAbs_REVERSED )
804 isConvex = ( cross < 1e-9 );
806 // check if concavity is strong enough to care about it
807 //const double maxAngle = 5 * Standard_PI180;
810 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
812 // map< double, const SMDS_MeshNode* > u2nodes;
813 // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
814 // /*ignoreMedium=*/true, u2nodes))
816 // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
817 // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
818 // double uPrev = u2n->first;
819 // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
821 // gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
822 // gp_Vec2d segmentDir( uvPrev, uv );
823 // curve.D1( uPrev, p, drv1 );
825 // if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
830 // uPrev = u2n->first;
836 //--------------------------------------------------------------------------------
837 // DEBUG. Dump intermediate node positions into a python script
842 const char* fname = "/tmp/viscous.py";
843 cout << "execfile('"<<fname<<"')"<<endl;
844 py = new ofstream(fname);
845 *py << "from smesh import *" << endl
846 << "meshSO = GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
847 << "mesh = Mesh( meshSO.GetObject() )"<<endl;
851 *py << "mesh.MakeGroup('Viscous Prisms',VOLUME,FT_ElemGeomType,'=',Geom_PENTA)"<<endl;
854 ~PyDump() { Finish(); }
856 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
857 #define dumpMove(n) { _dumpMove(n, __LINE__);}
858 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
859 void _dumpFunction(const string& fun, int ln)
860 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
861 void _dumpMove(const SMDS_MeshNode* n, int ln)
862 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
863 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
864 void _dumpCmd(const string& txt, int ln)
865 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
866 void dumpFunctionEnd()
867 { if (py) *py<< " return"<< endl; }
868 void dumpChangeNodes( const SMDS_MeshElement* f )
869 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
870 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
871 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
873 struct PyDump { void Finish() {} };
874 #define dumpFunction(f) f
877 #define dumpFunctionEnd()
878 #define dumpChangeNodes(f)
882 using namespace VISCOUS_3D;
884 //================================================================================
886 * \brief Constructor of _ViscousBuilder
888 //================================================================================
890 _ViscousBuilder::_ViscousBuilder()
892 _error = SMESH_ComputeError::New(COMPERR_OK);
896 //================================================================================
898 * \brief Stores error description and returns false
900 //================================================================================
902 bool _ViscousBuilder::error(const string& text, int solidId )
904 _error->myName = COMPERR_ALGO_FAILED;
905 _error->myComment = string("Viscous layers builder: ") + text;
908 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
909 if ( !sm && !_sdVec.empty() )
910 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
911 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
913 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
914 if ( smError && smError->myAlgo )
915 _error->myAlgo = smError->myAlgo;
919 makeGroupOfLE(); // debug
924 //================================================================================
926 * \brief At study restoration, restore event listeners used to clear an inferior
927 * dim sub-mesh modified by viscous layers
929 //================================================================================
931 void _ViscousBuilder::RestoreListeners()
936 //================================================================================
938 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
940 //================================================================================
942 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
944 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
945 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
946 for ( ; fExp.More(); fExp.Next() )
948 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
949 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
951 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
953 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
956 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
957 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
959 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
960 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
961 while( prxIt->more() )
963 const SMDS_MeshElement* fSrc = srcIt->next();
964 const SMDS_MeshElement* fPrx = prxIt->next();
965 if ( fSrc->NbNodes() != fPrx->NbNodes())
966 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
967 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
968 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
971 pm->_n2nMapComputed = true;
975 //================================================================================
977 * \brief Does its job
979 //================================================================================
981 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
982 const TopoDS_Shape& theShape)
984 // TODO: set priority of solids during Gen::Compute()
988 // check if proxy mesh already computed
989 TopExp_Explorer exp( theShape, TopAbs_SOLID );
991 return error("No SOLID's in theShape"), _error;
993 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
994 return SMESH_ComputeErrorPtr(); // everything already computed
998 // TODO: ignore already computed SOLIDs
999 if ( !findSolidsWithLayers())
1002 if ( !findFacesWithLayers() )
1005 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1007 if ( ! makeLayer(_sdVec[i]) )
1010 if ( _sdVec[i]._edges.size() == 0 )
1013 if ( ! inflate(_sdVec[i]) )
1016 if ( ! refine(_sdVec[i]) )
1022 addBoundaryElements();
1024 makeGroupOfLE(); // debug
1030 //================================================================================
1032 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1034 //================================================================================
1036 bool _ViscousBuilder::findSolidsWithLayers()
1039 TopTools_IndexedMapOfShape allSolids;
1040 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1041 _sdVec.reserve( allSolids.Extent());
1043 SMESH_Gen* gen = _mesh->GetGen();
1044 for ( int i = 1; i <= allSolids.Extent(); ++i )
1046 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1047 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1048 if ( !algo ) continue;
1049 // TODO: check if algo is hidden
1050 const list <const SMESHDS_Hypothesis *> & allHyps =
1051 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1052 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1053 const StdMeshers_ViscousLayers* viscHyp = 0;
1054 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1055 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1058 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1061 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, proxyMesh ));
1062 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1065 if ( _sdVec.empty() )
1067 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1072 //================================================================================
1076 //================================================================================
1078 bool _ViscousBuilder::findFacesWithLayers()
1080 // collect all faces to ignore defined by hyp
1081 vector<TopoDS_Shape> ignoreFaces;
1082 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1084 vector<TGeomID> ids = _sdVec[i]._hyp->GetBndShapes();
1085 for ( unsigned i = 0; i < ids.size(); ++i )
1087 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
1088 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1090 _ignoreShapeIds.insert( ids[i] );
1091 ignoreFaces.push_back( s );
1096 // ignore internal faces
1097 SMESH_MesherHelper helper( *_mesh );
1098 TopExp_Explorer exp;
1099 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1101 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1102 for ( ; exp.More(); exp.Next() )
1104 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1105 if ( helper.NbAncestors( exp.Current(), *_mesh, TopAbs_SOLID ) > 1 )
1107 _ignoreShapeIds.insert( faceInd );
1108 ignoreFaces.push_back( exp.Current() );
1109 if ( helper.IsReversedSubMesh( TopoDS::Face( exp.Current() )))
1110 _sdVec[i]._reversedFaceIds.insert( faceInd );
1115 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1116 TopTools_IndexedMapOfShape shapes;
1117 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1120 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1121 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1123 const TopoDS_Shape& edge = shapes(iE);
1124 // find 2 faces sharing an edge
1126 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1127 while ( fIt->more())
1129 const TopoDS_Shape* f = fIt->next();
1130 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1131 FF[ int( !FF[0].IsNull()) ] = *f;
1133 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1134 // check presence of layers on them
1136 for ( int j = 0; j < 2; ++j )
1137 ignore[j] = _ignoreShapeIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1138 if ( ignore[0] == ignore[1] ) continue; // nothing interesting
1139 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1141 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1142 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1145 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1146 // the algo of the SOLID sharing the FACE does not support it
1147 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1148 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1150 TopTools_MapOfShape noShrinkVertices;
1151 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1152 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1154 const TopoDS_Shape& fWOL = e2f->second;
1155 TGeomID edgeID = e2f->first;
1156 bool notShrinkFace = false;
1157 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1158 while ( soIt->more())
1160 const TopoDS_Shape* solid = soIt->next();
1161 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1162 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1163 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1164 notShrinkFace = true;
1165 for ( unsigned j = 0; j < _sdVec.size(); ++j )
1167 if ( _sdVec[j]._solid.IsSame( *solid ) )
1168 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1169 notShrinkFace = false;
1172 if ( notShrinkFace )
1174 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1175 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1176 noShrinkVertices.Add( vExp.Current() );
1179 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1180 // to the found not shrinked fWOL's
1181 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1182 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1184 TGeomID edgeID = e2f->first;
1185 TopoDS_Vertex VV[2];
1186 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1187 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1189 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1190 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1199 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1201 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1204 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1205 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1207 const TopoDS_Shape& vertex = shapes(iV);
1208 // find faces WOL sharing the vertex
1209 vector< TopoDS_Shape > facesWOL;
1210 int totalNbFaces = 0;
1211 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1212 while ( fIt->more())
1214 const TopoDS_Shape* f = fIt->next();
1215 const int fID = getMeshDS()->ShapeToIndex( *f );
1216 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1219 if ( _ignoreShapeIds.count ( fID ) && ! _sdVec[i]._noShrinkFaces.count( fID ))
1220 facesWOL.push_back( *f );
1223 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1224 continue; // no layers at this vertex or no WOL
1225 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1226 switch ( facesWOL.size() )
1230 helper.SetSubShape( facesWOL[0] );
1231 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1233 TopoDS_Shape seamEdge;
1234 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1235 while ( eIt->more() && seamEdge.IsNull() )
1237 const TopoDS_Shape* e = eIt->next();
1238 if ( helper.IsRealSeam( *e ) )
1241 if ( !seamEdge.IsNull() )
1243 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1247 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1252 // find an edge shared by 2 faces
1253 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1254 while ( eIt->more())
1256 const TopoDS_Shape* e = eIt->next();
1257 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1258 helper.IsSubShape( *e, facesWOL[1]))
1260 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1266 return error("Not yet supported case", _sdVec[i]._index);
1274 //================================================================================
1276 * \brief Create the inner surface of the viscous layer and prepare data for infation
1278 //================================================================================
1280 bool _ViscousBuilder::makeLayer(_SolidData& data)
1282 // get all sub-shapes to make layers on
1283 set<TGeomID> subIds, faceIds;
1284 subIds = data._noShrinkFaces;
1285 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1286 for ( ; exp.More(); exp.Next() )
1287 if ( ! _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1289 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1290 faceIds.insert( fSubM->GetId() );
1291 SMESH_subMeshIteratorPtr subIt =
1292 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1293 while ( subIt->more() )
1294 subIds.insert( subIt->next()->GetId() );
1297 // make a map to find new nodes on sub-shapes shared with other SOLID
1298 map< TGeomID, TNode2Edge* > s2neMap;
1299 map< TGeomID, TNode2Edge* >::iterator s2ne;
1300 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1301 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1303 TGeomID shapeInd = s2s->first;
1304 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1306 if ( _sdVec[i]._index == data._index ) continue;
1307 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1308 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1309 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1311 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1317 // Create temporary faces and _LayerEdge's
1319 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1321 data._stepSize = Precision::Infinite();
1322 data._stepSizeNodes[0] = 0;
1324 SMESH_MesherHelper helper( *_mesh );
1325 helper.SetSubShape( data._solid );
1326 helper.SetElementsOnShape(true);
1328 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1329 TNode2Edge::iterator n2e2;
1331 // collect _LayerEdge's of shapes they are based on
1332 const int nbShapes = getMeshDS()->MaxShapeIndex();
1333 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1335 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1337 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1338 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1340 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1341 SMESH_ProxyMesh::SubMesh* proxySub =
1342 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1344 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1345 while ( eIt->more() )
1347 const SMDS_MeshElement* face = eIt->next();
1348 newNodes.resize( face->NbCornerNodes() );
1349 double faceMaxCosin = -1;
1350 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1352 const SMDS_MeshNode* n = face->GetNode(i);
1353 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1354 if ( !(*n2e).second )
1357 _LayerEdge* edge = new _LayerEdge();
1359 edge->_nodes.push_back( n );
1360 const int shapeID = n->getshapeId();
1361 edgesByGeom[ shapeID ].push_back( edge );
1363 // set edge data or find already refined _LayerEdge and get data from it
1364 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1365 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1366 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1368 _LayerEdge* foundEdge = (*n2e2).second;
1369 edge->Copy( *foundEdge, helper );
1370 // location of the last node is modified but we can restore
1371 // it by node position on _sWOL stored by the node
1372 const_cast< SMDS_MeshNode* >
1373 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1377 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1378 if ( !setEdgeData( *edge, subIds, helper, data ))
1381 dumpMove(edge->_nodes.back());
1382 if ( edge->_cosin > 0.01 )
1384 if ( edge->_cosin > faceMaxCosin )
1385 faceMaxCosin = edge->_cosin;
1388 newNodes[ i ] = n2e->second->_nodes.back();
1390 // create a temporary face
1391 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1392 proxySub->AddElement( newFace );
1394 // compute inflation step size by min size of element on a convex surface
1395 if ( faceMaxCosin > 0.1 )
1396 limitStepSize( data, face, faceMaxCosin );
1397 } // loop on 2D elements on a FACE
1398 } // loop on FACEs of a SOLID
1400 data._epsilon = 1e-7;
1401 if ( data._stepSize < 1. )
1402 data._epsilon *= data._stepSize;
1404 // Put _LayerEdge's into the vector data._edges
1406 if ( !sortEdges( data, edgesByGeom ))
1409 // Set target nodes into _Simplex and _2NearEdges
1410 TNode2Edge::iterator n2e;
1411 for ( unsigned i = 0; i < data._edges.size(); ++i )
1413 if ( data._edges[i]->IsOnEdge())
1414 for ( int j = 0; j < 2; ++j )
1416 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1417 break; // _LayerEdge is shared by two _SolidData's
1418 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1419 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1420 return error("_LayerEdge not found by src node", data._index);
1421 n = (*n2e).second->_nodes.back();
1422 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1425 for ( unsigned j = 0; j < data._edges[i]->_simplices.size(); ++j )
1427 _Simplex& s = data._edges[i]->_simplices[j];
1428 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1429 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1437 //================================================================================
1439 * \brief Compute inflation step size by min size of element on a convex surface
1441 //================================================================================
1443 void _ViscousBuilder::limitStepSize( _SolidData& data,
1444 const SMDS_MeshElement* face,
1448 double minSize = 10 * data._stepSize;
1449 const int nbNodes = face->NbCornerNodes();
1450 for ( int i = 0; i < nbNodes; ++i )
1452 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1453 const SMDS_MeshNode* curN = face->GetNode( i );
1454 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1455 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1457 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1458 if ( dist < minSize )
1459 minSize = dist, iN = i;
1462 double newStep = 0.8 * minSize / cosin;
1463 if ( newStep < data._stepSize )
1465 data._stepSize = newStep;
1466 data._stepSizeCoeff = 0.8 / cosin;
1467 data._stepSizeNodes[0] = face->GetNode( iN );
1468 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1472 //================================================================================
1474 * \brief Compute inflation step size by min size of element on a convex surface
1476 //================================================================================
1478 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1480 if ( minSize < data._stepSize )
1482 data._stepSize = minSize;
1483 if ( data._stepSizeNodes[0] )
1486 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1487 data._stepSizeCoeff = data._stepSize / dist;
1492 //================================================================================
1494 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1496 //================================================================================
1498 bool _ViscousBuilder::sortEdges( _SolidData& data,
1499 vector< vector<_LayerEdge*> >& edgesByGeom)
1501 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1502 // boundry inclined at a sharp angle to the shape
1504 list< TGeomID > shapesToSmooth;
1506 SMESH_MesherHelper helper( *_mesh );
1509 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1511 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1512 if ( eS.empty() ) continue;
1513 TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1514 bool needSmooth = false;
1515 switch ( S.ShapeType() )
1519 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1520 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1522 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1523 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1524 if ( eV.empty() ) continue;
1525 double cosin = eV[0]->_cosin;
1527 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1531 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1532 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1534 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1535 eV[0]->_nodes[0], helper, ok);
1536 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1537 double angle = dir1.Angle( dir2 );
1538 cosin = cos( angle );
1540 needSmooth = ( cosin > 0.1 );
1546 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1548 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1549 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1550 if ( eE.empty() ) continue;
1551 if ( eE[0]->_sWOL.IsNull() )
1553 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1554 needSmooth = ( eE[i]->_cosin > 0.1 );
1558 const TopoDS_Face& F1 = TopoDS::Face( S );
1559 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1560 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1561 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1563 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1564 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1565 double angle = dir1.Angle( dir2 );
1566 double cosin = cos( angle );
1567 needSmooth = ( cosin > 0.1 );
1579 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1580 else shapesToSmooth.push_back ( iS );
1583 } // loop on edgesByGeom
1585 data._edges.reserve( data._n2eMap.size() );
1586 data._endEdgeToSmooth.clear();
1588 // first we put _LayerEdge's on shapes to smooth
1589 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1590 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1592 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1593 if ( eVec.empty() ) continue;
1594 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1595 data._endEdgeToSmooth.push_back( data._edges.size() );
1599 // then the rest _LayerEdge's
1600 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1602 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1603 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1610 //================================================================================
1612 * \brief Set data of _LayerEdge needed for smoothing
1613 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1615 //================================================================================
1617 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1618 const set<TGeomID>& subIds,
1619 SMESH_MesherHelper& helper,
1622 SMESH_MeshEditor editor(_mesh);
1624 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1625 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1629 edge._curvature = 0;
1631 // --------------------------
1632 // Compute _normal and _cosin
1633 // --------------------------
1636 edge._normal.SetCoord(0,0,0);
1638 int totalNbFaces = 0;
1640 gp_Vec du, dv, geomNorm;
1643 TGeomID shapeInd = node->getshapeId();
1644 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1645 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1646 TopoDS_Shape vertEdge;
1648 if ( onShrinkShape ) // one of faces the node is on has no layers
1650 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1651 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1653 // inflate from VERTEX along EDGE
1654 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1656 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1658 // inflate from VERTEX along FACE
1659 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1660 node, helper, normOK, &edge._cosin);
1664 // inflate from EDGE along FACE
1665 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1666 node, helper, normOK);
1669 else // layers are on all faces of SOLID the node is on
1671 // find indices of geom faces the node lies on
1672 set<TGeomID> faceIds;
1673 if ( posType == SMDS_TOP_FACE )
1675 faceIds.insert( node->getshapeId() );
1679 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1680 while ( fIt->more() )
1681 faceIds.insert( editor.FindShape(fIt->next()));
1684 set<TGeomID>::iterator id = faceIds.begin();
1686 for ( ; id != faceIds.end(); ++id )
1688 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1689 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1692 //nbLayerFaces += subIds.count( *id );
1693 F = TopoDS::Face( s );
1695 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1696 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1697 surface->D1( uv.X(),uv.Y(), p, du,dv );
1699 double size2 = geomNorm.SquareMagnitude();
1700 if ( size2 > numeric_limits<double>::min() )
1701 geomNorm /= sqrt( size2 );
1704 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1706 edge._normal += geomNorm.XYZ();
1708 if ( totalNbFaces == 0 )
1709 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1711 edge._normal /= totalNbFaces;
1716 edge._cosin = 0; break;
1718 case SMDS_TOP_EDGE: {
1719 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1720 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1721 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1722 edge._cosin = cos( angle );
1723 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1726 case SMDS_TOP_VERTEX: {
1727 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1728 gp_XYZ inFaceDir = getFaceDir( F, V, node, helper, normOK);
1729 double angle = gp_Vec( inFaceDir).Angle( edge._normal ); // [0,PI]
1730 edge._cosin = cos( angle );
1731 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1735 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1739 double normSize = edge._normal.SquareModulus();
1740 if ( normSize < numeric_limits<double>::min() )
1741 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1743 edge._normal /= sqrt( normSize );
1745 // TODO: if ( !normOK ) then get normal by mesh faces
1747 // Set the rest data
1748 // --------------------
1749 if ( onShrinkShape )
1751 edge._sWOL = (*s2s).second;
1753 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1754 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1755 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1757 // set initial position which is parameters on _sWOL in this case
1758 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1760 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1761 edge._pos.push_back( gp_XYZ( u, 0, 0));
1762 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1766 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1767 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1768 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1773 edge._pos.push_back( SMESH_TNodeXYZ( node ));
1775 if ( posType == SMDS_TOP_FACE )
1777 getSimplices( node, edge._simplices, _ignoreShapeIds, &data );
1778 double avgNormProj = 0, avgLen = 0;
1779 for ( unsigned i = 0; i < edge._simplices.size(); ++i )
1781 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
1782 avgNormProj += edge._normal * vec;
1783 avgLen += vec.Modulus();
1785 avgNormProj /= edge._simplices.size();
1786 avgLen /= edge._simplices.size();
1787 edge._curvature = _Curvature::New( avgNormProj, avgLen );
1791 // Set neighbour nodes for a _LayerEdge based on EDGE
1793 if ( posType == SMDS_TOP_EDGE /*||
1794 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1796 edge._2neibors = new _2NearEdges;
1797 // target node instead of source ones will be set later
1798 if ( ! findNeiborsOnEdge( &edge,
1799 edge._2neibors->_nodes[0],
1800 edge._2neibors->_nodes[1],
1803 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1804 edge._2neibors->_nodes[1],
1808 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1813 //================================================================================
1815 * \brief Find 2 neigbor nodes of a node on EDGE
1817 //================================================================================
1819 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
1820 const SMDS_MeshNode*& n1,
1821 const SMDS_MeshNode*& n2,
1824 const SMDS_MeshNode* node = edge->_nodes[0];
1825 const int shapeInd = node->getshapeId();
1826 SMESHDS_SubMesh* edgeSM = 0;
1827 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
1830 edgeSM = getMeshDS()->MeshElements( shapeInd );
1831 if ( !edgeSM || edgeSM->NbElements() == 0 )
1832 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
1836 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
1837 while ( eIt->more() && !n2 )
1839 const SMDS_MeshElement* e = eIt->next();
1840 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
1841 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
1844 if (!edgeSM->Contains(e)) continue;
1848 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
1849 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
1851 ( iN++ ? n2 : n1 ) = nNeibor;
1854 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
1858 //================================================================================
1860 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
1862 //================================================================================
1864 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
1865 const SMDS_MeshNode* n2,
1866 SMESH_MesherHelper& helper)
1868 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1871 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
1872 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
1873 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
1877 double sumLen = vec1.Modulus() + vec2.Modulus();
1878 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
1879 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
1880 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
1881 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
1882 if ( _curvature ) delete _curvature;
1883 _curvature = _Curvature::New( avgNormProj, avgLen );
1885 // if ( _curvature )
1886 // cout << _nodes[0]->GetID()
1887 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
1888 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
1889 // << _curvature->lenDelta(0) << endl;
1894 if ( _sWOL.IsNull() )
1896 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
1897 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
1898 gp_XYZ plnNorm = dirE ^ _normal;
1899 double proj0 = plnNorm * vec1;
1900 double proj1 = plnNorm * vec2;
1901 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
1903 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
1904 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
1909 //================================================================================
1911 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
1912 * this and other _LayerEdge's are inflated along a FACE or an EDGE
1914 //================================================================================
1916 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
1918 _nodes = other._nodes;
1919 _normal = other._normal;
1921 _lenFactor = other._lenFactor;
1922 _cosin = other._cosin;
1923 _sWOL = other._sWOL;
1924 _2neibors = other._2neibors;
1925 _curvature = 0; std::swap( _curvature, other._curvature );
1926 _2neibors = 0; std::swap( _2neibors, other._2neibors );
1928 if ( _sWOL.ShapeType() == TopAbs_EDGE )
1930 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
1931 _pos.push_back( gp_XYZ( u, 0, 0));
1935 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
1936 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1940 //================================================================================
1942 * \brief Set _cosin and _lenFactor
1944 //================================================================================
1946 void _LayerEdge::SetCosin( double cosin )
1949 _lenFactor = ( _cosin > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
1952 //================================================================================
1954 * \brief Fills a vector<_Simplex >
1956 //================================================================================
1958 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
1959 vector<_Simplex>& simplices,
1960 const set<TGeomID>& ingnoreShapes,
1961 const _SolidData* dataToCheckOri,
1964 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1965 while ( fIt->more() )
1967 const SMDS_MeshElement* f = fIt->next();
1968 const TGeomID shapeInd = f->getshapeId();
1969 if ( ingnoreShapes.count( shapeInd )) continue;
1970 const int nbNodes = f->NbCornerNodes();
1971 int srcInd = f->GetNodeIndex( node );
1972 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
1973 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
1974 const SMDS_MeshNode* nOpp = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+2, nbNodes ));
1975 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
1976 std::swap( nPrev, nNext );
1977 simplices.push_back( _Simplex( nPrev, nNext, nOpp ));
1982 vector<_Simplex> sortedSimplices( simplices.size() );
1983 sortedSimplices[0] = simplices[0];
1985 for ( size_t i = 1; i < simplices.size(); ++i )
1987 for ( size_t j = 1; j < simplices.size(); ++j )
1988 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
1990 sortedSimplices[i] = simplices[j];
1995 if ( nbFound == simplices.size() - 1 )
1996 simplices.swap( sortedSimplices );
2000 //================================================================================
2002 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
2004 //================================================================================
2006 void _ViscousBuilder::makeGroupOfLE()
2009 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
2011 if ( _sdVec[i]._edges.empty() ) continue;
2012 // string name = SMESH_Comment("_LayerEdge's_") << i;
2014 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
2015 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
2016 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
2018 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
2019 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2021 _LayerEdge* le = _sdVec[i]._edges[j];
2022 for ( unsigned iN = 1; iN < le->_nodes.size(); ++iN )
2023 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
2024 << ", " << le->_nodes[iN]->GetID() <<"])");
2025 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
2029 dumpFunction( SMESH_Comment("makeNormals") << i );
2030 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2032 _LayerEdge& edge = *_sdVec[i]._edges[j];
2033 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2034 nXYZ += edge._normal * _sdVec[i]._stepSize;
2035 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2036 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2040 // name = SMESH_Comment("tmp_faces ") << i;
2041 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2042 // gDS = (SMESHDS_Group*)g->GetGroupDS();
2043 // SMESH_MeshEditor editor( _mesh );
2044 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2045 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2046 for ( ; fExp.More(); fExp.Next() )
2048 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2050 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2051 while ( fIt->more())
2053 const SMDS_MeshElement* e = fIt->next();
2054 SMESH_Comment cmd("mesh.AddFace([");
2055 for ( int j=0; j < e->NbCornerNodes(); ++j )
2056 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2058 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2059 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2068 //================================================================================
2070 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2072 //================================================================================
2074 bool _ViscousBuilder::inflate(_SolidData& data)
2076 SMESH_MesherHelper helper( *_mesh );
2078 // Limit inflation step size by geometry size found by itersecting
2079 // normals of _LayerEdge's with mesh faces
2080 double geomSize = Precision::Infinite(), intersecDist;
2081 auto_ptr<SMESH_ElementSearcher> searcher
2082 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2083 data._proxyMesh->GetFaces( data._solid )) );
2084 for ( unsigned i = 0; i < data._edges.size(); ++i )
2086 if ( data._edges[i]->IsOnEdge() ) continue;
2087 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2088 if ( geomSize > intersecDist && intersecDist > 0 )
2089 geomSize = intersecDist;
2091 if ( data._stepSize > 0.3 * geomSize )
2092 limitStepSize( data, 0.3 * geomSize );
2094 const double tgtThick = data._hyp->GetTotalThickness();
2095 if ( data._stepSize > tgtThick )
2096 limitStepSize( data, tgtThick );
2098 if ( data._stepSize < 1. )
2099 data._epsilon = data._stepSize * 1e-7;
2102 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2105 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2106 int nbSteps = 0, nbRepeats = 0;
2107 while ( 1.01 * avgThick < tgtThick )
2109 // new target length
2110 curThick += data._stepSize;
2111 if ( curThick > tgtThick )
2113 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2117 // Elongate _LayerEdge's
2118 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2119 for ( unsigned i = 0; i < data._edges.size(); ++i )
2121 data._edges[i]->SetNewLength( curThick, helper );
2126 if ( !updateNormals( data, helper ) )
2129 // Improve and check quality
2130 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2134 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2135 for ( unsigned i = 0; i < data._edges.size(); ++i )
2137 data._edges[i]->InvalidateStep( nbSteps+1 );
2141 break; // no more inflating possible
2145 // Evaluate achieved thickness
2147 for ( unsigned i = 0; i < data._edges.size(); ++i )
2148 avgThick += data._edges[i]->_len;
2149 avgThick /= data._edges.size();
2151 cout << "-- Thickness " << avgThick << " reached" << endl;
2154 if ( distToIntersection < avgThick*1.5 )
2157 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2158 << avgThick << " ) * 1.5" << endl;
2163 limitStepSize( data, 0.25 * distToIntersection );
2164 if ( data._stepSizeNodes[0] )
2165 data._stepSize = data._stepSizeCoeff *
2166 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2170 return error("failed at the very first inflation step", data._index);
2175 //================================================================================
2177 * \brief Improve quality of layer inner surface and check intersection
2179 //================================================================================
2181 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2183 double & distToIntersection)
2185 if ( data._endEdgeToSmooth.empty() )
2186 return true; // no shapes needing smoothing
2188 bool moved, improved;
2190 SMESH_MesherHelper helper(*_mesh);
2191 Handle(Geom_Surface) surface;
2195 for ( unsigned iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2198 iEnd = data._endEdgeToSmooth[ iS ];
2200 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2201 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2203 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2204 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2205 helper.SetSubShape( F );
2206 surface = BRep_Tool::Surface( F );
2211 F.Nullify(); surface.Nullify();
2213 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2215 if ( data._edges[ iBeg ]->IsOnEdge() )
2217 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2219 // try a simple solution on an analytic EDGE
2220 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2226 for ( int i = iBeg; i < iEnd; ++i )
2228 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2230 dumpCmd( SMESH_Comment("# end step ")<<step);
2232 while ( moved && step++ < 5 );
2233 //cout << " NB STEPS: " << step << endl;
2240 int step = 0, badNb = 0; moved = true;
2241 while (( ++step <= 5 && moved ) || improved )
2243 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2244 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2245 int oldBadNb = badNb;
2248 for ( int i = iBeg; i < iEnd; ++i )
2249 moved |= data._edges[i]->Smooth(badNb);
2250 improved = ( badNb < oldBadNb );
2257 for ( int i = iBeg; i < iEnd; ++i )
2259 _LayerEdge* edge = data._edges[i];
2260 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2261 for ( unsigned j = 0; j < edge->_simplices.size(); ++j )
2262 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2264 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2265 << " "<< edge->_simplices[j]._nPrev->GetID()
2266 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2274 } // loop on shapes to smooth
2276 // Check if the last segments of _LayerEdge intersects 2D elements;
2277 // checked elements are either temporary faces or faces on surfaces w/o the layers
2279 auto_ptr<SMESH_ElementSearcher> searcher
2280 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2281 data._proxyMesh->GetFaces( data._solid )) );
2283 distToIntersection = Precision::Infinite();
2285 const SMDS_MeshElement* intFace = 0;
2287 const SMDS_MeshElement* closestFace = 0;
2290 for ( unsigned i = 0; i < data._edges.size(); ++i )
2292 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2294 if ( distToIntersection > dist )
2296 distToIntersection = dist;
2299 closestFace = intFace;
2306 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2307 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2308 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2309 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2310 << ") distance = " << distToIntersection<< endl;
2317 //================================================================================
2319 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2320 * _LayerEdge's to be in a consequent order
2322 //================================================================================
2324 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2327 Handle(Geom_Surface)& surface,
2328 const TopoDS_Face& F,
2329 SMESH_MesherHelper& helper)
2331 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2333 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2335 if ( i2curve == _edge2curve.end() )
2337 // sort _LayerEdge's by position on the EDGE
2339 map< double, _LayerEdge* > u2edge;
2340 for ( int i = iFrom; i < iTo; ++i )
2341 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2343 ASSERT( u2edge.size() == iTo - iFrom );
2344 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2345 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2346 _edges[i] = u2e->second;
2348 // set _2neibors according to the new order
2349 for ( int i = iFrom; i < iTo-1; ++i )
2350 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2351 _edges[i]->_2neibors->reverse();
2352 if ( u2edge.size() > 1 &&
2353 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2354 _edges[iTo-1]->_2neibors->reverse();
2357 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2359 TopLoc_Location loc; double f,l;
2361 Handle(Geom_Line) line;
2362 Handle(Geom_Circle) circle;
2363 bool isLine, isCirc;
2364 if ( F.IsNull() ) // 3D case
2366 // check if the EDGE is a line
2367 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2368 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2369 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2371 line = Handle(Geom_Line)::DownCast( curve );
2372 circle = Handle(Geom_Circle)::DownCast( curve );
2373 isLine = (!line.IsNull());
2374 isCirc = (!circle.IsNull());
2376 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2379 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2380 while ( nIt->more() )
2381 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2382 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2384 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2385 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2386 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2387 for ( int i = 0; i < 3 && !isLine; ++i )
2388 isLine = ( size.Coord( i+1 ) <= lineTol );
2390 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2397 // check if the EDGE is a line
2398 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2399 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2400 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2402 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2403 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2404 isLine = (!line2d.IsNull());
2405 isCirc = (!circle2d.IsNull());
2407 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2410 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2411 while ( nIt->more() )
2412 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2413 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2415 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2416 for ( int i = 0; i < 2 && !isLine; ++i )
2417 isLine = ( size.Coord( i+1 ) <= lineTol );
2419 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2425 line = new Geom_Line( gp::OX() ); // only type does matter
2429 gp_Pnt2d p = circle2d->Location();
2430 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2431 circle = new Geom_Circle( ax, 1.); // only center position does matter
2435 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2443 return i2curve->second;
2446 //================================================================================
2448 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2450 //================================================================================
2452 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2455 Handle(Geom_Surface)& surface,
2456 const TopoDS_Face& F,
2457 SMESH_MesherHelper& helper)
2459 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2460 helper.GetMeshDS());
2461 TopoDS_Edge E = TopoDS::Edge( S );
2463 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2464 if ( curve.IsNull() ) return false;
2466 // compute a relative length of segments
2467 vector< double > len( iTo-iFrom+1 );
2469 double curLen, prevLen = len[0] = 1.0;
2470 for ( int i = iFrom; i < iTo; ++i )
2472 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2473 len[i-iFrom+1] = len[i-iFrom] + curLen;
2478 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2480 if ( F.IsNull() ) // 3D
2482 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2483 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2484 for ( int i = iFrom; i < iTo; ++i )
2486 double r = len[i-iFrom] / len.back();
2487 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2488 data._edges[i]->_pos.back() = newPos;
2489 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2490 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2491 dumpMove( tgtNode );
2496 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2497 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2498 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2499 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2501 int iPeriodic = helper.GetPeriodicIndex();
2502 if ( iPeriodic == 1 || iPeriodic == 2 )
2504 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2505 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2506 std::swap( uv0, uv1 );
2509 const gp_XY rangeUV = uv1 - uv0;
2510 for ( int i = iFrom; i < iTo; ++i )
2512 double r = len[i-iFrom] / len.back();
2513 gp_XY newUV = uv0 + r * rangeUV;
2514 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2516 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2517 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2518 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2519 dumpMove( tgtNode );
2521 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2522 pos->SetUParameter( newUV.X() );
2523 pos->SetVParameter( newUV.Y() );
2529 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2531 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2532 gp_Pnt center3D = circle->Location();
2534 if ( F.IsNull() ) // 3D
2536 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2537 data._edges[iTo-1]->_2neibors->_nodes[1] )
2538 return true; // closed EDGE - nothing to do
2540 return false; // TODO ???
2544 const gp_XY center( center3D.X(), center3D.Y() );
2546 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2547 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2548 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2549 gp_Vec2d vec0( center, uv0 );
2550 gp_Vec2d vecM( center, uvM );
2551 gp_Vec2d vec1( center, uv1 );
2552 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2553 double uMidl = vec0.Angle( vecM );
2554 if ( uLast * uMidl < 0. )
2555 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
2556 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2558 gp_Ax2d axis( center, vec0 );
2559 gp_Circ2d circ( axis, radius );
2560 for ( int i = iFrom; i < iTo; ++i )
2562 double newU = uLast * len[i-iFrom] / len.back();
2563 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2564 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2566 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2567 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2568 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2569 dumpMove( tgtNode );
2571 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2572 pos->SetUParameter( newUV.X() );
2573 pos->SetVParameter( newUV.Y() );
2582 //================================================================================
2584 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2585 * _LayerEdge's on neighbor EDGE's
2587 //================================================================================
2589 bool _ViscousBuilder::updateNormals( _SolidData& data,
2590 SMESH_MesherHelper& helper )
2592 // make temporary quadrangles got by extrusion of
2593 // mesh edges along _LayerEdge._normal's
2595 vector< const SMDS_MeshElement* > tmpFaces;
2597 set< SMESH_TLink > extrudedLinks; // contains target nodes
2598 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2600 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2601 for ( unsigned i = 0; i < data._edges.size(); ++i )
2603 _LayerEdge* edge = data._edges[i];
2604 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2605 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2606 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2608 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2609 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2610 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2611 if ( !link_isnew.second )
2613 extrudedLinks.erase( link_isnew.first );
2614 continue; // already extruded and will no more encounter
2616 // look for a _LayerEdge containg tgt2
2617 // _LayerEdge* neiborEdge = 0;
2618 // unsigned di = 0; // check _edges[i+di] and _edges[i-di]
2619 // while ( !neiborEdge && ++di <= data._edges.size() )
2621 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2622 // neiborEdge = data._edges[i+di];
2623 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2624 // neiborEdge = data._edges[i-di];
2626 // if ( !neiborEdge )
2627 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2628 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2630 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2631 tmpFaces.push_back( f );
2633 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2634 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2635 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2640 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2641 // Perform two loops on _LayerEdge on EDGE's:
2642 // 1) to find and fix intersection
2643 // 2) to check that no new intersection appears as result of 1)
2645 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2647 auto_ptr<SMESH_ElementSearcher> searcher
2648 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
2650 // 1) Find intersections
2652 const SMDS_MeshElement* face;
2653 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2654 TLEdge2LEdgeSet edge2CloseEdge;
2656 const double eps = data._epsilon * data._epsilon;
2657 for ( unsigned i = 0; i < data._edges.size(); ++i )
2659 _LayerEdge* edge = data._edges[i];
2660 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2661 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2663 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2664 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2665 ee.insert( f->_le1 );
2666 ee.insert( f->_le2 );
2667 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
2668 edge2CloseEdge[ f->_le1 ].insert( edge );
2669 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
2670 edge2CloseEdge[ f->_le2 ].insert( edge );
2674 // Set _LayerEdge._normal
2676 if ( !edge2CloseEdge.empty() )
2678 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2680 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2681 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2683 _LayerEdge* edge1 = e2ee->first;
2684 _LayerEdge* edge2 = 0;
2685 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
2687 // find EDGEs the edges reside
2689 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2690 if ( S.ShapeType() != TopAbs_EDGE )
2691 continue; // TODO: find EDGE by VERTEX
2692 E1 = TopoDS::Edge( S );
2693 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
2694 while ( E2.IsNull() && eIt != ee.end())
2696 _LayerEdge* e2 = *eIt++;
2697 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2698 if ( S.ShapeType() == TopAbs_EDGE )
2699 E2 = TopoDS::Edge( S ), edge2 = e2;
2701 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2703 // find 3 FACEs sharing 2 EDGEs
2705 TopoDS_Face FF1[2], FF2[2];
2706 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2707 while ( fIt->more() && FF1[1].IsNull())
2709 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2710 if ( helper.IsSubShape( *F, data._solid))
2711 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2713 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2714 while ( fIt->more() && FF2[1].IsNull())
2716 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2717 if ( helper.IsSubShape( *F, data._solid))
2718 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2720 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2721 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2722 std::swap( FF1[0], FF1[1] );
2723 if ( FF2[0].IsSame( FF1[0]) )
2724 std::swap( FF2[0], FF2[1] );
2725 if ( FF1[0].IsNull() || FF2[0].IsNull() )
2728 // // get a new normal for edge1
2730 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2731 if ( edge1->_cosin < 0 )
2732 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2733 if ( edge2->_cosin < 0 )
2734 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2735 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2736 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2737 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2738 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2739 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2740 // newNorm.Normalize();
2742 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2743 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2744 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2745 newNorm.Normalize();
2747 edge1->_normal = newNorm.XYZ();
2749 // update data of edge1 depending on _normal
2750 const SMDS_MeshNode *n1, *n2;
2751 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2752 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2753 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2755 edge1->SetDataByNeighbors( n1, n2, helper );
2757 if ( edge1->_cosin < 0 )
2760 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2761 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2762 edge1->SetCosin( cos( angle ));
2764 // limit data._stepSize
2765 if ( edge1->_cosin > 0.1 )
2767 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2768 while ( fIt->more() )
2769 limitStepSize( data, fIt->next(), edge1->_cosin );
2771 // set new XYZ of target node
2772 edge1->InvalidateStep( 1 );
2774 edge1->SetNewLength( data._stepSize, helper );
2777 // Update normals and other dependent data of not intersecting _LayerEdge's
2778 // neighboring the intersecting ones
2780 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2782 _LayerEdge* edge1 = e2ee->first;
2783 if ( !edge1->_2neibors )
2785 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2787 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2788 if ( edge2CloseEdge.count ( neighbor ))
2789 continue; // j-th neighbor is also intersected
2790 _LayerEdge* prevEdge = edge1;
2791 const int nbSteps = 6;
2792 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2794 if ( !neighbor->_2neibors )
2795 break; // neighbor is on VERTEX
2797 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2798 if ( nextEdge == prevEdge )
2799 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2800 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2801 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
2802 double r = double(step-1)/nbSteps;
2803 if ( !nextEdge->_2neibors )
2806 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2807 newNorm.Normalize();
2809 neighbor->_normal = newNorm;
2810 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2811 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2813 neighbor->InvalidateStep( 1 );
2815 neighbor->SetNewLength( data._stepSize, helper );
2817 // goto the next neighbor
2818 prevEdge = neighbor;
2819 neighbor = nextEdge;
2825 // 2) Check absence of intersections
2828 for ( unsigned i = 0 ; i < tmpFaces.size(); ++i )
2834 //================================================================================
2836 * \brief Looks for intersection of it's last segment with faces
2837 * \param distance - returns shortest distance from the last node to intersection
2839 //================================================================================
2841 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
2843 const double& epsilon,
2844 const SMDS_MeshElement** face)
2846 vector< const SMDS_MeshElement* > suspectFaces;
2848 gp_Ax1 lastSegment = LastSegment(segLen);
2849 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2851 bool segmentIntersected = false;
2852 distance = Precision::Infinite();
2853 int iFace = -1; // intersected face
2854 for ( unsigned j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
2856 const SMDS_MeshElement* face = suspectFaces[j];
2857 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
2858 face->GetNodeIndex( _nodes[0] ) >= 0 )
2859 continue; // face sharing _LayerEdge node
2860 const int nbNodes = face->NbCornerNodes();
2861 bool intFound = false;
2863 SMDS_MeshElement::iterator nIt = face->begin_nodes();
2866 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
2870 const SMDS_MeshNode* tria[3];
2873 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
2876 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
2882 if ( dist < segLen*(1.01) && dist > -(_len-segLen) )
2883 segmentIntersected = true;
2884 if ( distance > dist )
2885 distance = dist, iFace = j;
2888 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
2889 // if ( distance && iFace > -1 )
2891 // // distance is used to limit size of inflation step which depends on
2892 // // whether the intersected face bears viscous layers or not
2893 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
2897 if ( segmentIntersected )
2900 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
2901 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
2902 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
2903 << ", intersection with face ("
2904 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2905 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
2906 << ") distance = " << distance - segLen<< endl;
2912 return segmentIntersected;
2915 //================================================================================
2917 * \brief Returns size and direction of the last segment
2919 //================================================================================
2921 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
2923 // find two non-coincident positions
2924 gp_XYZ orig = _pos.back();
2926 int iPrev = _pos.size() - 2;
2927 while ( iPrev >= 0 )
2929 dir = orig - _pos[iPrev];
2930 if ( dir.SquareModulus() > 1e-100 )
2940 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
2941 segDir.SetDirection( _normal );
2946 gp_Pnt pPrev = _pos[ iPrev ];
2947 if ( !_sWOL.IsNull() )
2949 TopLoc_Location loc;
2950 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2953 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2954 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
2958 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2959 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
2961 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
2963 segDir.SetLocation( pPrev );
2964 segDir.SetDirection( dir );
2965 segLen = dir.Modulus();
2971 //================================================================================
2973 * \brief Test intersection of the last segment with a given triangle
2974 * using Moller-Trumbore algorithm
2975 * Intersection is detected if distance to intersection is less than _LayerEdge._len
2977 //================================================================================
2979 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
2980 const SMDS_MeshNode* n0,
2981 const SMDS_MeshNode* n1,
2982 const SMDS_MeshNode* n2,
2984 const double& EPSILON) const
2986 //const double EPSILON = 1e-6;
2988 gp_XYZ orig = lastSegment.Location().XYZ();
2989 gp_XYZ dir = lastSegment.Direction().XYZ();
2991 SMESH_TNodeXYZ vert0( n0 );
2992 SMESH_TNodeXYZ vert1( n1 );
2993 SMESH_TNodeXYZ vert2( n2 );
2995 /* calculate distance from vert0 to ray origin */
2996 gp_XYZ tvec = orig - vert0;
2998 if ( tvec * dir > EPSILON )
2999 // intersected face is at back side of the temporary face this _LayerEdge belongs to
3002 gp_XYZ edge1 = vert1 - vert0;
3003 gp_XYZ edge2 = vert2 - vert0;
3005 /* begin calculating determinant - also used to calculate U parameter */
3006 gp_XYZ pvec = dir ^ edge2;
3008 /* if determinant is near zero, ray lies in plane of triangle */
3009 double det = edge1 * pvec;
3011 if (det > -EPSILON && det < EPSILON)
3013 double inv_det = 1.0 / det;
3015 /* calculate U parameter and test bounds */
3016 double u = ( tvec * pvec ) * inv_det;
3017 if (u < 0.0 || u > 1.0)
3020 /* prepare to test V parameter */
3021 gp_XYZ qvec = tvec ^ edge1;
3023 /* calculate V parameter and test bounds */
3024 double v = (dir * qvec) * inv_det;
3025 if ( v < 0.0 || u + v > 1.0 )
3028 /* calculate t, ray intersects triangle */
3029 t = (edge2 * qvec) * inv_det;
3031 // if (det < EPSILON)
3034 // /* calculate distance from vert0 to ray origin */
3035 // gp_XYZ tvec = orig - vert0;
3037 // /* calculate U parameter and test bounds */
3038 // double u = tvec * pvec;
3039 // if (u < 0.0 || u > det)
3042 // /* prepare to test V parameter */
3043 // gp_XYZ qvec = tvec ^ edge1;
3045 // /* calculate V parameter and test bounds */
3046 // double v = dir * qvec;
3047 // if (v < 0.0 || u + v > det)
3050 // /* calculate t, scale parameters, ray intersects triangle */
3051 // double t = edge2 * qvec;
3052 // double inv_det = 1.0 / det;
3060 //================================================================================
3062 * \brief Perform smooth of _LayerEdge's based on EDGE's
3063 * \retval bool - true if node has been moved
3065 //================================================================================
3067 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3068 const TopoDS_Face& F,
3069 SMESH_MesherHelper& helper)
3071 ASSERT( IsOnEdge() );
3073 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3074 SMESH_TNodeXYZ oldPos( tgtNode );
3075 double dist01, distNewOld;
3077 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3078 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3079 dist01 = p0.Distance( _2neibors->_nodes[1] );
3081 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3082 double lenDelta = 0;
3085 //lenDelta = _curvature->lenDelta( _len );
3086 lenDelta = _curvature->lenDeltaByDist( dist01 );
3087 newPos.ChangeCoord() += _normal * lenDelta;
3090 distNewOld = newPos.Distance( oldPos );
3094 if ( _2neibors->_plnNorm )
3096 // put newPos on the plane defined by source node and _plnNorm
3097 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3098 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3099 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3101 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3102 _pos.back() = newPos.XYZ();
3106 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3107 gp_XY uv( Precision::Infinite(), 0 );
3108 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3109 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3111 newPos = surface->Value( uv.X(), uv.Y() );
3112 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3115 if ( _curvature && lenDelta < 0 )
3117 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3118 _len -= prevPos.Distance( oldPos );
3119 _len += prevPos.Distance( newPos );
3121 bool moved = distNewOld > dist01/50;
3123 dumpMove( tgtNode ); // debug
3128 //================================================================================
3130 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3131 * \retval bool - true if _tgtNode has been moved
3133 //================================================================================
3135 bool _LayerEdge::Smooth(int& badNb)
3137 if ( _simplices.size() < 2 )
3138 return false; // _LayerEdge inflated along EDGE or FACE
3140 // compute new position for the last _pos
3141 gp_XYZ newPos (0,0,0);
3142 for ( unsigned i = 0; i < _simplices.size(); ++i )
3143 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3144 newPos /= _simplices.size();
3147 newPos += _normal * _curvature->lenDelta( _len );
3149 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3150 // if ( _cosin < -0.1)
3152 // // Avoid decreasing length of edge on concave surface
3153 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3154 // gp_Vec newMove( prevPos, newPos );
3155 // newPos = _pos.back() + newMove.XYZ();
3157 // else if ( _cosin > 0.3 )
3159 // // Avoid increasing length of edge too much
3162 // count quality metrics (orientation) of tetras around _tgtNode
3164 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3165 for ( unsigned i = 0; i < _simplices.size(); ++i )
3166 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3169 for ( unsigned i = 0; i < _simplices.size(); ++i )
3170 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3172 if ( nbOkAfter < nbOkBefore )
3175 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3177 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3178 _len += prevPos.Distance(newPos);
3180 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3181 _pos.back() = newPos;
3183 badNb += _simplices.size() - nbOkAfter;
3190 //================================================================================
3192 * \brief Add a new segment to _LayerEdge during inflation
3194 //================================================================================
3196 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3198 if ( _len - len > -1e-6 )
3200 _pos.push_back( _pos.back() );
3204 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3205 SMESH_TNodeXYZ oldXYZ( n );
3206 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3207 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3209 _pos.push_back( nXYZ );
3211 if ( !_sWOL.IsNull() )
3214 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3216 double u = Precision::Infinite(); // to force projection w/o distance check
3217 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3218 _pos.back().SetCoord( u, 0, 0 );
3219 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3220 pos->SetUParameter( u );
3224 gp_XY uv( Precision::Infinite(), 0 );
3225 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3226 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3227 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3228 pos->SetUParameter( uv.X() );
3229 pos->SetVParameter( uv.Y() );
3231 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3233 dumpMove( n ); //debug
3236 //================================================================================
3238 * \brief Remove last inflation step
3240 //================================================================================
3242 void _LayerEdge::InvalidateStep( int curStep )
3244 if ( _pos.size() > curStep )
3246 _pos.resize( curStep );
3247 gp_Pnt nXYZ = _pos.back();
3248 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3249 if ( !_sWOL.IsNull() )
3251 TopLoc_Location loc;
3252 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3254 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3255 pos->SetUParameter( nXYZ.X() );
3257 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3258 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3262 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3263 pos->SetUParameter( nXYZ.X() );
3264 pos->SetVParameter( nXYZ.Y() );
3265 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3266 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3269 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3274 //================================================================================
3276 * \brief Create layers of prisms
3278 //================================================================================
3280 bool _ViscousBuilder::refine(_SolidData& data)
3282 SMESH_MesherHelper helper( *_mesh );
3283 helper.SetSubShape( data._solid );
3284 helper.SetElementsOnShape(false);
3286 Handle(Geom_Curve) curve;
3287 Handle(Geom_Surface) surface;
3288 TopoDS_Edge geomEdge;
3289 TopoDS_Face geomFace;
3290 TopLoc_Location loc;
3291 double f,l, u/*, distXYZ[4]*/;
3295 for ( unsigned i = 0; i < data._edges.size(); ++i )
3297 _LayerEdge& edge = *data._edges[i];
3299 // get accumulated length of segments
3300 vector< double > segLen( edge._pos.size() );
3302 for ( unsigned j = 1; j < edge._pos.size(); ++j )
3303 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3305 // allocate memory for new nodes if it is not yet refined
3306 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3307 if ( edge._nodes.size() == 2 )
3309 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3311 edge._nodes.back() = tgtNode;
3313 if ( !edge._sWOL.IsNull() )
3315 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3316 // restore position of the last node
3320 geomEdge = TopoDS::Edge( edge._sWOL );
3321 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3322 // double u = helper.GetNodeU( tgtNode );
3323 // p = curve->Value( u );
3327 geomFace = TopoDS::Face( edge._sWOL );
3328 surface = BRep_Tool::Surface( geomFace, loc );
3329 // gp_XY uv = helper.GetNodeUV( tgtNode );
3330 // p = surface->Value( uv.X(), uv.Y() );
3332 // p.Transform( loc );
3333 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3335 // calculate height of the first layer
3337 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3338 const double f = data._hyp->GetStretchFactor();
3339 const int N = data._hyp->GetNumberLayers();
3340 const double fPowN = pow( f, N );
3341 if ( fPowN - 1 <= numeric_limits<double>::min() )
3344 h0 = T * ( f - 1 )/( fPowN - 1 );
3346 const double zeroLen = std::numeric_limits<double>::min();
3348 // create intermediate nodes
3349 double hSum = 0, hi = h0/f;
3351 for ( unsigned iStep = 1; iStep < edge._nodes.size(); ++iStep )
3353 // compute an intermediate position
3356 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3358 int iPrevSeg = iSeg-1;
3359 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3361 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3362 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3364 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3365 if ( !edge._sWOL.IsNull() )
3367 // compute XYZ by parameters <pos>
3371 pos = curve->Value( u ).Transformed(loc);
3375 uv.SetCoord( pos.X(), pos.Y() );
3376 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3379 // create or update the node
3382 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3383 if ( !edge._sWOL.IsNull() )
3386 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3388 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3392 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3397 if ( !edge._sWOL.IsNull() )
3399 // make average pos from new and current parameters
3402 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3403 pos = curve->Value( u ).Transformed(loc);
3407 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3408 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3411 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3416 if ( !getMeshDS()->IsEmbeddedMode() )
3417 // Log node movement
3418 for ( unsigned i = 0; i < data._edges.size(); ++i )
3420 _LayerEdge& edge = *data._edges[i];
3421 SMESH_TNodeXYZ p ( edge._nodes.back() );
3422 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
3425 // TODO: make quadratic prisms and polyhedrons(?)
3427 helper.SetElementsOnShape(true);
3429 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3430 for ( ; exp.More(); exp.Next() )
3432 if ( _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3434 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3435 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3436 vector< vector<const SMDS_MeshNode*>* > nnVec;
3437 while ( fIt->more() )
3439 const SMDS_MeshElement* face = fIt->next();
3440 int nbNodes = face->NbCornerNodes();
3441 nnVec.resize( nbNodes );
3442 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3443 for ( int iN = 0; iN < nbNodes; ++iN )
3445 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3446 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3449 int nbZ = nnVec[0]->size();
3453 for ( int iZ = 1; iZ < nbZ; ++iZ )
3454 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3455 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3458 for ( int iZ = 1; iZ < nbZ; ++iZ )
3459 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3460 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3461 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3462 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3465 return error("Not supported type of element", data._index);
3472 //================================================================================
3474 * \brief Shrink 2D mesh on faces to let space for inflated layers
3476 //================================================================================
3478 bool _ViscousBuilder::shrink()
3480 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3481 // inflated along FACE or EDGE)
3482 map< TGeomID, _SolidData* > f2sdMap;
3483 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
3485 _SolidData& data = _sdVec[i];
3486 TopTools_MapOfShape FFMap;
3487 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3488 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3489 if ( s2s->second.ShapeType() == TopAbs_FACE )
3491 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3493 if ( FFMap.Add( (*s2s).second ))
3494 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3495 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3496 // by StdMeshers_QuadToTriaAdaptor
3497 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3499 SMESH_ProxyMesh::SubMesh* proxySub =
3500 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3501 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3502 while ( fIt->more() )
3503 proxySub->AddElement( fIt->next() );
3504 // as a result 3D algo will use elements from proxySub and not from smDS
3509 SMESH_MesherHelper helper( *_mesh );
3510 helper.ToFixNodeParameters( true );
3513 map< TGeomID, _Shrinker1D > e2shrMap;
3515 // loop on FACES to srink mesh on
3516 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3517 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3519 _SolidData& data = *f2sd->second;
3520 TNode2Edge& n2eMap = data._n2eMap;
3521 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3523 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3525 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3526 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3528 helper.SetSubShape(F);
3530 // ===========================
3531 // Prepare data for shrinking
3532 // ===========================
3534 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3535 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3536 vector < const SMDS_MeshNode* > smoothNodes;
3538 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3539 while ( nIt->more() )
3541 const SMDS_MeshNode* n = nIt->next();
3542 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3543 smoothNodes.push_back( n );
3546 // Find out face orientation
3548 const set<TGeomID> ignoreShapes;
3550 if ( !smoothNodes.empty() )
3552 vector<_Simplex> simplices;
3553 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3554 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3555 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3556 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3557 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3561 // Find _LayerEdge's inflated along F
3562 vector< _LayerEdge* > lEdges;
3564 SMESH_subMeshIteratorPtr subIt =
3565 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3566 while ( subIt->more() )
3568 SMESH_subMesh* sub = subIt->next();
3569 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3570 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3572 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3573 while ( nIt->more() )
3575 _LayerEdge* edge = n2eMap[ nIt->next() ];
3576 lEdges.push_back( edge );
3577 prepareEdgeToShrink( *edge, F, helper, smDS );
3582 // Replace source nodes by target nodes in mesh faces to shrink
3583 const SMDS_MeshNode* nodes[20];
3584 for ( unsigned i = 0; i < lEdges.size(); ++i )
3586 _LayerEdge& edge = *lEdges[i];
3587 const SMDS_MeshNode* srcNode = edge._nodes[0];
3588 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3589 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3590 while ( fIt->more() )
3592 const SMDS_MeshElement* f = fIt->next();
3593 if ( !smDS->Contains( f ))
3595 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3596 for ( int iN = 0; iN < f->NbNodes(); ++iN )
3598 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3599 nodes[iN] = ( n == srcNode ? tgtNode : n );
3601 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3605 // find out if a FACE is concave
3606 const bool isConcaveFace = isConcave( F, helper );
3608 // Create _SmoothNode's on face F
3609 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3611 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3612 const bool sortSimplices = isConcaveFace;
3613 for ( unsigned i = 0; i < smoothNodes.size(); ++i )
3615 const SMDS_MeshNode* n = smoothNodes[i];
3616 nodesToSmooth[ i ]._node = n;
3617 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3618 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, sortSimplices );
3619 // fix up incorrect uv of nodes on the FACE
3620 helper.GetNodeUV( F, n, 0, &isOkUV);
3625 //if ( nodesToSmooth.empty() ) continue;
3627 // Find EDGE's to shrink
3628 set< _Shrinker1D* > eShri1D;
3630 for ( unsigned i = 0; i < lEdges.size(); ++i )
3632 _LayerEdge* edge = lEdges[i];
3633 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3635 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3636 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3637 eShri1D.insert( & srinker );
3638 srinker.AddEdge( edge, helper );
3639 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
3640 // restore params of nodes on EGDE if the EDGE has been already
3641 // srinked while srinking another FACE
3642 srinker.RestoreParams();
3647 // ==================
3648 // Perform shrinking
3649 // ==================
3651 bool shrinked = true;
3652 int badNb, shriStep=0, smooStep=0;
3653 _SmoothNode::SmoothType smoothType
3654 = isConcaveFace ? _SmoothNode::CENTROIDAL : _SmoothNode::LAPLACIAN;
3657 // Move boundary nodes (actually just set new UV)
3658 // -----------------------------------------------
3659 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep++ ); // debug
3661 for ( unsigned i = 0; i < lEdges.size(); ++i )
3663 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3667 // Move nodes on EDGE's
3668 // (XYZ is set as soon as a needed length reached in SetNewLength2d())
3669 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3670 for ( ; shr != eShri1D.end(); ++shr )
3671 (*shr)->Compute( /*set3D=*/false, helper );
3674 // -----------------
3675 int nbNoImpSteps = 0;
3678 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3680 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3682 int oldBadNb = badNb;
3685 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3687 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3688 smoothType, /*set3D=*/isConcaveFace);
3690 if ( badNb < oldBadNb )
3698 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3701 // No wrongly shaped faces remain; final smooth. Set node XYZ.
3702 bool isStructuredFixed = false;
3703 if ( SMESH_2D_Algo* algo = dynamic_cast<SMESH_2D_Algo*>( sm->GetAlgo() ))
3704 isStructuredFixed = algo->FixInternalNodes( *data._proxyMesh, F );
3705 if ( !isStructuredFixed )
3707 if ( isConcaveFace )
3708 fixBadFaces( F, helper ); // fix narrow faces by swapping diagonals
3709 for ( int st = /*highQuality ? 10 :*/ 3; st; --st )
3711 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3712 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3714 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3715 smoothType,/*set3D=*/st==1 );
3720 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
3721 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
3723 if ( !getMeshDS()->IsEmbeddedMode() )
3724 // Log node movement
3725 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3727 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
3728 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
3731 } // loop on FACES to srink mesh on
3734 // Replace source nodes by target nodes in shrinked mesh edges
3736 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3737 for ( ; e2shr != e2shrMap.end(); ++e2shr )
3738 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3743 //================================================================================
3745 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3747 //================================================================================
3749 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
3750 const TopoDS_Face& F,
3751 SMESH_MesherHelper& helper,
3752 const SMESHDS_SubMesh* faceSubMesh)
3754 const SMDS_MeshNode* srcNode = edge._nodes[0];
3755 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3759 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3761 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3762 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3763 gp_Vec2d uvDir( srcUV, tgtUV );
3764 double uvLen = uvDir.Magnitude();
3766 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3769 // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3770 vector<const SMDS_MeshElement*> faces;
3771 multimap< double, const SMDS_MeshNode* > proj2node;
3772 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3773 while ( fIt->more() )
3775 const SMDS_MeshElement* f = fIt->next();
3776 if ( faceSubMesh->Contains( f ))
3777 faces.push_back( f );
3779 for ( unsigned i = 0; i < faces.size(); ++i )
3781 const int nbNodes = faces[i]->NbCornerNodes();
3782 for ( int j = 0; j < nbNodes; ++j )
3784 const SMDS_MeshNode* n = faces[i]->GetNode(j);
3785 if ( n == srcNode ) continue;
3786 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3787 ( faces.size() > 1 || nbNodes > 3 ))
3789 gp_Pnt2d uv = helper.GetNodeUV( F, n );
3790 gp_Vec2d uvDirN( srcUV, uv );
3791 double proj = uvDirN * uvDir;
3792 proj2node.insert( make_pair( proj, n ));
3796 multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
3797 const double minProj = p2n->first;
3798 const double projThreshold = 1.1 * uvLen;
3799 if ( minProj > projThreshold )
3801 // tgtNode is located so that it does not make faces with wrong orientation
3804 edge._pos.resize(1);
3805 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
3807 // store most risky nodes in _simplices
3808 p2nEnd = proj2node.lower_bound( projThreshold );
3809 int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
3810 edge._simplices.resize( nbSimpl );
3811 for ( int i = 0; i < nbSimpl; ++i )
3813 edge._simplices[i]._nPrev = p2n->second;
3814 if ( ++p2n != p2nEnd )
3815 edge._simplices[i]._nNext = p2n->second;
3817 // set UV of source node to target node
3818 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3819 pos->SetUParameter( srcUV.X() );
3820 pos->SetVParameter( srcUV.Y() );
3822 else // _sWOL is TopAbs_EDGE
3824 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
3825 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
3826 if ( !edgeSM || edgeSM->NbElements() == 0 )
3827 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3829 const SMDS_MeshNode* n2 = 0;
3830 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3831 while ( eIt->more() && !n2 )
3833 const SMDS_MeshElement* e = eIt->next();
3834 if ( !edgeSM->Contains(e)) continue;
3835 n2 = e->GetNode( 0 );
3836 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
3839 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3841 double uSrc = helper.GetNodeU( E, srcNode, n2 );
3842 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
3843 double u2 = helper.GetNodeU( E, n2, srcNode );
3845 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
3847 // tgtNode is located so that it does not make faces with wrong orientation
3850 edge._pos.resize(1);
3851 edge._pos[0].SetCoord( U_TGT, uTgt );
3852 edge._pos[0].SetCoord( U_SRC, uSrc );
3853 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
3855 edge._simplices.resize( 1 );
3856 edge._simplices[0]._nPrev = n2;
3858 // set UV of source node to target node
3859 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3860 pos->SetUParameter( uSrc );
3864 //================================================================================
3866 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
3868 //================================================================================
3870 // Compute UV to follow during shrinking
3872 // const SMDS_MeshNode* srcNode = edge._nodes[0];
3873 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
3875 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3876 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3877 // gp_Vec2d uvDir( srcUV, tgtUV );
3878 // double uvLen = uvDir.Magnitude();
3881 // // Select shrinking step such that not to make faces with wrong orientation.
3882 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3883 // const double minStepSize = uvLen / 20;
3884 // double stepSize = uvLen;
3885 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3886 // while ( fIt->more() )
3888 // const SMDS_MeshElement* f = fIt->next();
3889 // if ( !faceSubMesh->Contains( f )) continue;
3890 // const int nbNodes = f->NbCornerNodes();
3891 // for ( int i = 0; i < nbNodes; ++i )
3893 // const SMDS_MeshNode* n = f->GetNode(i);
3894 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
3896 // gp_XY uv = helper.GetNodeUV( F, n );
3897 // gp_Vec2d uvDirN( srcUV, uv );
3898 // double proj = uvDirN * uvDir;
3899 // if ( proj < stepSize && proj > minStepSize )
3905 // const int nbSteps = ceil( uvLen / stepSize );
3906 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
3907 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
3908 // edge._pos.resize( nbSteps );
3909 // edge._pos[0] = tgtUV0;
3910 // for ( int i = 1; i < nbSteps; ++i )
3912 // double r = i / double( nbSteps );
3913 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
3918 //================================================================================
3920 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
3922 //================================================================================
3924 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper)
3926 SMESH::Controls::AspectRatio qualifier;
3927 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
3928 const double maxAspectRatio = 4.;
3930 // find bad triangles
3932 vector< const SMDS_MeshElement* > badTrias;
3933 vector< double > badAspects;
3934 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
3935 SMDS_ElemIteratorPtr fIt = sm->GetElements();
3936 while ( fIt->more() )
3938 const SMDS_MeshElement * f = fIt->next();
3939 if ( f->NbCornerNodes() != 3 ) continue;
3940 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = SMESH_TNodeXYZ( f->GetNode(iP));
3941 double aspect = qualifier.GetValue( points );
3942 if ( aspect > maxAspectRatio )
3944 badTrias.push_back( f );
3945 badAspects.push_back( aspect );
3948 if ( badTrias.empty() )
3951 // find couples of faces to swap diagonal
3953 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
3954 vector< T2Trias > triaCouples;
3956 TIDSortedElemSet involvedFaces, emptySet;
3957 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
3960 double aspRatio [3];
3963 involvedFaces.insert( badTrias[iTia] );
3964 for ( int iP = 0; iP < 3; ++iP )
3965 points(iP+1) = SMESH_TNodeXYZ( badTrias[iTia]->GetNode(iP));
3967 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
3968 int bestCouple = -1;
3969 for ( int iSide = 0; iSide < 3; ++iSide )
3971 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
3972 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
3973 trias [iSide].first = badTrias[iTia];
3974 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
3976 if ( ! trias[iSide].second || trias[iSide].second->NbCornerNodes() != 3 )
3979 // aspect ratio of an adjacent tria
3980 for ( int iP = 0; iP < 3; ++iP )
3981 points2(iP+1) = SMESH_TNodeXYZ( trias[iSide].second->GetNode(iP));
3982 double aspectInit = qualifier.GetValue( points2 );
3984 // arrange nodes as after diag-swaping
3985 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
3986 i3 = helper.WrapIndex( i1-1, 3 );
3988 i3 = helper.WrapIndex( i1+1, 3 );
3990 points1( 1+ iSide ) = points2( 1+ i3 );
3991 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
3993 // aspect ratio after diag-swaping
3994 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
3995 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
3998 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
4002 if ( bestCouple >= 0 )
4004 triaCouples.push_back( trias[bestCouple] );
4005 involvedFaces.insert ( trias[bestCouple].second );
4009 involvedFaces.erase( badTrias[iTia] );
4012 if ( triaCouples.empty() )
4017 SMESH_MeshEditor editor( helper.GetMesh() );
4018 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
4019 for ( size_t i = 0; i < triaCouples.size(); ++i )
4021 dumpChangeNodes( triaCouples[i].first );
4022 dumpChangeNodes( triaCouples[i].second );
4023 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
4027 // just for debug dump resulting triangles
4028 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID());
4029 for ( size_t i = 0; i < triaCouples.size(); ++i )
4031 dumpChangeNodes( triaCouples[i].first );
4032 dumpChangeNodes( triaCouples[i].second );
4036 //================================================================================
4038 * \brief Move target node to it's final position on the FACE during shrinking
4040 //================================================================================
4042 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
4043 const TopoDS_Face& F,
4044 SMESH_MesherHelper& helper )
4047 return false; // already at the target position
4049 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
4051 if ( _sWOL.ShapeType() == TopAbs_FACE )
4053 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
4054 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y());
4055 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4056 const double uvLen = tgtUV.Distance( curUV );
4058 // Select shrinking step such that not to make faces with wrong orientation.
4059 const double kSafe = 0.8;
4060 const double minStepSize = uvLen / 10;
4061 double stepSize = uvLen;
4062 for ( unsigned i = 0; i < _simplices.size(); ++i )
4064 const SMDS_MeshNode* nn[2] = { _simplices[i]._nPrev, _simplices[i]._nNext };
4065 for ( int j = 0; j < 2; ++j )
4066 if ( const SMDS_MeshNode* n = nn[j] )
4068 gp_XY uv = helper.GetNodeUV( F, n );
4069 gp_Vec2d uvDirN( curUV, uv );
4070 double proj = uvDirN * uvDir * kSafe;
4071 if ( proj < stepSize && proj > minStepSize )
4073 else if ( proj < minStepSize )
4074 stepSize = minStepSize;
4079 if ( uvLen - stepSize < _len / 20. )
4086 newUV = curUV + uvDir.XY() * stepSize;
4089 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4090 pos->SetUParameter( newUV.X() );
4091 pos->SetVParameter( newUV.Y() );
4094 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4095 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4096 dumpMove( tgtNode );
4099 else // _sWOL is TopAbs_EDGE
4101 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4102 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4103 SMDS_EdgePosition* tgtPos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4105 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4106 const double uSrc = _pos[0].Coord( U_SRC );
4107 const double lenTgt = _pos[0].Coord( LEN_TGT );
4109 double newU = _pos[0].Coord( U_TGT );
4110 if ( lenTgt < 0.99 * fabs( uSrc-u2 )) // n2 got out of src-tgt range
4116 newU = 0.1 * tgtPos->GetUParameter() + 0.9 * u2;
4118 tgtPos->SetUParameter( newU );
4120 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4121 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4122 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4123 dumpMove( tgtNode );
4129 //================================================================================
4131 * \brief Perform smooth on the FACE
4132 * \retval bool - true if the node has been moved
4134 //================================================================================
4136 bool _SmoothNode::Smooth(int& badNb,
4137 Handle(Geom_Surface)& surface,
4138 SMESH_MesherHelper& helper,
4139 const double refSign,
4143 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4145 // get uv of surrounding nodes
4146 vector<gp_XY> uv( _simplices.size() );
4147 for ( size_t i = 0; i < _simplices.size(); ++i )
4148 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4150 // compute new UV for the node
4152 /* if ( how == ANGULAR && _simplices.size() == 4 )
4154 vector<gp_XY> corners; corners.reserve(4);
4155 for ( size_t i = 0; i < _simplices.size(); ++i )
4156 if ( _simplices[i]._nOpp )
4157 corners.push_back( helper.GetNodeUV( face, _simplices[i]._nOpp, _node ));
4158 if ( corners.size() == 4 )
4160 newPos = helper.calcTFI
4162 corners[0], corners[1], corners[2], corners[3],
4163 uv[1], uv[2], uv[3], uv[0] );
4165 // vector<gp_XY> p( _simplices.size() * 2 + 1 );
4167 // for ( size_t i = 0; i < _simplices.size(); ++i )
4169 // p.push_back( uv[i] );
4170 // if ( _simplices[i]._nOpp )
4171 // p.push_back( helper.GetNodeUV( face, _simplices[i]._nOpp, _node ));
4173 // newPos = computeAngularPos( p, helper.GetNodeUV( face, _node ), refSign );
4175 else*/ if ( how == CENTROIDAL && _simplices.size() > 3 )
4177 // average centers of diagonals wieghted with their reciprocal lengths
4178 if ( _simplices.size() == 4 )
4180 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4181 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4182 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4186 double sumWeight = 0;
4187 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4188 for ( int i = 0; i < nb; ++i )
4191 int iTo = i + _simplices.size() - 1;
4192 for ( int j = iFrom; j < iTo; ++j )
4194 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4195 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4197 newPos += w * ( uv[i]+uv[i2] );
4200 newPos /= 2 * sumWeight; // 2 is to get a middle between uv's
4206 //isCentroidal = false;
4207 for ( size_t i = 0; i < _simplices.size(); ++i )
4209 newPos /= _simplices.size();
4212 // count quality metrics (orientation) of triangles around the node
4214 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4215 for ( unsigned i = 0; i < _simplices.size(); ++i )
4216 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4219 for ( unsigned i = 0; i < _simplices.size(); ++i )
4220 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4222 if ( nbOkAfter < nbOkBefore )
4224 // if ( isCentroidal )
4225 // return Smooth( badNb, surface, helper, refSign, !isCentroidal, set3D );
4226 badNb += _simplices.size() - nbOkBefore;
4230 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4231 pos->SetUParameter( newPos.X() );
4232 pos->SetVParameter( newPos.Y() );
4239 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4240 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4244 badNb += _simplices.size() - nbOkAfter;
4245 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4248 //================================================================================
4250 * \brief Computes new UV using angle based smoothing technic
4252 //================================================================================
4254 gp_XY _SmoothNode::computeAngularPos(vector<gp_XY>& uv,
4255 const gp_XY& uvToFix,
4256 const double refSign)
4258 uv.push_back( uv.front() );
4260 vector< gp_XY > edgeDir( uv.size() );
4261 vector< double > edgeSize( uv.size() );
4262 for ( size_t i = 1; i < edgeDir.size(); ++i )
4264 edgeDir[i-1] = uv[i] - uv[i-1];
4265 edgeSize[i-1] = edgeDir[i-1].Modulus();
4266 if ( edgeSize[i-1] < numeric_limits<double>::min() )
4267 edgeDir[i-1].SetX( 100 );
4269 edgeDir[i-1] /= edgeSize[i-1] * refSign;
4271 edgeDir.back() = edgeDir.front();
4272 edgeSize.back() = edgeSize.front();
4277 for ( size_t i = 1; i < edgeDir.size(); ++i )
4279 if ( edgeDir[i-1].X() > 1. ) continue;
4281 while ( edgeDir[i].X() > 1. && ++i < edgeDir.size() );
4282 if ( i == edgeDir.size() ) break;
4284 gp_XY norm1( -edgeDir[i1].Y(), edgeDir[i1].X() );
4285 gp_XY norm2( -edgeDir[i].Y(), edgeDir[i].X() );
4286 gp_XY bisec = norm1 + norm2;
4287 double bisecSize = bisec.Modulus();
4288 if ( bisecSize < numeric_limits<double>::min() )
4290 bisec = -edgeDir[i1] + edgeDir[i];
4291 bisecSize = bisec.Modulus();
4295 gp_XY dirToN = uvToFix - p;
4296 double distToN = dirToN.Modulus();
4297 if ( bisec * dirToN < 0 )
4300 newPos += ( p + bisec * distToN ) * ( edgeSize[i1] + edgeSize[i] );
4302 sumSize += edgeSize[i1] + edgeSize[i];
4304 newPos /= /*nbEdges * */sumSize;
4308 //================================================================================
4310 * \brief Delete _SolidData
4312 //================================================================================
4314 _SolidData::~_SolidData()
4316 for ( unsigned i = 0; i < _edges.size(); ++i )
4318 if ( _edges[i] && _edges[i]->_2neibors )
4319 delete _edges[i]->_2neibors;
4324 //================================================================================
4326 * \brief Add a _LayerEdge inflated along the EDGE
4328 //================================================================================
4330 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4333 if ( _nodes.empty() )
4335 _edges[0] = _edges[1] = 0;
4339 if ( e == _edges[0] || e == _edges[1] )
4341 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4342 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4343 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4344 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4347 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4349 BRep_Tool::Range( E, f,l );
4350 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4351 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4355 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4356 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4358 if ( _nodes.empty() )
4360 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4361 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4363 TopLoc_Location loc;
4364 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4365 GeomAdaptor_Curve aCurve(C, f,l);
4366 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4368 int nbExpectNodes = eSubMesh->NbNodes();
4369 _initU .reserve( nbExpectNodes );
4370 _normPar.reserve( nbExpectNodes );
4371 _nodes .reserve( nbExpectNodes );
4372 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4373 while ( nIt->more() )
4375 const SMDS_MeshNode* node = nIt->next();
4376 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4377 node == tgtNode0 || node == tgtNode1 )
4378 continue; // refinement nodes
4379 _nodes.push_back( node );
4380 _initU.push_back( helper.GetNodeU( E, node ));
4381 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4382 _normPar.push_back( len / totLen );
4387 // remove target node of the _LayerEdge from _nodes
4389 for ( unsigned i = 0; i < _nodes.size(); ++i )
4390 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4391 _nodes[i] = 0, nbFound++;
4392 if ( nbFound == _nodes.size() )
4397 //================================================================================
4399 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4401 //================================================================================
4403 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4405 if ( _done || _nodes.empty())
4407 const _LayerEdge* e = _edges[0];
4408 if ( !e ) e = _edges[1];
4411 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4412 ( !_edges[1] || _edges[1]->_pos.empty() ));
4414 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4416 if ( set3D || _done )
4418 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4419 GeomAdaptor_Curve aCurve(C, f,l);
4422 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4424 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4425 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4427 for ( unsigned i = 0; i < _nodes.size(); ++i )
4429 if ( !_nodes[i] ) continue;
4430 double len = totLen * _normPar[i];
4431 GCPnts_AbscissaPoint discret( aCurve, len, f );
4432 if ( !discret.IsDone() )
4433 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4434 double u = discret.Parameter();
4435 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4436 pos->SetUParameter( u );
4437 gp_Pnt p = C->Value( u );
4438 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4443 BRep_Tool::Range( E, f,l );
4445 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4447 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4449 for ( unsigned i = 0; i < _nodes.size(); ++i )
4451 if ( !_nodes[i] ) continue;
4452 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4453 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4454 pos->SetUParameter( u );
4459 //================================================================================
4461 * \brief Restore initial parameters of nodes on EDGE
4463 //================================================================================
4465 void _Shrinker1D::RestoreParams()
4468 for ( unsigned i = 0; i < _nodes.size(); ++i )
4470 if ( !_nodes[i] ) continue;
4471 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4472 pos->SetUParameter( _initU[i] );
4477 //================================================================================
4479 * \brief Replace source nodes by target nodes in shrinked mesh edges
4481 //================================================================================
4483 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4485 const SMDS_MeshNode* nodes[3];
4486 for ( int i = 0; i < 2; ++i )
4488 if ( !_edges[i] ) continue;
4490 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4491 if ( !eSubMesh ) return;
4492 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4493 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4494 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4495 while ( eIt->more() )
4497 const SMDS_MeshElement* e = eIt->next();
4498 if ( !eSubMesh->Contains( e ))
4500 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4501 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4503 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4504 nodes[iN] = ( n == srcNode ? tgtNode : n );
4506 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4511 //================================================================================
4513 * \brief Creates 2D and 1D elements on boundaries of new prisms
4515 //================================================================================
4517 bool _ViscousBuilder::addBoundaryElements()
4519 SMESH_MesherHelper helper( *_mesh );
4521 for ( unsigned i = 0; i < _sdVec.size(); ++i )
4523 _SolidData& data = _sdVec[i];
4524 TopTools_IndexedMapOfShape geomEdges;
4525 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4526 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4528 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4530 // Get _LayerEdge's based on E
4532 map< double, const SMDS_MeshNode* > u2nodes;
4533 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4536 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
4537 TNode2Edge & n2eMap = data._n2eMap;
4538 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4540 //check if 2D elements are needed on E
4541 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
4542 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
4543 ledges.push_back( n2e->second );
4545 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
4546 continue; // no layers on E
4547 ledges.push_back( n2eMap[ u2n->second ]);
4549 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
4550 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
4551 int nbSharedPyram = 0;
4552 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
4553 while ( vIt->more() )
4555 const SMDS_MeshElement* v = vIt->next();
4556 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
4558 if ( nbSharedPyram > 1 )
4559 continue; // not free border of the pyramid
4561 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
4562 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
4563 continue; // faces already created
4565 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
4566 ledges.push_back( n2eMap[ u2n->second ]);
4568 // Find out orientation and type of face to create
4570 bool reverse = false, isOnFace;
4572 map< TGeomID, TopoDS_Shape >::iterator e2f =
4573 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
4575 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
4577 F = e2f->second.Oriented( TopAbs_FORWARD );
4578 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
4579 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
4580 reverse = !reverse, F.Reverse();
4581 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
4586 // find FACE with layers sharing E
4587 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
4588 while ( fIt->more() && F.IsNull() )
4590 const TopoDS_Shape* pF = fIt->next();
4591 if ( helper.IsSubShape( *pF, data._solid) &&
4592 !_ignoreShapeIds.count( e2f->first ))
4596 // Find the sub-mesh to add new faces
4597 SMESHDS_SubMesh* sm = 0;
4599 sm = getMeshDS()->MeshElements( F );
4601 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
4603 return error("error in addBoundaryElements()", data._index);
4606 const int dj1 = reverse ? 0 : 1;
4607 const int dj2 = reverse ? 1 : 0;
4608 for ( unsigned j = 1; j < ledges.size(); ++j )
4610 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
4611 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
4613 for ( size_t z = 1; z < nn1.size(); ++z )
4614 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
4616 for ( size_t z = 1; z < nn1.size(); ++z )
4617 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
4621 for ( int isFirst = 0; isFirst < 2; ++isFirst )
4623 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
4624 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
4626 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
4627 if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
4629 helper.SetSubShape( edge->_sWOL );
4630 helper.SetElementsOnShape( true );
4631 for ( size_t z = 1; z < nn.size(); ++z )
4632 helper.AddEdge( nn[z-1], nn[z] );