1 // Copyright (C) 2007-2012 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_ViscousLayers.cxx
21 // Created : Wed Dec 1 15:15:34 2010
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers.hxx"
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_ControlsDef.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_Mesh.hxx"
39 #include "SMESH_MesherHelper.hxx"
40 #include "SMESH_ProxyMesh.hxx"
41 #include "SMESH_subMesh.hxx"
42 #include "SMESH_subMeshEventListener.hxx"
44 #include "utilities.h"
46 #include <BRepAdaptor_Curve2d.hxx>
47 #include <BRep_Tool.hxx>
48 #include <Bnd_B2d.hxx>
49 #include <Bnd_B3d.hxx>
51 #include <GCPnts_AbscissaPoint.hxx>
52 #include <Geom2d_Circle.hxx>
53 #include <Geom2d_Line.hxx>
54 #include <Geom2d_TrimmedCurve.hxx>
55 #include <GeomAdaptor_Curve.hxx>
56 #include <Geom_Circle.hxx>
57 #include <Geom_Curve.hxx>
58 #include <Geom_Line.hxx>
59 #include <Geom_TrimmedCurve.hxx>
60 #include <Precision.hxx>
61 #include <Standard_ErrorHandler.hxx>
62 #include <TColStd_Array1OfReal.hxx>
64 #include <TopExp_Explorer.hxx>
65 #include <TopTools_IndexedMapOfShape.hxx>
66 #include <TopTools_MapOfShape.hxx>
68 #include <TopoDS_Edge.hxx>
69 #include <TopoDS_Face.hxx>
70 #include <TopoDS_Vertex.hxx>
84 //================================================================================
89 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
92 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
93 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
95 struct _MeshOfSolid : public SMESH_ProxyMesh,
96 public SMESH_subMeshEventListenerData
100 _MeshOfSolid( SMESH_Mesh* mesh)
101 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
103 SMESH_ProxyMesh::setMesh( *mesh );
106 // returns submesh for a geom face
107 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
109 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
110 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
112 void setNode2Node(const SMDS_MeshNode* srcNode,
113 const SMDS_MeshNode* proxyNode,
114 const SMESH_ProxyMesh::SubMesh* subMesh)
116 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
119 //--------------------------------------------------------------------------------
121 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
122 * It is used to clear an inferior dim sub-meshes modified by viscous layers
124 class _ShrinkShapeListener : SMESH_subMeshEventListener
126 _ShrinkShapeListener()
127 : SMESH_subMeshEventListener(/*isDeletable=*/false,
128 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
130 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
131 virtual void ProcessEvent(const int event,
133 SMESH_subMesh* solidSM,
134 SMESH_subMeshEventListenerData* data,
135 const SMESH_Hypothesis* hyp)
137 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
139 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
143 //--------------------------------------------------------------------------------
145 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
146 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
147 * delete the data as soon as it has been used
149 class _ViscousListener : SMESH_subMeshEventListener
152 SMESH_subMeshEventListener(/*isDeletable=*/false,
153 "StdMeshers_ViscousLayers::_ViscousListener") {}
154 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
156 virtual void ProcessEvent(const int event,
158 SMESH_subMesh* subMesh,
159 SMESH_subMeshEventListenerData* data,
160 const SMESH_Hypothesis* hyp)
162 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
164 // delete SMESH_ProxyMesh containing temporary faces
165 subMesh->DeleteEventListener( this );
168 // Finds or creates proxy mesh of the solid
169 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
170 const TopoDS_Shape& solid,
173 if ( !mesh ) return 0;
174 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
175 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
176 if ( !data && toCreate )
178 data = new _MeshOfSolid(mesh);
179 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
180 sm->SetEventListener( Get(), data, sm );
184 // Removes proxy mesh of the solid
185 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
187 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
191 //================================================================================
193 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
194 * the main shape when sub-mesh of the main shape is cleared,
195 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
198 //================================================================================
200 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
202 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
203 SMESH_subMeshEventListenerData* data =
204 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
207 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
208 data->mySubMeshes.end())
209 data->mySubMeshes.push_back( sub );
213 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
214 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
217 //--------------------------------------------------------------------------------
219 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
220 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
221 * The class is used to check validity of face or volumes around a smoothed node;
222 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
226 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
227 _Simplex(const SMDS_MeshNode* nPrev=0, const SMDS_MeshNode* nNext=0)
228 : _nPrev(nPrev), _nNext(nNext) {}
229 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
231 const double M[3][3] =
232 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
233 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
234 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
235 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
236 + M[0][1]*M[1][2]*M[2][0]
237 + M[0][2]*M[1][0]*M[2][1]
238 - M[0][0]*M[1][2]*M[2][1]
239 - M[0][1]*M[1][0]*M[2][2]
240 - M[0][2]*M[1][1]*M[2][0]);
241 return determinant > 1e-100;
243 bool IsForward(const gp_XY& tgtUV,
244 const SMDS_MeshNode* smoothedNode,
245 const TopoDS_Face& face,
246 SMESH_MesherHelper& helper,
247 const double refSign) const
249 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
250 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
251 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
253 return d*refSign > 1e-100;
255 bool IsNeighbour(const _Simplex& other) const
257 return _nPrev == other._nNext || _nNext == other._nPrev;
260 //--------------------------------------------------------------------------------
262 * Structure used to take into account surface curvature while smoothing
267 double _k; // factor to correct node smoothed position
268 double _h2lenRatio; // avgNormProj / (2*avgDist)
270 static _Curvature* New( double avgNormProj, double avgDist )
273 if ( fabs( avgNormProj / avgDist ) > 1./200 )
276 c->_r = avgDist * avgDist / avgNormProj;
277 c->_k = avgDist * avgDist / c->_r / c->_r;
278 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
279 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
283 double lenDelta(double len) const { return _k * ( _r + len ); }
284 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
287 //--------------------------------------------------------------------------------
289 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
293 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
294 const SMDS_MeshNode* _nodes[2];
295 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
297 double _wgt[2]; // weights of _nodes
298 _LayerEdge* _edges[2];
300 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
303 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
305 std::swap( _nodes[0], _nodes[1] );
306 std::swap( _wgt[0], _wgt[1] );
309 //--------------------------------------------------------------------------------
311 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
312 * and a node of the most internal layer (_nodes.back())
316 vector< const SMDS_MeshNode*> _nodes;
318 gp_XYZ _normal; // to solid surface
319 vector<gp_XYZ> _pos; // points computed during inflation
320 double _len; // length achived with the last step
321 double _cosin; // of angle (_normal ^ surface)
322 double _lenFactor; // to compute _len taking _cosin into account
324 // face or edge w/o layer along or near which _LayerEdge is inflated
326 // simplices connected to the source node (_nodes[0]);
327 // used for smoothing and quality check of _LayerEdge's based on the FACE
328 vector<_Simplex> _simplices;
329 // data for smoothing of _LayerEdge's based on the EDGE
330 _2NearEdges* _2neibors;
332 _Curvature* _curvature;
333 // TODO:: detele _Curvature, _plnNorm
335 void SetNewLength( double len, SMESH_MesherHelper& helper );
336 bool SetNewLength2d( Handle(Geom_Surface)& surface,
337 const TopoDS_Face& F,
338 SMESH_MesherHelper& helper );
339 void SetDataByNeighbors( const SMDS_MeshNode* n1,
340 const SMDS_MeshNode* n2,
341 SMESH_MesherHelper& helper);
342 void InvalidateStep( int curStep );
343 bool Smooth(int& badNb);
344 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
345 const TopoDS_Face& F,
346 SMESH_MesherHelper& helper);
347 bool FindIntersection( SMESH_ElementSearcher& searcher,
349 const double& epsilon,
350 const SMDS_MeshElement** face = 0);
351 bool SegTriaInter( const gp_Ax1& lastSegment,
352 const SMDS_MeshNode* n0,
353 const SMDS_MeshNode* n1,
354 const SMDS_MeshNode* n2,
356 const double& epsilon) const;
357 gp_Ax1 LastSegment(double& segLen) const;
358 bool IsOnEdge() const { return _2neibors; }
359 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
360 void SetCosin( double cosin );
364 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
366 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
367 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
370 //--------------------------------------------------------------------------------
372 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
374 //--------------------------------------------------------------------------------
376 * \brief Data of a SOLID
381 const StdMeshers_ViscousLayers* _hyp;
382 _MeshOfSolid* _proxyMesh;
383 set<TGeomID> _reversedFaceIds;
385 double _stepSize, _stepSizeCoeff;
386 const SMDS_MeshNode* _stepSizeNodes[2];
389 // edges of _n2eMap. We keep same data in two containers because
390 // iteration over the map is 5 time longer than over the vector
391 vector< _LayerEdge* > _edges;
393 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
394 // layers and a FACE w/o layers
395 // value: the shape (FACE or EDGE) to shrink mesh on.
396 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
397 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
399 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
400 set< TGeomID > _noShrinkFaces;
402 // <EDGE to smooth on> to <it's curve>
403 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
405 // end indices in _edges of _LayerEdge on one shape to smooth
406 vector< int > _endEdgeToSmooth;
408 double _epsilon; // precision for SegTriaInter()
410 int _index; // for debug
412 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
413 const StdMeshers_ViscousLayers* h=0,
414 _MeshOfSolid* m=0) :_solid(s), _hyp(h), _proxyMesh(m) {}
417 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
420 Handle(Geom_Surface)& surface,
421 const TopoDS_Face& F,
422 SMESH_MesherHelper& helper);
424 //--------------------------------------------------------------------------------
426 * \brief Data of node on a shrinked FACE
430 const SMDS_MeshNode* _node;
431 //vector<const SMDS_MeshNode*> _nodesAround;
432 vector<_Simplex> _simplices; // for quality check
434 bool Smooth(int& badNb,
435 Handle(Geom_Surface)& surface,
436 SMESH_MesherHelper& helper,
437 const double refSign,
441 //--------------------------------------------------------------------------------
443 * \brief Builder of viscous layers
445 class _ViscousBuilder
450 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
451 const TopoDS_Shape& shape);
453 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
454 void RestoreListeners();
456 // computes SMESH_ProxyMesh::SubMesh::_n2n;
457 bool MakeN2NMap( _MeshOfSolid* pm );
461 bool findSolidsWithLayers();
462 bool findFacesWithLayers();
463 bool makeLayer(_SolidData& data);
464 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
465 SMESH_MesherHelper& helper, _SolidData& data);
466 bool findNeiborsOnEdge(const _LayerEdge* edge,
467 const SMDS_MeshNode*& n1,
468 const SMDS_MeshNode*& n2,
470 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
471 const set<TGeomID>& ingnoreShapes,
472 const _SolidData* dataToCheckOri = 0,
473 const bool toSort = false);
474 bool sortEdges( _SolidData& data,
475 vector< vector<_LayerEdge*> >& edgesByGeom);
476 void limitStepSize( _SolidData& data,
477 const SMDS_MeshElement* face,
479 void limitStepSize( _SolidData& data, const double minSize);
480 bool inflate(_SolidData& data);
481 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
482 bool smoothAnalyticEdge( _SolidData& data,
485 Handle(Geom_Surface)& surface,
486 const TopoDS_Face& F,
487 SMESH_MesherHelper& helper);
488 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
489 bool refine(_SolidData& data);
491 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
492 SMESH_MesherHelper& helper,
493 const SMESHDS_SubMesh* faceSubMesh );
494 void fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper);
495 bool addBoundaryElements();
497 bool error( const string& text, int solidID=-1 );
498 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
501 void makeGroupOfLE();
504 SMESH_ComputeErrorPtr _error;
506 vector< _SolidData > _sdVec;
507 set<TGeomID> _ignoreShapeIds;
510 //--------------------------------------------------------------------------------
512 * \brief Shrinker of nodes on the EDGE
516 vector<double> _initU;
517 vector<double> _normPar;
518 vector<const SMDS_MeshNode*> _nodes;
519 const _LayerEdge* _edges[2];
522 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
523 void Compute(bool set3D, SMESH_MesherHelper& helper);
524 void RestoreParams();
525 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
527 //--------------------------------------------------------------------------------
529 * \brief Class of temporary mesh face.
530 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
531 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
533 struct TmpMeshFace : public SMDS_MeshElement
535 vector<const SMDS_MeshNode* > _nn;
536 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
537 SMDS_MeshElement(id), _nn(nodes) {}
538 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
539 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
540 virtual vtkIdType GetVtkType() const { return -1; }
541 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
542 virtual SMDSAbs_GeometryType GetGeomType() const { return SMDSGeom_TRIANGLE; }
543 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const
544 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
546 //--------------------------------------------------------------------------------
548 * \brief Class of temporary mesh face storing _LayerEdge it's based on
550 struct TmpMeshFaceOnEdge : public TmpMeshFace
552 _LayerEdge *_le1, *_le2;
553 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
554 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
556 _nn[0]=_le1->_nodes[0];
557 _nn[1]=_le1->_nodes.back();
558 _nn[2]=_le2->_nodes.back();
559 _nn[3]=_le2->_nodes[0];
562 } // namespace VISCOUS_3D
564 //================================================================================
565 // StdMeshers_ViscousLayers hypothesis
567 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
568 :SMESH_Hypothesis(hypId, studyId, gen),
569 _nbLayers(1), _thickness(1), _stretchFactor(1)
571 _name = StdMeshers_ViscousLayers::GetHypType();
572 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
573 } // --------------------------------------------------------------------------------
574 void StdMeshers_ViscousLayers::SetBndShapesToIgnore(const std::vector<int>& faceIds)
576 if ( faceIds != _ignoreBndShapeIds )
577 _ignoreBndShapeIds = faceIds, NotifySubMeshesHypothesisModification();
578 } // --------------------------------------------------------------------------------
579 bool StdMeshers_ViscousLayers::IsIgnoredShape(const int shapeID) const
581 return ( find( _ignoreBndShapeIds.begin(), _ignoreBndShapeIds.end(), shapeID )
582 != _ignoreBndShapeIds.end() );
583 } // --------------------------------------------------------------------------------
584 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
586 if ( thickness != _thickness )
587 _thickness = thickness, NotifySubMeshesHypothesisModification();
588 } // --------------------------------------------------------------------------------
589 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
591 if ( _nbLayers != nb )
592 _nbLayers = nb, NotifySubMeshesHypothesisModification();
593 } // --------------------------------------------------------------------------------
594 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
596 if ( _stretchFactor != factor )
597 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
598 } // --------------------------------------------------------------------------------
600 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
601 const TopoDS_Shape& theShape,
602 const bool toMakeN2NMap) const
604 using namespace VISCOUS_3D;
605 _ViscousBuilder bulder;
606 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
607 if ( err && !err->IsOK() )
608 return SMESH_ProxyMesh::Ptr();
610 vector<SMESH_ProxyMesh::Ptr> components;
611 TopExp_Explorer exp( theShape, TopAbs_SOLID );
612 for ( ; exp.More(); exp.Next() )
614 if ( _MeshOfSolid* pm =
615 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
617 if ( toMakeN2NMap && !pm->_n2nMapComputed )
618 if ( !bulder.MakeN2NMap( pm ))
619 return SMESH_ProxyMesh::Ptr();
620 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
621 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
623 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
625 switch ( components.size() )
629 case 1: return components[0];
631 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
633 return SMESH_ProxyMesh::Ptr();
634 } // --------------------------------------------------------------------------------
635 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
637 save << " " << _nbLayers
639 << " " << _stretchFactor
640 << " " << _ignoreBndShapeIds.size();
641 for ( unsigned i = 0; i < _ignoreBndShapeIds.size(); ++i )
642 save << " " << _ignoreBndShapeIds[i];
644 } // --------------------------------------------------------------------------------
645 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
648 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
649 while ( _ignoreBndShapeIds.size() < nbFaces && load >> faceID )
650 _ignoreBndShapeIds.push_back( faceID );
652 } // --------------------------------------------------------------------------------
653 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
654 const TopoDS_Shape& theShape)
659 // END StdMeshers_ViscousLayers hypothesis
660 //================================================================================
664 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
668 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
669 gp_Pnt p = BRep_Tool::Pnt( fromV );
670 double distF = p.SquareDistance( c->Value( f ));
671 double distL = p.SquareDistance( c->Value( l ));
672 c->D1(( distF < distL ? f : l), p, dir );
673 if ( distL < distF ) dir.Reverse();
676 //--------------------------------------------------------------------------------
677 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
678 SMESH_MesherHelper& helper)
681 double f,l; gp_Pnt p;
682 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
683 double u = helper.GetNodeU( E, atNode );
687 //--------------------------------------------------------------------------------
688 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
689 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
691 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
692 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
693 gp_Pnt p; gp_Vec du, dv, norm;
694 surface->D1( uv.X(),uv.Y(), p, du,dv );
698 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
699 double u = helper.GetNodeU( fromE, node, 0, &ok );
701 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
702 if ( o == TopAbs_REVERSED )
705 gp_Vec dir = norm ^ du;
707 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
708 helper.IsClosedEdge( fromE ))
710 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
711 else c->D1( f, p, dv );
712 if ( o == TopAbs_REVERSED )
714 gp_Vec dir2 = norm ^ dv;
715 dir = dir.Normalized() + dir2.Normalized();
719 //--------------------------------------------------------------------------------
720 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
721 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
722 bool& ok, double* cosin=0)
724 double f,l; TopLoc_Location loc;
725 vector< TopoDS_Edge > edges; // sharing a vertex
726 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
729 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
730 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
731 edges.push_back( *e );
734 if ( !( ok = ( edges.size() > 0 ))) return dir;
735 // get average dir of edges going fromV
737 //if ( edges.size() > 1 )
738 for ( unsigned i = 0; i < edges.size(); ++i )
740 edgeDir = getEdgeDir( edges[i], fromV );
741 double size2 = edgeDir.SquareModulus();
742 if ( size2 > numeric_limits<double>::min() )
743 edgeDir /= sqrt( size2 );
748 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
749 if ( edges.size() == 1 )
751 else if ( dir.SquareModulus() < 0.1 ) // ~< 20 degrees
752 dir = fromEdgeDir + getFaceDir( F, edges[1], node, helper, ok );
753 else if ( dir * fromEdgeDir < 0 )
757 //dir /= edges.size();
759 double angle = gp_Vec( edgeDir ).Angle( dir );
760 *cosin = cos( angle );
765 //================================================================================
767 * \brief Returns true if a FACE is bound by a concave EDGE
769 //================================================================================
771 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
775 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
776 for ( ; eExp.More(); eExp.Next() )
778 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
779 if ( BRep_Tool::Degenerated( E )) continue;
780 // check if 2D curve is concave
781 BRepAdaptor_Curve2d curve( E, F );
782 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
783 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
784 curve.Intervals( intervals, GeomAbs_C2 );
785 bool isConvex = true;
786 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
788 double u1 = intervals( i );
789 double u2 = intervals( i+1 );
790 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
791 double cross = drv2 ^ drv1;
792 if ( E.Orientation() == TopAbs_REVERSED )
794 isConvex = ( cross < 1e-9 );
796 // check if concavity is strong enough to care about it
797 //const double maxAngle = 5 * Standard_PI180;
800 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
802 // map< double, const SMDS_MeshNode* > u2nodes;
803 // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
804 // /*ignoreMedium=*/true, u2nodes))
806 // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
807 // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
808 // double uPrev = u2n->first;
809 // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
811 // gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
812 // gp_Vec2d segmentDir( uvPrev, uv );
813 // curve.D1( uPrev, p, drv1 );
815 // if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
820 // uPrev = u2n->first;
826 //--------------------------------------------------------------------------------
827 // DEBUG. Dump intermediate node positions into a python script
832 const char* fname = "/tmp/viscous.py";
833 cout << "execfile('"<<fname<<"')"<<endl;
834 py = new ofstream(fname);
835 *py << "from smesh import *" << endl
836 << "meshSO = GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
837 << "mesh = Mesh( meshSO.GetObject() )"<<endl;
841 *py << "mesh.MakeGroup('Viscous Prisms',VOLUME,FT_ElemGeomType,'=',Geom_PENTA)"<<endl;
844 ~PyDump() { Finish(); }
846 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
847 #define dumpMove(n) { _dumpMove(n, __LINE__);}
848 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
849 void _dumpFunction(const string& fun, int ln)
850 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
851 void _dumpMove(const SMDS_MeshNode* n, int ln)
852 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
853 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
854 void _dumpCmd(const string& txt, int ln)
855 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
856 void dumpFunctionEnd()
857 { if (py) *py<< " return"<< endl; }
858 void dumpChangeNodes( const SMDS_MeshElement* f )
859 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
860 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
861 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
863 struct PyDump { void Finish() {} };
864 #define dumpFunction(f) f
867 #define dumpFunctionEnd()
868 #define dumpChangeNodes(f)
872 using namespace VISCOUS_3D;
874 //================================================================================
876 * \brief Constructor of _ViscousBuilder
878 //================================================================================
880 _ViscousBuilder::_ViscousBuilder()
882 _error = SMESH_ComputeError::New(COMPERR_OK);
886 //================================================================================
888 * \brief Stores error description and returns false
890 //================================================================================
892 bool _ViscousBuilder::error(const string& text, int solidId )
894 _error->myName = COMPERR_ALGO_FAILED;
895 _error->myComment = string("Viscous layers builder: ") + text;
898 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
899 if ( !sm && !_sdVec.empty() )
900 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
901 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
903 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
904 if ( smError && smError->myAlgo )
905 _error->myAlgo = smError->myAlgo;
909 makeGroupOfLE(); // debug
914 //================================================================================
916 * \brief At study restoration, restore event listeners used to clear an inferior
917 * dim sub-mesh modified by viscous layers
919 //================================================================================
921 void _ViscousBuilder::RestoreListeners()
926 //================================================================================
928 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
930 //================================================================================
932 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
934 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
935 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
936 for ( ; fExp.More(); fExp.Next() )
938 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
939 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
941 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
943 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
946 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
947 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
949 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
950 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
951 while( prxIt->more() )
953 const SMDS_MeshElement* fSrc = srcIt->next();
954 const SMDS_MeshElement* fPrx = prxIt->next();
955 if ( fSrc->NbNodes() != fPrx->NbNodes())
956 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
957 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
958 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
961 pm->_n2nMapComputed = true;
965 //================================================================================
967 * \brief Does its job
969 //================================================================================
971 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
972 const TopoDS_Shape& theShape)
974 // TODO: set priority of solids during Gen::Compute()
978 // check if proxy mesh already computed
979 TopExp_Explorer exp( theShape, TopAbs_SOLID );
981 return error("No SOLID's in theShape"), _error;
983 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
984 return SMESH_ComputeErrorPtr(); // everything already computed
988 // TODO: ignore already computed SOLIDs
989 if ( !findSolidsWithLayers())
992 if ( !findFacesWithLayers() )
995 for ( unsigned i = 0; i < _sdVec.size(); ++i )
997 if ( ! makeLayer(_sdVec[i]) )
1000 if ( _sdVec[i]._edges.size() == 0 )
1003 if ( ! inflate(_sdVec[i]) )
1006 if ( ! refine(_sdVec[i]) )
1012 addBoundaryElements();
1014 makeGroupOfLE(); // debug
1020 //================================================================================
1022 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1024 //================================================================================
1026 bool _ViscousBuilder::findSolidsWithLayers()
1029 TopTools_IndexedMapOfShape allSolids;
1030 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1031 _sdVec.reserve( allSolids.Extent());
1033 SMESH_Gen* gen = _mesh->GetGen();
1034 for ( int i = 1; i <= allSolids.Extent(); ++i )
1036 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1037 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1038 if ( !algo ) continue;
1039 // TODO: check if algo is hidden
1040 const list <const SMESHDS_Hypothesis *> & allHyps =
1041 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1042 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1043 const StdMeshers_ViscousLayers* viscHyp = 0;
1044 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1045 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1048 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1051 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, proxyMesh ));
1052 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1055 if ( _sdVec.empty() )
1057 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1062 //================================================================================
1066 //================================================================================
1068 bool _ViscousBuilder::findFacesWithLayers()
1070 // collect all faces to ignore defined by hyp
1071 vector<TopoDS_Shape> ignoreFaces;
1072 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1074 vector<TGeomID> ids = _sdVec[i]._hyp->GetBndShapesToIgnore();
1075 for ( unsigned i = 0; i < ids.size(); ++i )
1077 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
1078 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1080 _ignoreShapeIds.insert( ids[i] );
1081 ignoreFaces.push_back( s );
1086 // ignore internal faces
1087 SMESH_MesherHelper helper( *_mesh );
1088 TopExp_Explorer exp;
1089 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1091 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1092 for ( ; exp.More(); exp.Next() )
1094 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1095 if ( helper.NbAncestors( exp.Current(), *_mesh, TopAbs_SOLID ) > 1 )
1097 _ignoreShapeIds.insert( faceInd );
1098 ignoreFaces.push_back( exp.Current() );
1099 if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face( exp.Current() ), getMeshDS()))
1100 _sdVec[i]._reversedFaceIds.insert( faceInd );
1105 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1106 TopTools_IndexedMapOfShape shapes;
1107 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1110 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1111 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1113 const TopoDS_Shape& edge = shapes(iE);
1114 // find 2 faces sharing an edge
1116 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1117 while ( fIt->more())
1119 const TopoDS_Shape* f = fIt->next();
1120 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1121 FF[ int( !FF[0].IsNull()) ] = *f;
1123 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1124 // check presence of layers on them
1126 for ( int j = 0; j < 2; ++j )
1127 ignore[j] = _ignoreShapeIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1128 if ( ignore[0] == ignore[1] ) continue; // nothing interesting
1129 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1131 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1132 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1135 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1136 // the algo of the SOLID sharing the FACE does not support it
1137 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1138 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1140 TopTools_MapOfShape noShrinkVertices;
1141 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1142 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1144 const TopoDS_Shape& fWOL = e2f->second;
1145 TGeomID edgeID = e2f->first;
1146 bool notShrinkFace = false;
1147 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1148 while ( soIt->more())
1150 const TopoDS_Shape* solid = soIt->next();
1151 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1152 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1153 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1154 notShrinkFace = true;
1155 for ( unsigned j = 0; j < _sdVec.size(); ++j )
1157 if ( _sdVec[j]._solid.IsSame( *solid ) )
1158 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1159 notShrinkFace = false;
1162 if ( notShrinkFace )
1164 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1165 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1166 noShrinkVertices.Add( vExp.Current() );
1169 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1170 // to the found not shrinked fWOL's
1171 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1172 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1174 TGeomID edgeID = e2f->first;
1175 TopoDS_Vertex VV[2];
1176 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1177 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1179 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1180 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1189 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1191 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1194 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1195 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1197 const TopoDS_Shape& vertex = shapes(iV);
1198 // find faces WOL sharing the vertex
1199 vector< TopoDS_Shape > facesWOL;
1200 int totalNbFaces = 0;
1201 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1202 while ( fIt->more())
1204 const TopoDS_Shape* f = fIt->next();
1205 const int fID = getMeshDS()->ShapeToIndex( *f );
1206 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1209 if ( _ignoreShapeIds.count ( fID ) && ! _sdVec[i]._noShrinkFaces.count( fID ))
1210 facesWOL.push_back( *f );
1213 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1214 continue; // no layers at this vertex or no WOL
1215 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1216 switch ( facesWOL.size() )
1220 helper.SetSubShape( facesWOL[0] );
1221 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1223 TopoDS_Shape seamEdge;
1224 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1225 while ( eIt->more() && seamEdge.IsNull() )
1227 const TopoDS_Shape* e = eIt->next();
1228 if ( helper.IsRealSeam( *e ) )
1231 if ( !seamEdge.IsNull() )
1233 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1237 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1242 // find an edge shared by 2 faces
1243 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1244 while ( eIt->more())
1246 const TopoDS_Shape* e = eIt->next();
1247 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1248 helper.IsSubShape( *e, facesWOL[1]))
1250 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1256 return error("Not yet supported case", _sdVec[i]._index);
1264 //================================================================================
1266 * \brief Create the inner surface of the viscous layer and prepare data for infation
1268 //================================================================================
1270 bool _ViscousBuilder::makeLayer(_SolidData& data)
1272 // get all sub-shapes to make layers on
1273 set<TGeomID> subIds, faceIds;
1274 subIds = data._noShrinkFaces;
1275 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1276 for ( ; exp.More(); exp.Next() )
1277 if ( ! _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1279 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1280 faceIds.insert( fSubM->GetId() );
1281 SMESH_subMeshIteratorPtr subIt =
1282 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1283 while ( subIt->more() )
1284 subIds.insert( subIt->next()->GetId() );
1287 // make a map to find new nodes on sub-shapes shared with other SOLID
1288 map< TGeomID, TNode2Edge* > s2neMap;
1289 map< TGeomID, TNode2Edge* >::iterator s2ne;
1290 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1291 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1293 TGeomID shapeInd = s2s->first;
1294 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1296 if ( _sdVec[i]._index == data._index ) continue;
1297 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1298 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1299 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1301 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1307 // Create temporary faces and _LayerEdge's
1309 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1311 data._stepSize = Precision::Infinite();
1312 data._stepSizeNodes[0] = 0;
1314 SMESH_MesherHelper helper( *_mesh );
1315 helper.SetSubShape( data._solid );
1316 helper.SetElementsOnShape(true);
1318 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1319 TNode2Edge::iterator n2e2;
1321 // collect _LayerEdge's of shapes they are based on
1322 const int nbShapes = getMeshDS()->MaxShapeIndex();
1323 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1325 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1327 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1328 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1330 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1331 SMESH_ProxyMesh::SubMesh* proxySub =
1332 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1334 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1335 while ( eIt->more() )
1337 const SMDS_MeshElement* face = eIt->next();
1338 newNodes.resize( face->NbCornerNodes() );
1339 double faceMaxCosin = -1;
1340 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1342 const SMDS_MeshNode* n = face->GetNode(i);
1343 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1344 if ( !(*n2e).second )
1347 _LayerEdge* edge = new _LayerEdge();
1349 edge->_nodes.push_back( n );
1350 const int shapeID = n->getshapeId();
1351 edgesByGeom[ shapeID ].push_back( edge );
1353 // set edge data or find already refined _LayerEdge and get data from it
1354 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1355 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1356 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1358 _LayerEdge* foundEdge = (*n2e2).second;
1359 edge->Copy( *foundEdge, helper );
1360 // location of the last node is modified but we can restore
1361 // it by node position on _sWOL stored by the node
1362 const_cast< SMDS_MeshNode* >
1363 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1367 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1368 if ( !setEdgeData( *edge, subIds, helper, data ))
1371 dumpMove(edge->_nodes.back());
1372 if ( edge->_cosin > 0.01 )
1374 if ( edge->_cosin > faceMaxCosin )
1375 faceMaxCosin = edge->_cosin;
1378 newNodes[ i ] = n2e->second->_nodes.back();
1380 // create a temporary face
1381 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1382 proxySub->AddElement( newFace );
1384 // compute inflation step size by min size of element on a convex surface
1385 if ( faceMaxCosin > 0.1 )
1386 limitStepSize( data, face, faceMaxCosin );
1387 } // loop on 2D elements on a FACE
1388 } // loop on FACEs of a SOLID
1390 data._epsilon = 1e-7;
1391 if ( data._stepSize < 1. )
1392 data._epsilon *= data._stepSize;
1394 // Put _LayerEdge's into the vector data._edges
1396 if ( !sortEdges( data, edgesByGeom ))
1399 // Set target nodes into _Simplex and _2NearEdges
1400 TNode2Edge::iterator n2e;
1401 for ( unsigned i = 0; i < data._edges.size(); ++i )
1403 if ( data._edges[i]->IsOnEdge())
1404 for ( int j = 0; j < 2; ++j )
1406 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1407 break; // _LayerEdge is shared by two _SolidData's
1408 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1409 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1410 return error("_LayerEdge not found by src node", data._index);
1411 n = (*n2e).second->_nodes.back();
1412 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1415 for ( unsigned j = 0; j < data._edges[i]->_simplices.size(); ++j )
1417 _Simplex& s = data._edges[i]->_simplices[j];
1418 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1419 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1427 //================================================================================
1429 * \brief Compute inflation step size by min size of element on a convex surface
1431 //================================================================================
1433 void _ViscousBuilder::limitStepSize( _SolidData& data,
1434 const SMDS_MeshElement* face,
1438 double minSize = 10 * data._stepSize;
1439 const int nbNodes = face->NbCornerNodes();
1440 for ( int i = 0; i < nbNodes; ++i )
1442 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1443 const SMDS_MeshNode* curN = face->GetNode( i );
1444 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1445 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1447 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1448 if ( dist < minSize )
1449 minSize = dist, iN = i;
1452 double newStep = 0.8 * minSize / cosin;
1453 if ( newStep < data._stepSize )
1455 data._stepSize = newStep;
1456 data._stepSizeCoeff = 0.8 / cosin;
1457 data._stepSizeNodes[0] = face->GetNode( iN );
1458 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1462 //================================================================================
1464 * \brief Compute inflation step size by min size of element on a convex surface
1466 //================================================================================
1468 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1470 if ( minSize < data._stepSize )
1472 data._stepSize = minSize;
1473 if ( data._stepSizeNodes[0] )
1476 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1477 data._stepSizeCoeff = data._stepSize / dist;
1482 //================================================================================
1484 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1486 //================================================================================
1488 bool _ViscousBuilder::sortEdges( _SolidData& data,
1489 vector< vector<_LayerEdge*> >& edgesByGeom)
1491 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1492 // boundry inclined at a sharp angle to the shape
1494 list< TGeomID > shapesToSmooth;
1496 SMESH_MesherHelper helper( *_mesh );
1499 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1501 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1502 if ( eS.empty() ) continue;
1503 TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1504 bool needSmooth = false;
1505 switch ( S.ShapeType() )
1509 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1510 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1512 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1513 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1514 if ( eV.empty() ) continue;
1515 double cosin = eV[0]->_cosin;
1517 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1521 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1522 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1524 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1525 eV[0]->_nodes[0], helper, ok);
1526 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1527 double angle = dir1.Angle( dir2 );
1528 cosin = cos( angle );
1530 needSmooth = ( cosin > 0.1 );
1536 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1538 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1539 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1540 if ( eE.empty() ) continue;
1541 if ( eE[0]->_sWOL.IsNull() )
1543 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1544 needSmooth = ( eE[i]->_cosin > 0.1 );
1548 const TopoDS_Face& F1 = TopoDS::Face( S );
1549 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1550 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1551 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1553 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1554 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1555 double angle = dir1.Angle( dir2 );
1556 double cosin = cos( angle );
1557 needSmooth = ( cosin > 0.1 );
1569 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1570 else shapesToSmooth.push_back ( iS );
1573 } // loop on edgesByGeom
1575 data._edges.reserve( data._n2eMap.size() );
1576 data._endEdgeToSmooth.clear();
1578 // first we put _LayerEdge's on shapes to smooth
1579 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1580 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1582 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1583 if ( eVec.empty() ) continue;
1584 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1585 data._endEdgeToSmooth.push_back( data._edges.size() );
1589 // then the rest _LayerEdge's
1590 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1592 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1593 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1600 //================================================================================
1602 * \brief Set data of _LayerEdge needed for smoothing
1603 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1605 //================================================================================
1607 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1608 const set<TGeomID>& subIds,
1609 SMESH_MesherHelper& helper,
1612 SMESH_MeshEditor editor(_mesh);
1614 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1615 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1619 edge._curvature = 0;
1621 // --------------------------
1622 // Compute _normal and _cosin
1623 // --------------------------
1626 edge._normal.SetCoord(0,0,0);
1628 int totalNbFaces = 0;
1630 gp_Vec du, dv, geomNorm;
1633 TGeomID shapeInd = node->getshapeId();
1634 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1635 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1636 TopoDS_Shape vertEdge;
1638 if ( onShrinkShape ) // one of faces the node is on has no layers
1640 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1641 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1643 // inflate from VERTEX along EDGE
1644 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1646 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1648 // inflate from VERTEX along FACE
1649 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1650 node, helper, normOK, &edge._cosin);
1654 // inflate from EDGE along FACE
1655 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1656 node, helper, normOK);
1659 else // layers are on all faces of SOLID the node is on
1661 // find indices of geom faces the node lies on
1662 set<TGeomID> faceIds;
1663 if ( posType == SMDS_TOP_FACE )
1665 faceIds.insert( node->getshapeId() );
1669 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1670 while ( fIt->more() )
1671 faceIds.insert( editor.FindShape(fIt->next()));
1674 set<TGeomID>::iterator id = faceIds.begin();
1676 for ( ; id != faceIds.end(); ++id )
1678 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1679 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1682 //nbLayerFaces += subIds.count( *id );
1683 F = TopoDS::Face( s );
1685 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1686 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1687 surface->D1( uv.X(),uv.Y(), p, du,dv );
1689 double size2 = geomNorm.SquareMagnitude();
1690 if ( size2 > numeric_limits<double>::min() )
1691 geomNorm /= sqrt( size2 );
1694 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1696 edge._normal += geomNorm.XYZ();
1698 if ( totalNbFaces == 0 )
1699 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1701 edge._normal /= totalNbFaces;
1706 edge._cosin = 0; break;
1708 case SMDS_TOP_EDGE: {
1709 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1710 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1711 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1712 edge._cosin = cos( angle );
1713 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1716 case SMDS_TOP_VERTEX: {
1717 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1718 gp_XYZ inFaceDir = getFaceDir( F, V, node, helper, normOK);
1719 double angle = gp_Vec( inFaceDir).Angle( edge._normal ); // [0,PI]
1720 edge._cosin = cos( angle );
1721 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1725 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1729 double normSize = edge._normal.SquareModulus();
1730 if ( normSize < numeric_limits<double>::min() )
1731 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1733 edge._normal /= sqrt( normSize );
1735 // TODO: if ( !normOK ) then get normal by mesh faces
1737 // Set the rest data
1738 // --------------------
1739 if ( onShrinkShape )
1741 edge._sWOL = (*s2s).second;
1743 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1744 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1745 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1747 // set initial position which is parameters on _sWOL in this case
1748 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1750 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1751 edge._pos.push_back( gp_XYZ( u, 0, 0));
1752 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1756 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1757 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1758 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1763 edge._pos.push_back( SMESH_TNodeXYZ( node ));
1765 if ( posType == SMDS_TOP_FACE )
1767 getSimplices( node, edge._simplices, _ignoreShapeIds, &data );
1768 double avgNormProj = 0, avgLen = 0;
1769 for ( unsigned i = 0; i < edge._simplices.size(); ++i )
1771 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
1772 avgNormProj += edge._normal * vec;
1773 avgLen += vec.Modulus();
1775 avgNormProj /= edge._simplices.size();
1776 avgLen /= edge._simplices.size();
1777 edge._curvature = _Curvature::New( avgNormProj, avgLen );
1781 // Set neighbour nodes for a _LayerEdge based on EDGE
1783 if ( posType == SMDS_TOP_EDGE /*||
1784 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1786 edge._2neibors = new _2NearEdges;
1787 // target node instead of source ones will be set later
1788 if ( ! findNeiborsOnEdge( &edge,
1789 edge._2neibors->_nodes[0],
1790 edge._2neibors->_nodes[1],
1793 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1794 edge._2neibors->_nodes[1],
1798 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1803 //================================================================================
1805 * \brief Find 2 neigbor nodes of a node on EDGE
1807 //================================================================================
1809 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
1810 const SMDS_MeshNode*& n1,
1811 const SMDS_MeshNode*& n2,
1814 const SMDS_MeshNode* node = edge->_nodes[0];
1815 const int shapeInd = node->getshapeId();
1816 SMESHDS_SubMesh* edgeSM = 0;
1817 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
1820 edgeSM = getMeshDS()->MeshElements( shapeInd );
1821 if ( !edgeSM || edgeSM->NbElements() == 0 )
1822 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
1826 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
1827 while ( eIt->more() && !n2 )
1829 const SMDS_MeshElement* e = eIt->next();
1830 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
1831 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
1834 if (!edgeSM->Contains(e)) continue;
1838 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
1839 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
1841 ( iN++ ? n2 : n1 ) = nNeibor;
1844 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
1848 //================================================================================
1850 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
1852 //================================================================================
1854 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
1855 const SMDS_MeshNode* n2,
1856 SMESH_MesherHelper& helper)
1858 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1861 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
1862 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
1863 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
1867 double sumLen = vec1.Modulus() + vec2.Modulus();
1868 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
1869 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
1870 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
1871 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
1872 if ( _curvature ) delete _curvature;
1873 _curvature = _Curvature::New( avgNormProj, avgLen );
1875 // if ( _curvature )
1876 // cout << _nodes[0]->GetID()
1877 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
1878 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
1879 // << _curvature->lenDelta(0) << endl;
1884 if ( _sWOL.IsNull() )
1886 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
1887 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
1888 gp_XYZ plnNorm = dirE ^ _normal;
1889 double proj0 = plnNorm * vec1;
1890 double proj1 = plnNorm * vec2;
1891 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
1893 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
1894 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
1899 //================================================================================
1901 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
1902 * this and other _LayerEdge's are inflated along a FACE or an EDGE
1904 //================================================================================
1906 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
1908 _nodes = other._nodes;
1909 _normal = other._normal;
1911 _lenFactor = other._lenFactor;
1912 _cosin = other._cosin;
1913 _sWOL = other._sWOL;
1914 _2neibors = other._2neibors;
1915 _curvature = 0; std::swap( _curvature, other._curvature );
1916 _2neibors = 0; std::swap( _2neibors, other._2neibors );
1918 if ( _sWOL.ShapeType() == TopAbs_EDGE )
1920 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
1921 _pos.push_back( gp_XYZ( u, 0, 0));
1925 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
1926 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1930 //================================================================================
1932 * \brief Set _cosin and _lenFactor
1934 //================================================================================
1936 void _LayerEdge::SetCosin( double cosin )
1939 _lenFactor = ( _cosin > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
1942 //================================================================================
1944 * \brief Fills a vector<_Simplex >
1946 //================================================================================
1948 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
1949 vector<_Simplex>& simplices,
1950 const set<TGeomID>& ingnoreShapes,
1951 const _SolidData* dataToCheckOri,
1954 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1955 while ( fIt->more() )
1957 const SMDS_MeshElement* f = fIt->next();
1958 const TGeomID shapeInd = f->getshapeId();
1959 if ( ingnoreShapes.count( shapeInd )) continue;
1960 const int nbNodes = f->NbCornerNodes();
1961 int srcInd = f->GetNodeIndex( node );
1962 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
1963 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
1964 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
1965 std::swap( nPrev, nNext );
1966 simplices.push_back( _Simplex( nPrev, nNext ));
1971 vector<_Simplex> sortedSimplices( simplices.size() );
1972 sortedSimplices[0] = simplices[0];
1974 for ( size_t i = 1; i < simplices.size(); ++i )
1976 for ( size_t j = 1; j < simplices.size(); ++j )
1977 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
1979 sortedSimplices[i] = simplices[j];
1984 if ( nbFound == simplices.size() - 1 )
1985 simplices.swap( sortedSimplices );
1989 //================================================================================
1991 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
1993 //================================================================================
1995 void _ViscousBuilder::makeGroupOfLE()
1998 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
2000 if ( _sdVec[i]._edges.empty() ) continue;
2001 // string name = SMESH_Comment("_LayerEdge's_") << i;
2003 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
2004 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
2005 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
2007 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
2008 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2010 _LayerEdge* le = _sdVec[i]._edges[j];
2011 for ( unsigned iN = 1; iN < le->_nodes.size(); ++iN )
2012 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
2013 << ", " << le->_nodes[iN]->GetID() <<"])");
2014 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
2018 dumpFunction( SMESH_Comment("makeNormals") << i );
2019 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2021 _LayerEdge& edge = *_sdVec[i]._edges[j];
2022 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2023 nXYZ += edge._normal * _sdVec[i]._stepSize;
2024 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2025 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2029 // name = SMESH_Comment("tmp_faces ") << i;
2030 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2031 // gDS = (SMESHDS_Group*)g->GetGroupDS();
2032 // SMESH_MeshEditor editor( _mesh );
2033 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2034 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2035 for ( ; fExp.More(); fExp.Next() )
2037 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2039 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2040 while ( fIt->more())
2042 const SMDS_MeshElement* e = fIt->next();
2043 SMESH_Comment cmd("mesh.AddFace([");
2044 for ( int j=0; j < e->NbCornerNodes(); ++j )
2045 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2047 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2048 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2057 //================================================================================
2059 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2061 //================================================================================
2063 bool _ViscousBuilder::inflate(_SolidData& data)
2065 SMESH_MesherHelper helper( *_mesh );
2067 // Limit inflation step size by geometry size found by itersecting
2068 // normals of _LayerEdge's with mesh faces
2069 double geomSize = Precision::Infinite(), intersecDist;
2070 SMESH_MeshEditor editor( _mesh );
2071 auto_ptr<SMESH_ElementSearcher> searcher
2072 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2073 for ( unsigned i = 0; i < data._edges.size(); ++i )
2075 if ( data._edges[i]->IsOnEdge() ) continue;
2076 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2077 if ( geomSize > intersecDist )
2078 geomSize = intersecDist;
2080 if ( data._stepSize > 0.3 * geomSize )
2081 limitStepSize( data, 0.3 * geomSize );
2083 const double tgtThick = data._hyp->GetTotalThickness();
2084 if ( data._stepSize > tgtThick )
2085 limitStepSize( data, tgtThick );
2087 if ( data._stepSize < 1. )
2088 data._epsilon = data._stepSize * 1e-7;
2091 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2094 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2095 int nbSteps = 0, nbRepeats = 0;
2096 while ( 1.01 * avgThick < tgtThick )
2098 // new target length
2099 curThick += data._stepSize;
2100 if ( curThick > tgtThick )
2102 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2106 // Elongate _LayerEdge's
2107 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2108 for ( unsigned i = 0; i < data._edges.size(); ++i )
2110 data._edges[i]->SetNewLength( curThick, helper );
2115 if ( !updateNormals( data, helper ) )
2118 // Improve and check quality
2119 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2123 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2124 for ( unsigned i = 0; i < data._edges.size(); ++i )
2126 data._edges[i]->InvalidateStep( nbSteps+1 );
2130 break; // no more inflating possible
2134 // Evaluate achieved thickness
2136 for ( unsigned i = 0; i < data._edges.size(); ++i )
2137 avgThick += data._edges[i]->_len;
2138 avgThick /= data._edges.size();
2140 cout << "-- Thickness " << avgThick << " reached" << endl;
2143 if ( distToIntersection < avgThick*1.5 )
2146 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2147 << avgThick << " ) * 1.5" << endl;
2152 limitStepSize( data, 0.25 * distToIntersection );
2153 if ( data._stepSizeNodes[0] )
2154 data._stepSize = data._stepSizeCoeff *
2155 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2159 return error("failed at the very first inflation step", data._index);
2164 //================================================================================
2166 * \brief Improve quality of layer inner surface and check intersection
2168 //================================================================================
2170 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2172 double & distToIntersection)
2174 if ( data._endEdgeToSmooth.empty() )
2175 return true; // no shapes needing smoothing
2177 bool moved, improved;
2179 SMESH_MesherHelper helper(*_mesh);
2180 Handle(Geom_Surface) surface;
2184 for ( unsigned iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2187 iEnd = data._endEdgeToSmooth[ iS ];
2189 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2190 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2192 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2193 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2194 helper.SetSubShape( F );
2195 surface = BRep_Tool::Surface( F );
2200 F.Nullify(); surface.Nullify();
2202 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2204 if ( data._edges[ iBeg ]->IsOnEdge() )
2206 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2208 // try a simple solution on an analytic EDGE
2209 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2215 for ( int i = iBeg; i < iEnd; ++i )
2217 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2219 dumpCmd( SMESH_Comment("# end step ")<<step);
2221 while ( moved && step++ < 5 );
2222 //cout << " NB STEPS: " << step << endl;
2229 int step = 0, badNb = 0; moved = true;
2230 while (( ++step <= 5 && moved ) || improved )
2232 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2233 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2234 int oldBadNb = badNb;
2237 for ( int i = iBeg; i < iEnd; ++i )
2238 moved |= data._edges[i]->Smooth(badNb);
2239 improved = ( badNb < oldBadNb );
2246 for ( int i = iBeg; i < iEnd; ++i )
2248 _LayerEdge* edge = data._edges[i];
2249 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2250 for ( unsigned j = 0; j < edge->_simplices.size(); ++j )
2251 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2253 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2254 << " "<< edge->_simplices[j]._nPrev->GetID()
2255 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2263 } // loop on shapes to smooth
2265 // Check if the last segments of _LayerEdge intersects 2D elements;
2266 // checked elements are either temporary faces or faces on surfaces w/o the layers
2268 SMESH_MeshEditor editor( _mesh );
2269 auto_ptr<SMESH_ElementSearcher> searcher
2270 ( editor.GetElementSearcher( data._proxyMesh->GetFaces( data._solid )) );
2272 distToIntersection = Precision::Infinite();
2274 const SMDS_MeshElement* intFace = 0;
2276 const SMDS_MeshElement* closestFace = 0;
2279 for ( unsigned i = 0; i < data._edges.size(); ++i )
2281 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2283 if ( distToIntersection > dist )
2285 distToIntersection = dist;
2288 closestFace = intFace;
2295 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2296 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2297 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2298 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2299 << ") distance = " << distToIntersection<< endl;
2306 //================================================================================
2308 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2309 * _LayerEdge's to be in a consequent order
2311 //================================================================================
2313 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2316 Handle(Geom_Surface)& surface,
2317 const TopoDS_Face& F,
2318 SMESH_MesherHelper& helper)
2320 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2322 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2324 if ( i2curve == _edge2curve.end() )
2326 // sort _LayerEdge's by position on the EDGE
2328 map< double, _LayerEdge* > u2edge;
2329 for ( int i = iFrom; i < iTo; ++i )
2330 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2332 ASSERT( u2edge.size() == iTo - iFrom );
2333 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2334 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2335 _edges[i] = u2e->second;
2337 // set _2neibors according to the new order
2338 for ( int i = iFrom; i < iTo-1; ++i )
2339 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2340 _edges[i]->_2neibors->reverse();
2341 if ( u2edge.size() > 1 &&
2342 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2343 _edges[iTo-1]->_2neibors->reverse();
2346 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2348 TopLoc_Location loc; double f,l;
2350 Handle(Geom_Line) line;
2351 Handle(Geom_Circle) circle;
2352 bool isLine, isCirc;
2353 if ( F.IsNull() ) // 3D case
2355 // check if the EDGE is a line
2356 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2357 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2358 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2360 line = Handle(Geom_Line)::DownCast( curve );
2361 circle = Handle(Geom_Circle)::DownCast( curve );
2362 isLine = (!line.IsNull());
2363 isCirc = (!circle.IsNull());
2365 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2368 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2369 while ( nIt->more() )
2370 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2371 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2373 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2374 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2375 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2376 for ( int i = 0; i < 3 && !isLine; ++i )
2377 isLine = ( size.Coord( i+1 ) <= lineTol );
2379 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2386 // check if the EDGE is a line
2387 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2388 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2389 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2391 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2392 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2393 isLine = (!line2d.IsNull());
2394 isCirc = (!circle2d.IsNull());
2396 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2399 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2400 while ( nIt->more() )
2401 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2402 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2404 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2405 for ( int i = 0; i < 2 && !isLine; ++i )
2406 isLine = ( size.Coord( i+1 ) <= lineTol );
2408 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2414 line = new Geom_Line( gp::OX() ); // only type does matter
2418 gp_Pnt2d p = circle2d->Location();
2419 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2420 circle = new Geom_Circle( ax, 1.); // only center position does matter
2424 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2432 return i2curve->second;
2435 //================================================================================
2437 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2439 //================================================================================
2441 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2444 Handle(Geom_Surface)& surface,
2445 const TopoDS_Face& F,
2446 SMESH_MesherHelper& helper)
2448 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2449 helper.GetMeshDS());
2450 TopoDS_Edge E = TopoDS::Edge( S );
2452 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2453 if ( curve.IsNull() ) return false;
2455 // compute a relative length of segments
2456 vector< double > len( iTo-iFrom+1 );
2458 double curLen, prevLen = len[0] = 1.0;
2459 for ( int i = iFrom; i < iTo; ++i )
2461 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2462 len[i-iFrom+1] = len[i-iFrom] + curLen;
2467 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2469 if ( F.IsNull() ) // 3D
2471 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2472 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2473 for ( int i = iFrom; i < iTo; ++i )
2475 double r = len[i-iFrom] / len.back();
2476 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2477 data._edges[i]->_pos.back() = newPos;
2478 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2479 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2480 dumpMove( tgtNode );
2485 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2486 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2487 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2488 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2490 int iPeriodic = helper.GetPeriodicIndex();
2491 if ( iPeriodic == 1 || iPeriodic == 2 )
2493 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2494 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2495 std::swap( uv0, uv1 );
2498 const gp_XY rangeUV = uv1 - uv0;
2499 for ( int i = iFrom; i < iTo; ++i )
2501 double r = len[i-iFrom] / len.back();
2502 gp_XY newUV = uv0 + r * rangeUV;
2503 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2505 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2506 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2507 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2508 dumpMove( tgtNode );
2510 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2511 pos->SetUParameter( newUV.X() );
2512 pos->SetVParameter( newUV.Y() );
2518 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2520 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2521 gp_Pnt center3D = circle->Location();
2523 if ( F.IsNull() ) // 3D
2525 return false; // TODO ???
2529 const gp_XY center( center3D.X(), center3D.Y() );
2531 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2532 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2533 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2534 gp_Vec2d vec0( center, uv0 );
2535 gp_Vec2d vecM( center, uvM );
2536 gp_Vec2d vec1( center, uv1 );
2537 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2538 double uMidl = vec0.Angle( vecM );
2539 if ( uLast * uMidl < 0. )
2540 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
2541 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2543 gp_Ax2d axis( center, vec0 );
2544 gp_Circ2d circ( axis, radius );
2545 for ( int i = iFrom; i < iTo; ++i )
2547 double newU = uLast * len[i-iFrom] / len.back();
2548 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2549 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2551 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2552 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2553 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2554 dumpMove( tgtNode );
2556 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2557 pos->SetUParameter( newUV.X() );
2558 pos->SetVParameter( newUV.Y() );
2567 //================================================================================
2569 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2570 * _LayerEdge's on neighbor EDGE's
2572 //================================================================================
2574 bool _ViscousBuilder::updateNormals( _SolidData& data,
2575 SMESH_MesherHelper& helper )
2577 // make temporary quadrangles got by extrusion of
2578 // mesh edges along _LayerEdge._normal's
2580 vector< const SMDS_MeshElement* > tmpFaces;
2582 set< SMESH_TLink > extrudedLinks; // contains target nodes
2583 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2585 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2586 for ( unsigned i = 0; i < data._edges.size(); ++i )
2588 _LayerEdge* edge = data._edges[i];
2589 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2590 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2591 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2593 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2594 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2595 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2596 if ( !link_isnew.second )
2598 extrudedLinks.erase( link_isnew.first );
2599 continue; // already extruded and will no more encounter
2601 // look for a _LayerEdge containg tgt2
2602 // _LayerEdge* neiborEdge = 0;
2603 // unsigned di = 0; // check _edges[i+di] and _edges[i-di]
2604 // while ( !neiborEdge && ++di <= data._edges.size() )
2606 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2607 // neiborEdge = data._edges[i+di];
2608 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2609 // neiborEdge = data._edges[i-di];
2611 // if ( !neiborEdge )
2612 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2613 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2615 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2616 tmpFaces.push_back( f );
2618 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2619 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2620 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2625 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2626 // Perform two loops on _LayerEdge on EDGE's:
2627 // 1) to find and fix intersection
2628 // 2) to check that no new intersection appears as result of 1)
2630 SMESH_MeshEditor editor( _mesh );
2631 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2633 auto_ptr<SMESH_ElementSearcher> searcher ( editor.GetElementSearcher( fIt ));
2635 // 1) Find intersections
2637 const SMDS_MeshElement* face;
2638 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2639 TLEdge2LEdgeSet edge2CloseEdge;
2641 const double eps = data._epsilon * data._epsilon;
2642 for ( unsigned i = 0; i < data._edges.size(); ++i )
2644 _LayerEdge* edge = data._edges[i];
2645 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2646 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2648 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2649 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2650 ee.insert( f->_le1 );
2651 ee.insert( f->_le2 );
2652 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
2653 edge2CloseEdge[ f->_le1 ].insert( edge );
2654 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
2655 edge2CloseEdge[ f->_le2 ].insert( edge );
2659 // Set _LayerEdge._normal
2661 if ( !edge2CloseEdge.empty() )
2663 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2665 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2666 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2668 _LayerEdge* edge1 = e2ee->first;
2669 _LayerEdge* edge2 = 0;
2670 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
2672 // find EDGEs the edges reside
2674 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2675 if ( S.ShapeType() != TopAbs_EDGE )
2676 continue; // TODO: find EDGE by VERTEX
2677 E1 = TopoDS::Edge( S );
2678 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
2679 while ( E2.IsNull() && eIt != ee.end())
2681 _LayerEdge* e2 = *eIt++;
2682 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2683 if ( S.ShapeType() == TopAbs_EDGE )
2684 E2 = TopoDS::Edge( S ), edge2 = e2;
2686 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2688 // find 3 FACEs sharing 2 EDGEs
2690 TopoDS_Face FF1[2], FF2[2];
2691 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2692 while ( fIt->more() && FF1[1].IsNull())
2694 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2695 if ( helper.IsSubShape( *F, data._solid))
2696 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2698 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2699 while ( fIt->more() && FF2[1].IsNull())
2701 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2702 if ( helper.IsSubShape( *F, data._solid))
2703 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2705 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2706 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2707 std::swap( FF1[0], FF1[1] );
2708 if ( FF2[0].IsSame( FF1[0]) )
2709 std::swap( FF2[0], FF2[1] );
2710 if ( FF1[0].IsNull() || FF2[0].IsNull() )
2713 // // get a new normal for edge1
2715 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2716 if ( edge1->_cosin < 0 )
2717 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2718 if ( edge2->_cosin < 0 )
2719 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2720 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2721 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2722 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2723 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2724 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2725 // newNorm.Normalize();
2727 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2728 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2729 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2730 newNorm.Normalize();
2732 edge1->_normal = newNorm.XYZ();
2734 // update data of edge1 depending on _normal
2735 const SMDS_MeshNode *n1, *n2;
2736 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2737 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2738 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2740 edge1->SetDataByNeighbors( n1, n2, helper );
2742 if ( edge1->_cosin < 0 )
2745 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2746 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2747 edge1->SetCosin( cos( angle ));
2749 // limit data._stepSize
2750 if ( edge1->_cosin > 0.1 )
2752 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2753 while ( fIt->more() )
2754 limitStepSize( data, fIt->next(), edge1->_cosin );
2756 // set new XYZ of target node
2757 edge1->InvalidateStep( 1 );
2759 edge1->SetNewLength( data._stepSize, helper );
2762 // Update normals and other dependent data of not intersecting _LayerEdge's
2763 // neighboring the intersecting ones
2765 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2767 _LayerEdge* edge1 = e2ee->first;
2768 if ( !edge1->_2neibors )
2770 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2772 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2773 if ( edge2CloseEdge.count ( neighbor ))
2774 continue; // j-th neighbor is also intersected
2775 _LayerEdge* prevEdge = edge1;
2776 const int nbSteps = 6;
2777 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2779 if ( !neighbor->_2neibors )
2780 break; // neighbor is on VERTEX
2782 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2783 if ( nextEdge == prevEdge )
2784 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2785 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2786 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
2787 double r = double(step-1)/nbSteps;
2788 if ( !nextEdge->_2neibors )
2791 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2792 newNorm.Normalize();
2794 neighbor->_normal = newNorm;
2795 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2796 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2798 neighbor->InvalidateStep( 1 );
2800 neighbor->SetNewLength( data._stepSize, helper );
2802 // goto the next neighbor
2803 prevEdge = neighbor;
2804 neighbor = nextEdge;
2810 // 2) Check absence of intersections
2813 for ( unsigned i = 0 ; i < tmpFaces.size(); ++i )
2819 //================================================================================
2821 * \brief Looks for intersection of it's last segment with faces
2822 * \param distance - returns shortest distance from the last node to intersection
2824 //================================================================================
2826 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
2828 const double& epsilon,
2829 const SMDS_MeshElement** face)
2831 vector< const SMDS_MeshElement* > suspectFaces;
2833 gp_Ax1 lastSegment = LastSegment(segLen);
2834 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2836 bool segmentIntersected = false;
2837 distance = Precision::Infinite();
2838 int iFace = -1; // intersected face
2839 for ( unsigned j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
2841 const SMDS_MeshElement* face = suspectFaces[j];
2842 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
2843 face->GetNodeIndex( _nodes[0] ) >= 0 )
2844 continue; // face sharing _LayerEdge node
2845 const int nbNodes = face->NbCornerNodes();
2846 bool intFound = false;
2848 SMDS_MeshElement::iterator nIt = face->begin_nodes();
2851 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
2855 const SMDS_MeshNode* tria[3];
2858 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
2861 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
2867 if ( dist < segLen*(1.01) && dist > -(_len-segLen) )
2868 segmentIntersected = true;
2869 if ( distance > dist )
2870 distance = dist, iFace = j;
2873 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
2874 // if ( distance && iFace > -1 )
2876 // // distance is used to limit size of inflation step which depends on
2877 // // whether the intersected face bears viscous layers or not
2878 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
2882 if ( segmentIntersected )
2885 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
2886 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
2887 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
2888 << ", intersection with face ("
2889 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2890 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
2891 << ") distance = " << distance - segLen<< endl;
2897 return segmentIntersected;
2900 //================================================================================
2902 * \brief Returns size and direction of the last segment
2904 //================================================================================
2906 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
2908 // find two non-coincident positions
2909 gp_XYZ orig = _pos.back();
2911 int iPrev = _pos.size() - 2;
2912 while ( iPrev >= 0 )
2914 dir = orig - _pos[iPrev];
2915 if ( dir.SquareModulus() > 1e-100 )
2925 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
2926 segDir.SetDirection( _normal );
2931 gp_Pnt pPrev = _pos[ iPrev ];
2932 if ( !_sWOL.IsNull() )
2934 TopLoc_Location loc;
2935 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2938 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2939 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
2943 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2944 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
2946 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
2948 segDir.SetLocation( pPrev );
2949 segDir.SetDirection( dir );
2950 segLen = dir.Modulus();
2956 //================================================================================
2958 * \brief Test intersection of the last segment with a given triangle
2959 * using Moller-Trumbore algorithm
2960 * Intersection is detected if distance to intersection is less than _LayerEdge._len
2962 //================================================================================
2964 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
2965 const SMDS_MeshNode* n0,
2966 const SMDS_MeshNode* n1,
2967 const SMDS_MeshNode* n2,
2969 const double& EPSILON) const
2971 //const double EPSILON = 1e-6;
2973 gp_XYZ orig = lastSegment.Location().XYZ();
2974 gp_XYZ dir = lastSegment.Direction().XYZ();
2976 SMESH_TNodeXYZ vert0( n0 );
2977 SMESH_TNodeXYZ vert1( n1 );
2978 SMESH_TNodeXYZ vert2( n2 );
2980 /* calculate distance from vert0 to ray origin */
2981 gp_XYZ tvec = orig - vert0;
2983 if ( tvec * dir > EPSILON )
2984 // intersected face is at back side of the temporary face this _LayerEdge belongs to
2987 gp_XYZ edge1 = vert1 - vert0;
2988 gp_XYZ edge2 = vert2 - vert0;
2990 /* begin calculating determinant - also used to calculate U parameter */
2991 gp_XYZ pvec = dir ^ edge2;
2993 /* if determinant is near zero, ray lies in plane of triangle */
2994 double det = edge1 * pvec;
2996 if (det > -EPSILON && det < EPSILON)
2998 double inv_det = 1.0 / det;
3000 /* calculate U parameter and test bounds */
3001 double u = ( tvec * pvec ) * inv_det;
3002 if (u < 0.0 || u > 1.0)
3005 /* prepare to test V parameter */
3006 gp_XYZ qvec = tvec ^ edge1;
3008 /* calculate V parameter and test bounds */
3009 double v = (dir * qvec) * inv_det;
3010 if ( v < 0.0 || u + v > 1.0 )
3013 /* calculate t, ray intersects triangle */
3014 t = (edge2 * qvec) * inv_det;
3016 // if (det < EPSILON)
3019 // /* calculate distance from vert0 to ray origin */
3020 // gp_XYZ tvec = orig - vert0;
3022 // /* calculate U parameter and test bounds */
3023 // double u = tvec * pvec;
3024 // if (u < 0.0 || u > det)
3027 // /* prepare to test V parameter */
3028 // gp_XYZ qvec = tvec ^ edge1;
3030 // /* calculate V parameter and test bounds */
3031 // double v = dir * qvec;
3032 // if (v < 0.0 || u + v > det)
3035 // /* calculate t, scale parameters, ray intersects triangle */
3036 // double t = edge2 * qvec;
3037 // double inv_det = 1.0 / det;
3045 //================================================================================
3047 * \brief Perform smooth of _LayerEdge's based on EDGE's
3048 * \retval bool - true if node has been moved
3050 //================================================================================
3052 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3053 const TopoDS_Face& F,
3054 SMESH_MesherHelper& helper)
3056 ASSERT( IsOnEdge() );
3058 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3059 SMESH_TNodeXYZ oldPos( tgtNode );
3060 double dist01, distNewOld;
3062 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3063 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3064 dist01 = p0.Distance( _2neibors->_nodes[1] );
3066 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3067 double lenDelta = 0;
3070 //lenDelta = _curvature->lenDelta( _len );
3071 lenDelta = _curvature->lenDeltaByDist( dist01 );
3072 newPos.ChangeCoord() += _normal * lenDelta;
3075 distNewOld = newPos.Distance( oldPos );
3079 if ( _2neibors->_plnNorm )
3081 // put newPos on the plane defined by source node and _plnNorm
3082 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3083 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3084 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3086 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3087 _pos.back() = newPos.XYZ();
3091 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3092 gp_XY uv( Precision::Infinite(), 0 );
3093 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3094 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3096 newPos = surface->Value( uv.X(), uv.Y() );
3097 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3100 if ( _curvature && lenDelta < 0 )
3102 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3103 _len -= prevPos.Distance( oldPos );
3104 _len += prevPos.Distance( newPos );
3106 bool moved = distNewOld > dist01/50;
3108 dumpMove( tgtNode ); // debug
3113 //================================================================================
3115 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3116 * \retval bool - true if _tgtNode has been moved
3118 //================================================================================
3120 bool _LayerEdge::Smooth(int& badNb)
3122 if ( _simplices.size() < 2 )
3123 return false; // _LayerEdge inflated along EDGE or FACE
3125 // compute new position for the last _pos
3126 gp_XYZ newPos (0,0,0);
3127 for ( unsigned i = 0; i < _simplices.size(); ++i )
3128 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3129 newPos /= _simplices.size();
3132 newPos += _normal * _curvature->lenDelta( _len );
3134 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3135 // if ( _cosin < -0.1)
3137 // // Avoid decreasing length of edge on concave surface
3138 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3139 // gp_Vec newMove( prevPos, newPos );
3140 // newPos = _pos.back() + newMove.XYZ();
3142 // else if ( _cosin > 0.3 )
3144 // // Avoid increasing length of edge too much
3147 // count quality metrics (orientation) of tetras around _tgtNode
3149 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3150 for ( unsigned i = 0; i < _simplices.size(); ++i )
3151 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3154 for ( unsigned i = 0; i < _simplices.size(); ++i )
3155 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3157 if ( nbOkAfter < nbOkBefore )
3160 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3162 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3163 _len += prevPos.Distance(newPos);
3165 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3166 _pos.back() = newPos;
3168 badNb += _simplices.size() - nbOkAfter;
3175 //================================================================================
3177 * \brief Add a new segment to _LayerEdge during inflation
3179 //================================================================================
3181 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3183 if ( _len - len > -1e-6 )
3185 _pos.push_back( _pos.back() );
3189 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3190 SMESH_TNodeXYZ oldXYZ( n );
3191 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3192 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3194 _pos.push_back( nXYZ );
3196 if ( !_sWOL.IsNull() )
3199 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3201 double u = Precision::Infinite(); // to force projection w/o distance check
3202 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3203 _pos.back().SetCoord( u, 0, 0 );
3204 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3205 pos->SetUParameter( u );
3209 gp_XY uv( Precision::Infinite(), 0 );
3210 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3211 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3212 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3213 pos->SetUParameter( uv.X() );
3214 pos->SetVParameter( uv.Y() );
3216 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3218 dumpMove( n ); //debug
3221 //================================================================================
3223 * \brief Remove last inflation step
3225 //================================================================================
3227 void _LayerEdge::InvalidateStep( int curStep )
3229 if ( _pos.size() > curStep )
3231 _pos.resize( curStep );
3232 gp_Pnt nXYZ = _pos.back();
3233 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3234 if ( !_sWOL.IsNull() )
3236 TopLoc_Location loc;
3237 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3239 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3240 pos->SetUParameter( nXYZ.X() );
3242 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3243 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3247 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3248 pos->SetUParameter( nXYZ.X() );
3249 pos->SetVParameter( nXYZ.Y() );
3250 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3251 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3254 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3259 //================================================================================
3261 * \brief Create layers of prisms
3263 //================================================================================
3265 bool _ViscousBuilder::refine(_SolidData& data)
3267 SMESH_MesherHelper helper( *_mesh );
3268 helper.SetSubShape( data._solid );
3269 helper.SetElementsOnShape(false);
3271 Handle(Geom_Curve) curve;
3272 Handle(Geom_Surface) surface;
3273 TopoDS_Edge geomEdge;
3274 TopoDS_Face geomFace;
3275 TopLoc_Location loc;
3276 double f,l, u/*, distXYZ[4]*/;
3280 for ( unsigned i = 0; i < data._edges.size(); ++i )
3282 _LayerEdge& edge = *data._edges[i];
3284 // get accumulated length of segments
3285 vector< double > segLen( edge._pos.size() );
3287 for ( unsigned j = 1; j < edge._pos.size(); ++j )
3288 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3290 // allocate memory for new nodes if it is not yet refined
3291 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3292 if ( edge._nodes.size() == 2 )
3294 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3296 edge._nodes.back() = tgtNode;
3298 if ( !edge._sWOL.IsNull() )
3300 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3301 // restore position of the last node
3305 geomEdge = TopoDS::Edge( edge._sWOL );
3306 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3307 // double u = helper.GetNodeU( tgtNode );
3308 // p = curve->Value( u );
3312 geomFace = TopoDS::Face( edge._sWOL );
3313 surface = BRep_Tool::Surface( geomFace, loc );
3314 // gp_XY uv = helper.GetNodeUV( tgtNode );
3315 // p = surface->Value( uv.X(), uv.Y() );
3317 // p.Transform( loc );
3318 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3320 // calculate height of the first layer
3322 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3323 const double f = data._hyp->GetStretchFactor();
3324 const int N = data._hyp->GetNumberLayers();
3325 const double fPowN = pow( f, N );
3326 if ( fPowN - 1 <= numeric_limits<double>::min() )
3329 h0 = T * ( f - 1 )/( fPowN - 1 );
3331 const double zeroLen = std::numeric_limits<double>::min();
3333 // create intermediate nodes
3334 double hSum = 0, hi = h0/f;
3336 for ( unsigned iStep = 1; iStep < edge._nodes.size(); ++iStep )
3338 // compute an intermediate position
3341 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3343 int iPrevSeg = iSeg-1;
3344 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3346 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3347 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3349 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3350 if ( !edge._sWOL.IsNull() )
3352 // compute XYZ by parameters <pos>
3356 pos = curve->Value( u ).Transformed(loc);
3360 uv.SetCoord( pos.X(), pos.Y() );
3361 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3364 // create or update the node
3367 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3368 if ( !edge._sWOL.IsNull() )
3371 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3373 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3377 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3382 if ( !edge._sWOL.IsNull() )
3384 // make average pos from new and current parameters
3387 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3388 pos = curve->Value( u ).Transformed(loc);
3392 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3393 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3396 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3401 if ( !getMeshDS()->IsEmbeddedMode() )
3402 // Log node movement
3403 for ( unsigned i = 0; i < data._edges.size(); ++i )
3405 _LayerEdge& edge = *data._edges[i];
3406 SMESH_TNodeXYZ p ( edge._nodes.back() );
3407 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
3410 // TODO: make quadratic prisms and polyhedrons(?)
3412 helper.SetElementsOnShape(true);
3414 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3415 for ( ; exp.More(); exp.Next() )
3417 if ( _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3419 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3420 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3421 vector< vector<const SMDS_MeshNode*>* > nnVec;
3422 while ( fIt->more() )
3424 const SMDS_MeshElement* face = fIt->next();
3425 int nbNodes = face->NbCornerNodes();
3426 nnVec.resize( nbNodes );
3427 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3428 for ( int iN = 0; iN < nbNodes; ++iN )
3430 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3431 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3434 int nbZ = nnVec[0]->size();
3438 for ( int iZ = 1; iZ < nbZ; ++iZ )
3439 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3440 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3443 for ( int iZ = 1; iZ < nbZ; ++iZ )
3444 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3445 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3446 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3447 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3450 return error("Not supported type of element", data._index);
3457 //================================================================================
3459 * \brief Shrink 2D mesh on faces to let space for inflated layers
3461 //================================================================================
3463 bool _ViscousBuilder::shrink()
3465 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3466 // inflated along FACE or EDGE)
3467 map< TGeomID, _SolidData* > f2sdMap;
3468 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
3470 _SolidData& data = _sdVec[i];
3471 TopTools_MapOfShape FFMap;
3472 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3473 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3474 if ( s2s->second.ShapeType() == TopAbs_FACE )
3476 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3478 if ( FFMap.Add( (*s2s).second ))
3479 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3480 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3481 // by StdMeshers_QuadToTriaAdaptor
3482 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3484 SMESH_ProxyMesh::SubMesh* proxySub =
3485 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3486 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3487 while ( fIt->more() )
3488 proxySub->AddElement( fIt->next() );
3489 // as a result 3D algo will use elements from proxySub and not from smDS
3494 SMESH_MesherHelper helper( *_mesh );
3495 helper.ToFixNodeParameters( true );
3498 map< TGeomID, _Shrinker1D > e2shrMap;
3500 // loop on FACES to srink mesh on
3501 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3502 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3504 _SolidData& data = *f2sd->second;
3505 TNode2Edge& n2eMap = data._n2eMap;
3506 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3508 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3510 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3511 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3513 helper.SetSubShape(F);
3515 // ===========================
3516 // Prepare data for shrinking
3517 // ===========================
3519 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3520 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3521 vector < const SMDS_MeshNode* > smoothNodes;
3523 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3524 while ( nIt->more() )
3526 const SMDS_MeshNode* n = nIt->next();
3527 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3528 smoothNodes.push_back( n );
3531 // Find out face orientation
3533 const set<TGeomID> ignoreShapes;
3535 if ( !smoothNodes.empty() )
3537 vector<_Simplex> simplices;
3538 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3539 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3540 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3541 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3542 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3546 // Find _LayerEdge's inflated along F
3547 vector< _LayerEdge* > lEdges;
3549 SMESH_subMeshIteratorPtr subIt =
3550 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3551 while ( subIt->more() )
3553 SMESH_subMesh* sub = subIt->next();
3554 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3555 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3557 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3558 while ( nIt->more() )
3560 _LayerEdge* edge = n2eMap[ nIt->next() ];
3561 lEdges.push_back( edge );
3562 prepareEdgeToShrink( *edge, F, helper, smDS );
3567 // Replace source nodes by target nodes in mesh faces to shrink
3568 const SMDS_MeshNode* nodes[20];
3569 for ( unsigned i = 0; i < lEdges.size(); ++i )
3571 _LayerEdge& edge = *lEdges[i];
3572 const SMDS_MeshNode* srcNode = edge._nodes[0];
3573 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3574 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3575 while ( fIt->more() )
3577 const SMDS_MeshElement* f = fIt->next();
3578 if ( !smDS->Contains( f ))
3580 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3581 for ( int iN = 0; iN < f->NbNodes(); ++iN )
3583 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3584 nodes[iN] = ( n == srcNode ? tgtNode : n );
3586 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3590 // find out if a FACE is concave
3591 const bool isConcaveFace = isConcave( F, helper );
3593 // Create _SmoothNode's on face F
3594 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3596 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3597 for ( unsigned i = 0; i < smoothNodes.size(); ++i )
3599 const SMDS_MeshNode* n = smoothNodes[i];
3600 nodesToSmooth[ i ]._node = n;
3601 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3602 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, isConcaveFace );
3603 // fix up incorrect uv of nodes on the FACE
3604 helper.GetNodeUV( F, n, 0, &isOkUV);
3609 //if ( nodesToSmooth.empty() ) continue;
3611 // Find EDGE's to shrink
3612 set< _Shrinker1D* > eShri1D;
3614 for ( unsigned i = 0; i < lEdges.size(); ++i )
3616 _LayerEdge* edge = lEdges[i];
3617 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3619 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3620 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3621 eShri1D.insert( & srinker );
3622 srinker.AddEdge( edge, helper );
3623 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
3624 // restore params of nodes on EGDE if the EDGE has been already
3625 // srinked while srinking another FACE
3626 srinker.RestoreParams();
3631 // ==================
3632 // Perform shrinking
3633 // ==================
3635 bool shrinked = true;
3636 int badNb, shriStep=0, smooStep=0;
3639 // Move boundary nodes (actually just set new UV)
3640 // -----------------------------------------------
3641 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep++ ); // debug
3643 for ( unsigned i = 0; i < lEdges.size(); ++i )
3645 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3649 // Move nodes on EDGE's
3650 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3651 for ( ; shr != eShri1D.end(); ++shr )
3652 (*shr)->Compute( /*set3D=*/false, helper );
3655 // -----------------
3656 int nbNoImpSteps = 0;
3659 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3661 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3663 int oldBadNb = badNb;
3666 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3668 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3669 /*isCentroidal=*/isConcaveFace,
3670 /*set3D=*/isConcaveFace);
3672 if ( badNb < oldBadNb )
3680 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3682 // No wrongly shaped faces remain; final smooth. Set node XYZ.
3683 // First, find out a needed quality of smoothing (high for quadrangles only)
3686 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
3687 if ( hasTria != hasQuad ) {
3688 highQuality = hasQuad;
3691 set<int> nbNodesSet;
3692 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3693 while ( fIt->more() && nbNodesSet.size() < 2 )
3694 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
3695 highQuality = ( *nbNodesSet.begin() == 4 );
3698 if ( !highQuality && isConcaveFace )
3699 fixBadFaces( F, helper ); // fix narrow faces by swaping diagonals
3700 for ( int st = highQuality ? 10 : 3; st; --st )
3702 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3703 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3704 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3705 /*isCentroidal=*/isConcaveFace,/*set3D=*/st==1 );
3708 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
3709 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
3711 if ( !getMeshDS()->IsEmbeddedMode() )
3712 // Log node movement
3713 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3715 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
3716 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
3719 } // loop on FACES to srink mesh on
3722 // Replace source nodes by target nodes in shrinked mesh edges
3724 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3725 for ( ; e2shr != e2shrMap.end(); ++e2shr )
3726 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3731 //================================================================================
3733 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3735 //================================================================================
3737 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
3738 const TopoDS_Face& F,
3739 SMESH_MesherHelper& helper,
3740 const SMESHDS_SubMesh* faceSubMesh)
3742 const SMDS_MeshNode* srcNode = edge._nodes[0];
3743 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3747 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3749 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3750 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3751 gp_Vec2d uvDir( srcUV, tgtUV );
3752 double uvLen = uvDir.Magnitude();
3754 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3756 // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3757 vector<const SMDS_MeshElement*> faces;
3758 multimap< double, const SMDS_MeshNode* > proj2node;
3759 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3760 while ( fIt->more() )
3762 const SMDS_MeshElement* f = fIt->next();
3763 if ( faceSubMesh->Contains( f ))
3764 faces.push_back( f );
3766 for ( unsigned i = 0; i < faces.size(); ++i )
3768 const int nbNodes = faces[i]->NbCornerNodes();
3769 for ( int j = 0; j < nbNodes; ++j )
3771 const SMDS_MeshNode* n = faces[i]->GetNode(j);
3772 if ( n == srcNode ) continue;
3773 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3774 ( faces.size() > 1 || nbNodes > 3 ))
3776 gp_Pnt2d uv = helper.GetNodeUV( F, n );
3777 gp_Vec2d uvDirN( srcUV, uv );
3778 double proj = uvDirN * uvDir;
3779 proj2node.insert( make_pair( proj, n ));
3783 multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
3784 const double minProj = p2n->first;
3785 const double projThreshold = 1.1 * uvLen;
3786 if ( minProj > projThreshold )
3788 // tgtNode is located so that it does not make faces with wrong orientation
3791 edge._pos.resize(1);
3792 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
3794 // store most risky nodes in _simplices
3795 p2nEnd = proj2node.lower_bound( projThreshold );
3796 int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
3797 edge._simplices.resize( nbSimpl );
3798 for ( int i = 0; i < nbSimpl; ++i )
3800 edge._simplices[i]._nPrev = p2n->second;
3801 if ( ++p2n != p2nEnd )
3802 edge._simplices[i]._nNext = p2n->second;
3804 // set UV of source node to target node
3805 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3806 pos->SetUParameter( srcUV.X() );
3807 pos->SetVParameter( srcUV.Y() );
3809 else // _sWOL is TopAbs_EDGE
3811 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
3812 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
3813 if ( !edgeSM || edgeSM->NbElements() == 0 )
3814 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3816 const SMDS_MeshNode* n2 = 0;
3817 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3818 while ( eIt->more() && !n2 )
3820 const SMDS_MeshElement* e = eIt->next();
3821 if ( !edgeSM->Contains(e)) continue;
3822 n2 = e->GetNode( 0 );
3823 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
3826 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3828 double uSrc = helper.GetNodeU( E, srcNode, n2 );
3829 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
3830 double u2 = helper.GetNodeU( E, n2, srcNode );
3832 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
3834 // tgtNode is located so that it does not make faces with wrong orientation
3837 edge._pos.resize(1);
3838 edge._pos[0].SetCoord( U_TGT, uTgt );
3839 edge._pos[0].SetCoord( U_SRC, uSrc );
3840 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
3842 edge._simplices.resize( 1 );
3843 edge._simplices[0]._nPrev = n2;
3845 // set UV of source node to target node
3846 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3847 pos->SetUParameter( uSrc );
3851 //================================================================================
3853 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
3855 //================================================================================
3857 // Compute UV to follow during shrinking
3859 // const SMDS_MeshNode* srcNode = edge._nodes[0];
3860 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
3862 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3863 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3864 // gp_Vec2d uvDir( srcUV, tgtUV );
3865 // double uvLen = uvDir.Magnitude();
3868 // // Select shrinking step such that not to make faces with wrong orientation.
3869 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3870 // const double minStepSize = uvLen / 20;
3871 // double stepSize = uvLen;
3872 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3873 // while ( fIt->more() )
3875 // const SMDS_MeshElement* f = fIt->next();
3876 // if ( !faceSubMesh->Contains( f )) continue;
3877 // const int nbNodes = f->NbCornerNodes();
3878 // for ( int i = 0; i < nbNodes; ++i )
3880 // const SMDS_MeshNode* n = f->GetNode(i);
3881 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
3883 // gp_XY uv = helper.GetNodeUV( F, n );
3884 // gp_Vec2d uvDirN( srcUV, uv );
3885 // double proj = uvDirN * uvDir;
3886 // if ( proj < stepSize && proj > minStepSize )
3892 // const int nbSteps = ceil( uvLen / stepSize );
3893 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
3894 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
3895 // edge._pos.resize( nbSteps );
3896 // edge._pos[0] = tgtUV0;
3897 // for ( int i = 1; i < nbSteps; ++i )
3899 // double r = i / double( nbSteps );
3900 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
3905 //================================================================================
3907 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
3909 //================================================================================
3911 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper)
3913 SMESH::Controls::AspectRatio qualifier;
3914 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
3915 const double maxAspectRatio = 4.;
3917 // find bad triangles
3919 vector< const SMDS_MeshElement* > badTrias;
3920 vector< double > badAspects;
3921 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
3922 SMDS_ElemIteratorPtr fIt = sm->GetElements();
3923 while ( fIt->more() )
3925 const SMDS_MeshElement * f = fIt->next();
3926 if ( f->NbCornerNodes() != 3 ) continue;
3927 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = SMESH_TNodeXYZ( f->GetNode(iP));
3928 double aspect = qualifier.GetValue( points );
3929 if ( aspect > maxAspectRatio )
3931 badTrias.push_back( f );
3932 badAspects.push_back( aspect );
3935 if ( badTrias.empty() )
3938 // find couples of faces to swap diagonal
3940 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
3941 vector< T2Trias > triaCouples;
3943 TIDSortedElemSet involvedFaces, emptySet;
3944 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
3947 double aspRatio [3];
3950 involvedFaces.insert( badTrias[iTia] );
3951 for ( int iP = 0; iP < 3; ++iP )
3952 points(iP+1) = SMESH_TNodeXYZ( badTrias[iTia]->GetNode(iP));
3954 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
3955 int bestCouple = -1;
3956 for ( int iSide = 0; iSide < 3; ++iSide )
3958 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
3959 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
3960 trias [iSide].first = badTrias[iTia];
3961 trias [iSide].second = SMESH_MeshEditor::FindFaceInSet( n1, n2, emptySet, involvedFaces,
3963 if ( ! trias[iSide].second || trias[iSide].second->NbCornerNodes() != 3 )
3966 // aspect ratio of an adjacent tria
3967 for ( int iP = 0; iP < 3; ++iP )
3968 points2(iP+1) = SMESH_TNodeXYZ( trias[iSide].second->GetNode(iP));
3969 double aspectInit = qualifier.GetValue( points2 );
3971 // arrange nodes as after diag-swaping
3972 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
3973 i3 = helper.WrapIndex( i1-1, 3 );
3975 i3 = helper.WrapIndex( i1+1, 3 );
3977 points1( 1+ iSide ) = points2( 1+ i3 );
3978 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
3980 // aspect ratio after diag-swaping
3981 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
3982 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
3985 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
3989 if ( bestCouple >= 0 )
3991 triaCouples.push_back( trias[bestCouple] );
3992 involvedFaces.insert ( trias[bestCouple].second );
3996 involvedFaces.erase( badTrias[iTia] );
3999 if ( triaCouples.empty() )
4004 SMESH_MeshEditor editor( helper.GetMesh() );
4005 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
4006 for ( size_t i = 0; i < triaCouples.size(); ++i )
4008 dumpChangeNodes( triaCouples[i].first );
4009 dumpChangeNodes( triaCouples[i].second );
4010 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
4014 // just for debug dump resulting triangles
4015 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID());
4016 for ( size_t i = 0; i < triaCouples.size(); ++i )
4018 dumpChangeNodes( triaCouples[i].first );
4019 dumpChangeNodes( triaCouples[i].second );
4023 //================================================================================
4025 * \brief Move target node to it's final position on the FACE during shrinking
4027 //================================================================================
4029 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
4030 const TopoDS_Face& F,
4031 SMESH_MesherHelper& helper )
4034 return false; // already at the target position
4036 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
4038 if ( _sWOL.ShapeType() == TopAbs_FACE )
4040 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
4041 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y());
4042 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4043 const double uvLen = tgtUV.Distance( curUV );
4045 // Select shrinking step such that not to make faces with wrong orientation.
4046 const double kSafe = 0.8;
4047 const double minStepSize = uvLen / 10;
4048 double stepSize = uvLen;
4049 for ( unsigned i = 0; i < _simplices.size(); ++i )
4051 const SMDS_MeshNode* nn[2] = { _simplices[i]._nPrev, _simplices[i]._nNext };
4052 for ( int j = 0; j < 2; ++j )
4053 if ( const SMDS_MeshNode* n = nn[j] )
4055 gp_XY uv = helper.GetNodeUV( F, n );
4056 gp_Vec2d uvDirN( curUV, uv );
4057 double proj = uvDirN * uvDir * kSafe;
4058 if ( proj < stepSize && proj > minStepSize )
4064 if ( stepSize == uvLen )
4071 newUV = curUV + uvDir.XY() * stepSize;
4074 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4075 pos->SetUParameter( newUV.X() );
4076 pos->SetVParameter( newUV.Y() );
4079 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4080 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4081 dumpMove( tgtNode );
4084 else // _sWOL is TopAbs_EDGE
4086 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4087 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4089 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4090 const double uSrc = _pos[0].Coord( U_SRC );
4091 const double lenTgt = _pos[0].Coord( LEN_TGT );
4093 double newU = _pos[0].Coord( U_TGT );
4094 if ( lenTgt < 0.99 * fabs( uSrc-u2 ))
4100 newU = 0.1 * uSrc + 0.9 * u2;
4102 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4103 pos->SetUParameter( newU );
4105 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4106 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4107 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4108 dumpMove( tgtNode );
4114 //================================================================================
4116 * \brief Perform smooth on the FACE
4117 * \retval bool - true if the node has been moved
4119 //================================================================================
4121 bool _SmoothNode::Smooth(int& badNb,
4122 Handle(Geom_Surface)& surface,
4123 SMESH_MesherHelper& helper,
4124 const double refSign,
4128 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4130 // get uv of surrounding nodes
4131 vector<gp_XY> uv( _simplices.size() );
4132 for ( size_t i = 0; i < _simplices.size(); ++i )
4133 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4135 // compute new UV for the node
4137 if ( isCentroidal && _simplices.size() > 3 )
4139 // average centers of diagonals wieghted with their reciprocal lengths
4140 if ( _simplices.size() == 4 )
4142 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4143 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4144 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4148 double sumWeight = 0;
4149 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4150 for ( int i = 0; i < nb; ++i )
4153 int iTo = i + _simplices.size() - 1;
4154 for ( int j = iFrom; j < iTo; ++j )
4156 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4157 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4159 newPos += w * ( uv[i]+uv[i2] );
4162 newPos /= 2 * sumWeight;
4168 isCentroidal = false;
4169 for ( size_t i = 0; i < _simplices.size(); ++i )
4171 newPos /= _simplices.size();
4174 // count quality metrics (orientation) of triangles around the node
4176 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4177 for ( unsigned i = 0; i < _simplices.size(); ++i )
4178 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4181 for ( unsigned i = 0; i < _simplices.size(); ++i )
4182 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4184 if ( nbOkAfter < nbOkBefore )
4186 // if ( isCentroidal )
4187 // return Smooth( badNb, surface, helper, refSign, !isCentroidal, set3D );
4188 badNb += _simplices.size() - nbOkBefore;
4192 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4193 pos->SetUParameter( newPos.X() );
4194 pos->SetVParameter( newPos.Y() );
4201 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4202 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4206 badNb += _simplices.size() - nbOkAfter;
4207 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4210 //================================================================================
4212 * \brief Delete _SolidData
4214 //================================================================================
4216 _SolidData::~_SolidData()
4218 for ( unsigned i = 0; i < _edges.size(); ++i )
4220 if ( _edges[i] && _edges[i]->_2neibors )
4221 delete _edges[i]->_2neibors;
4226 //================================================================================
4228 * \brief Add a _LayerEdge inflated along the EDGE
4230 //================================================================================
4232 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4235 if ( _nodes.empty() )
4237 _edges[0] = _edges[1] = 0;
4241 if ( e == _edges[0] || e == _edges[1] )
4243 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4244 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4245 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4246 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4249 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4251 BRep_Tool::Range( E, f,l );
4252 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4253 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4257 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4258 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4260 if ( _nodes.empty() )
4262 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4263 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4265 TopLoc_Location loc;
4266 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4267 GeomAdaptor_Curve aCurve(C, f,l);
4268 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4270 int nbExpectNodes = eSubMesh->NbNodes();
4271 _initU .reserve( nbExpectNodes );
4272 _normPar.reserve( nbExpectNodes );
4273 _nodes .reserve( nbExpectNodes );
4274 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4275 while ( nIt->more() )
4277 const SMDS_MeshNode* node = nIt->next();
4278 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4279 node == tgtNode0 || node == tgtNode1 )
4280 continue; // refinement nodes
4281 _nodes.push_back( node );
4282 _initU.push_back( helper.GetNodeU( E, node ));
4283 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4284 _normPar.push_back( len / totLen );
4289 // remove target node of the _LayerEdge from _nodes
4291 for ( unsigned i = 0; i < _nodes.size(); ++i )
4292 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4293 _nodes[i] = 0, nbFound++;
4294 if ( nbFound == _nodes.size() )
4299 //================================================================================
4301 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4303 //================================================================================
4305 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4307 if ( _done || _nodes.empty())
4309 const _LayerEdge* e = _edges[0];
4310 if ( !e ) e = _edges[1];
4313 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4314 ( !_edges[1] || _edges[1]->_pos.empty() ));
4316 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4318 if ( set3D || _done )
4320 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4321 GeomAdaptor_Curve aCurve(C, f,l);
4324 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4326 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4327 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4329 for ( unsigned i = 0; i < _nodes.size(); ++i )
4331 if ( !_nodes[i] ) continue;
4332 double len = totLen * _normPar[i];
4333 GCPnts_AbscissaPoint discret( aCurve, len, f );
4334 if ( !discret.IsDone() )
4335 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4336 double u = discret.Parameter();
4337 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4338 pos->SetUParameter( u );
4339 gp_Pnt p = C->Value( u );
4340 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4345 BRep_Tool::Range( E, f,l );
4347 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4349 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4351 for ( unsigned i = 0; i < _nodes.size(); ++i )
4353 if ( !_nodes[i] ) continue;
4354 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4355 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4356 pos->SetUParameter( u );
4361 //================================================================================
4363 * \brief Restore initial parameters of nodes on EDGE
4365 //================================================================================
4367 void _Shrinker1D::RestoreParams()
4370 for ( unsigned i = 0; i < _nodes.size(); ++i )
4372 if ( !_nodes[i] ) continue;
4373 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4374 pos->SetUParameter( _initU[i] );
4379 //================================================================================
4381 * \brief Replace source nodes by target nodes in shrinked mesh edges
4383 //================================================================================
4385 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4387 const SMDS_MeshNode* nodes[3];
4388 for ( int i = 0; i < 2; ++i )
4390 if ( !_edges[i] ) continue;
4392 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4393 if ( !eSubMesh ) return;
4394 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4395 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4396 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4397 while ( eIt->more() )
4399 const SMDS_MeshElement* e = eIt->next();
4400 if ( !eSubMesh->Contains( e ))
4402 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4403 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4405 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4406 nodes[iN] = ( n == srcNode ? tgtNode : n );
4408 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4413 //================================================================================
4415 * \brief Creates 2D and 1D elements on boundaries of new prisms
4417 //================================================================================
4419 bool _ViscousBuilder::addBoundaryElements()
4421 SMESH_MesherHelper helper( *_mesh );
4423 for ( unsigned i = 0; i < _sdVec.size(); ++i )
4425 _SolidData& data = _sdVec[i];
4426 TopTools_IndexedMapOfShape geomEdges;
4427 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4428 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4430 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4432 // Get _LayerEdge's based on E
4434 map< double, const SMDS_MeshNode* > u2nodes;
4435 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4438 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
4439 TNode2Edge & n2eMap = data._n2eMap;
4440 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4442 //check if 2D elements are needed on E
4443 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
4444 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
4445 ledges.push_back( n2e->second );
4447 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
4448 continue; // no layers on E
4449 ledges.push_back( n2eMap[ u2n->second ]);
4451 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
4452 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
4453 int nbSharedPyram = 0;
4454 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
4455 while ( vIt->more() )
4457 const SMDS_MeshElement* v = vIt->next();
4458 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
4460 if ( nbSharedPyram > 1 )
4461 continue; // not free border of the pyramid
4463 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
4464 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
4465 continue; // faces already created
4467 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
4468 ledges.push_back( n2eMap[ u2n->second ]);
4470 // Find out orientation and type of face to create
4472 bool reverse = false, isOnFace;
4474 map< TGeomID, TopoDS_Shape >::iterator e2f =
4475 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
4477 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
4479 F = e2f->second.Oriented( TopAbs_FORWARD );
4480 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
4481 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
4482 reverse = !reverse, F.Reverse();
4483 if ( SMESH_Algo::IsReversedSubMesh( TopoDS::Face(F), getMeshDS() ))
4488 // find FACE with layers sharing E
4489 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
4490 while ( fIt->more() && F.IsNull() )
4492 const TopoDS_Shape* pF = fIt->next();
4493 if ( helper.IsSubShape( *pF, data._solid) &&
4494 !_ignoreShapeIds.count( e2f->first ))
4498 // Find the sub-mesh to add new faces
4499 SMESHDS_SubMesh* sm = 0;
4501 sm = getMeshDS()->MeshElements( F );
4503 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
4505 return error("error in addBoundaryElements()", data._index);
4508 const int dj1 = reverse ? 0 : 1;
4509 const int dj2 = reverse ? 1 : 0;
4510 for ( unsigned j = 1; j < ledges.size(); ++j )
4512 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
4513 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
4515 for ( size_t z = 1; z < nn1.size(); ++z )
4516 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
4518 for ( size_t z = 1; z < nn1.size(); ++z )
4519 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
4523 for ( int isFirst = 0; isFirst < 2; ++isFirst )
4525 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
4526 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
4528 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
4529 if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
4531 helper.SetSubShape( edge->_sWOL );
4532 helper.SetElementsOnShape( true );
4533 for ( size_t z = 1; z < nn.size(); ++z )
4534 helper.AddEdge( nn[z-1], nn[z] );