1 // Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE
3 // This library is free software; you can redistribute it and/or
4 // modify it under the terms of the GNU Lesser General Public
5 // License as published by the Free Software Foundation; either
6 // version 2.1 of the License.
8 // This library is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 // Lesser General Public License for more details.
13 // You should have received a copy of the GNU Lesser General Public
14 // License along with this library; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
20 // File : StdMeshers_ViscousLayers.cxx
21 // Created : Wed Dec 1 15:15:34 2010
22 // Author : Edward AGAPOV (eap)
24 #include "StdMeshers_ViscousLayers.hxx"
26 #include "SMDS_EdgePosition.hxx"
27 #include "SMDS_FaceOfNodes.hxx"
28 #include "SMDS_FacePosition.hxx"
29 #include "SMDS_MeshNode.hxx"
30 #include "SMDS_SetIterator.hxx"
31 #include "SMESHDS_Group.hxx"
32 #include "SMESHDS_Hypothesis.hxx"
33 #include "SMESH_Algo.hxx"
34 #include "SMESH_ComputeError.hxx"
35 #include "SMESH_ControlsDef.hxx"
36 #include "SMESH_Gen.hxx"
37 #include "SMESH_Group.hxx"
38 #include "SMESH_Mesh.hxx"
39 #include "SMESH_MeshAlgos.hxx"
40 #include "SMESH_MesherHelper.hxx"
41 #include "SMESH_ProxyMesh.hxx"
42 #include "SMESH_subMesh.hxx"
43 #include "SMESH_subMeshEventListener.hxx"
45 #include "utilities.h"
47 #include <BRepAdaptor_Curve2d.hxx>
48 #include <BRep_Tool.hxx>
49 #include <Bnd_B2d.hxx>
50 #include <Bnd_B3d.hxx>
52 #include <GCPnts_AbscissaPoint.hxx>
53 #include <Geom2d_Circle.hxx>
54 #include <Geom2d_Line.hxx>
55 #include <Geom2d_TrimmedCurve.hxx>
56 #include <GeomAdaptor_Curve.hxx>
57 #include <Geom_Circle.hxx>
58 #include <Geom_Curve.hxx>
59 #include <Geom_Line.hxx>
60 #include <Geom_TrimmedCurve.hxx>
61 #include <Precision.hxx>
62 #include <Standard_ErrorHandler.hxx>
63 #include <TColStd_Array1OfReal.hxx>
65 #include <TopExp_Explorer.hxx>
66 #include <TopTools_IndexedMapOfShape.hxx>
67 #include <TopTools_MapOfShape.hxx>
69 #include <TopoDS_Edge.hxx>
70 #include <TopoDS_Face.hxx>
71 #include <TopoDS_Vertex.hxx>
85 //================================================================================
90 enum UIndex { U_TGT = 1, U_SRC, LEN_TGT };
93 * \brief SMESH_ProxyMesh computed by _ViscousBuilder for a SOLID.
94 * It is stored in a SMESH_subMesh of the SOLID as SMESH_subMeshEventListenerData
96 struct _MeshOfSolid : public SMESH_ProxyMesh,
97 public SMESH_subMeshEventListenerData
101 _MeshOfSolid( SMESH_Mesh* mesh)
102 :SMESH_subMeshEventListenerData( /*isDeletable=*/true),_n2nMapComputed(false)
104 SMESH_ProxyMesh::setMesh( *mesh );
107 // returns submesh for a geom face
108 SMESH_ProxyMesh::SubMesh* getFaceSubM(const TopoDS_Face& F, bool create=false)
110 TGeomID i = SMESH_ProxyMesh::shapeIndex(F);
111 return create ? SMESH_ProxyMesh::getProxySubMesh(i) : findProxySubMesh(i);
113 void setNode2Node(const SMDS_MeshNode* srcNode,
114 const SMDS_MeshNode* proxyNode,
115 const SMESH_ProxyMesh::SubMesh* subMesh)
117 SMESH_ProxyMesh::setNode2Node( srcNode,proxyNode,subMesh);
120 //--------------------------------------------------------------------------------
122 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
123 * It is used to clear an inferior dim sub-meshes modified by viscous layers
125 class _ShrinkShapeListener : SMESH_subMeshEventListener
127 _ShrinkShapeListener()
128 : SMESH_subMeshEventListener(/*isDeletable=*/false,
129 "StdMeshers_ViscousLayers::_ShrinkShapeListener") {}
131 static SMESH_subMeshEventListener* Get() { static _ShrinkShapeListener l; return &l; }
132 virtual void ProcessEvent(const int event,
134 SMESH_subMesh* solidSM,
135 SMESH_subMeshEventListenerData* data,
136 const SMESH_Hypothesis* hyp)
138 if ( SMESH_subMesh::COMPUTE_EVENT == eventType && solidSM->IsEmpty() && data )
140 SMESH_subMeshEventListener::ProcessEvent(event,eventType,solidSM,data,hyp);
144 //--------------------------------------------------------------------------------
146 * \brief Listener of events of 3D sub-meshes computed with viscous layers.
147 * It is used to store data computed by _ViscousBuilder for a sub-mesh and to
148 * delete the data as soon as it has been used
150 class _ViscousListener : SMESH_subMeshEventListener
153 SMESH_subMeshEventListener(/*isDeletable=*/false,
154 "StdMeshers_ViscousLayers::_ViscousListener") {}
155 static SMESH_subMeshEventListener* Get() { static _ViscousListener l; return &l; }
157 virtual void ProcessEvent(const int event,
159 SMESH_subMesh* subMesh,
160 SMESH_subMeshEventListenerData* data,
161 const SMESH_Hypothesis* hyp)
163 if ( SMESH_subMesh::COMPUTE_EVENT == eventType )
165 // delete SMESH_ProxyMesh containing temporary faces
166 subMesh->DeleteEventListener( this );
169 // Finds or creates proxy mesh of the solid
170 static _MeshOfSolid* GetSolidMesh(SMESH_Mesh* mesh,
171 const TopoDS_Shape& solid,
174 if ( !mesh ) return 0;
175 SMESH_subMesh* sm = mesh->GetSubMesh(solid);
176 _MeshOfSolid* data = (_MeshOfSolid*) sm->GetEventListenerData( Get() );
177 if ( !data && toCreate )
179 data = new _MeshOfSolid(mesh);
180 data->mySubMeshes.push_back( sm ); // to find SOLID by _MeshOfSolid
181 sm->SetEventListener( Get(), data, sm );
185 // Removes proxy mesh of the solid
186 static void RemoveSolidMesh(SMESH_Mesh* mesh, const TopoDS_Shape& solid)
188 mesh->GetSubMesh(solid)->DeleteEventListener( _ViscousListener::Get() );
192 //================================================================================
194 * \brief sets a sub-mesh event listener to clear sub-meshes of sub-shapes of
195 * the main shape when sub-mesh of the main shape is cleared,
196 * for example to clear sub-meshes of FACEs when sub-mesh of a SOLID
199 //================================================================================
201 void ToClearSubWithMain( SMESH_subMesh* sub, const TopoDS_Shape& main)
203 SMESH_subMesh* mainSM = sub->GetFather()->GetSubMesh( main );
204 SMESH_subMeshEventListenerData* data =
205 mainSM->GetEventListenerData( _ShrinkShapeListener::Get());
208 if ( find( data->mySubMeshes.begin(), data->mySubMeshes.end(), sub ) ==
209 data->mySubMeshes.end())
210 data->mySubMeshes.push_back( sub );
214 data = SMESH_subMeshEventListenerData::MakeData( /*dependent=*/sub );
215 sub->SetEventListener( _ShrinkShapeListener::Get(), data, /*whereToListenTo=*/mainSM );
218 //--------------------------------------------------------------------------------
220 * \brief Simplex (triangle or tetrahedron) based on 1 (tria) or 2 (tet) nodes of
221 * _LayerEdge and 2 nodes of the mesh surface beening smoothed.
222 * The class is used to check validity of face or volumes around a smoothed node;
223 * it stores only 2 nodes as the other nodes are stored by _LayerEdge.
227 const SMDS_MeshNode *_nPrev, *_nNext; // nodes on a smoothed mesh surface
228 _Simplex(const SMDS_MeshNode* nPrev=0, const SMDS_MeshNode* nNext=0)
229 : _nPrev(nPrev), _nNext(nNext) {}
230 bool IsForward(const SMDS_MeshNode* nSrc, const gp_XYZ* pntTgt) const
232 const double M[3][3] =
233 {{ _nNext->X() - nSrc->X(), _nNext->Y() - nSrc->Y(), _nNext->Z() - nSrc->Z() },
234 { pntTgt->X() - nSrc->X(), pntTgt->Y() - nSrc->Y(), pntTgt->Z() - nSrc->Z() },
235 { _nPrev->X() - nSrc->X(), _nPrev->Y() - nSrc->Y(), _nPrev->Z() - nSrc->Z() }};
236 double determinant = ( + M[0][0]*M[1][1]*M[2][2]
237 + M[0][1]*M[1][2]*M[2][0]
238 + M[0][2]*M[1][0]*M[2][1]
239 - M[0][0]*M[1][2]*M[2][1]
240 - M[0][1]*M[1][0]*M[2][2]
241 - M[0][2]*M[1][1]*M[2][0]);
242 return determinant > 1e-100;
244 bool IsForward(const gp_XY& tgtUV,
245 const SMDS_MeshNode* smoothedNode,
246 const TopoDS_Face& face,
247 SMESH_MesherHelper& helper,
248 const double refSign) const
250 gp_XY prevUV = helper.GetNodeUV( face, _nPrev, smoothedNode );
251 gp_XY nextUV = helper.GetNodeUV( face, _nNext, smoothedNode );
252 gp_Vec2d v1( tgtUV, prevUV ), v2( tgtUV, nextUV );
254 return d*refSign > 1e-100;
256 bool IsNeighbour(const _Simplex& other) const
258 return _nPrev == other._nNext || _nNext == other._nPrev;
261 //--------------------------------------------------------------------------------
263 * Structure used to take into account surface curvature while smoothing
268 double _k; // factor to correct node smoothed position
269 double _h2lenRatio; // avgNormProj / (2*avgDist)
271 static _Curvature* New( double avgNormProj, double avgDist )
274 if ( fabs( avgNormProj / avgDist ) > 1./200 )
277 c->_r = avgDist * avgDist / avgNormProj;
278 c->_k = avgDist * avgDist / c->_r / c->_r;
279 c->_k *= ( c->_r < 0 ? 1/1.1 : 1.1 ); // not to be too restrictive
280 c->_h2lenRatio = avgNormProj / ( avgDist + avgDist );
284 double lenDelta(double len) const { return _k * ( _r + len ); }
285 double lenDeltaByDist(double dist) const { return dist * _h2lenRatio; }
288 //--------------------------------------------------------------------------------
290 * Structure used to smooth a _LayerEdge (master) based on an EDGE.
294 // target nodes of 2 neighbour _LayerEdge's based on the same EDGE
295 const SMDS_MeshNode* _nodes[2];
296 // vectors from source nodes of 2 _LayerEdge's to the source node of master _LayerEdge
298 double _wgt[2]; // weights of _nodes
299 _LayerEdge* _edges[2];
301 // normal to plane passing through _LayerEdge._normal and tangent of EDGE
304 _2NearEdges() { _nodes[0]=_nodes[1]=0; _plnNorm = 0; }
306 std::swap( _nodes[0], _nodes[1] );
307 std::swap( _wgt[0], _wgt[1] );
310 //--------------------------------------------------------------------------------
312 * \brief Edge normal to surface, connecting a node on solid surface (_nodes[0])
313 * and a node of the most internal layer (_nodes.back())
317 vector< const SMDS_MeshNode*> _nodes;
319 gp_XYZ _normal; // to solid surface
320 vector<gp_XYZ> _pos; // points computed during inflation
321 double _len; // length achived with the last step
322 double _cosin; // of angle (_normal ^ surface)
323 double _lenFactor; // to compute _len taking _cosin into account
325 // face or edge w/o layer along or near which _LayerEdge is inflated
327 // simplices connected to the source node (_nodes[0]);
328 // used for smoothing and quality check of _LayerEdge's based on the FACE
329 vector<_Simplex> _simplices;
330 // data for smoothing of _LayerEdge's based on the EDGE
331 _2NearEdges* _2neibors;
333 _Curvature* _curvature;
334 // TODO:: detele _Curvature, _plnNorm
336 void SetNewLength( double len, SMESH_MesherHelper& helper );
337 bool SetNewLength2d( Handle(Geom_Surface)& surface,
338 const TopoDS_Face& F,
339 SMESH_MesherHelper& helper );
340 void SetDataByNeighbors( const SMDS_MeshNode* n1,
341 const SMDS_MeshNode* n2,
342 SMESH_MesherHelper& helper);
343 void InvalidateStep( int curStep );
344 bool Smooth(int& badNb);
345 bool SmoothOnEdge(Handle(Geom_Surface)& surface,
346 const TopoDS_Face& F,
347 SMESH_MesherHelper& helper);
348 bool FindIntersection( SMESH_ElementSearcher& searcher,
350 const double& epsilon,
351 const SMDS_MeshElement** face = 0);
352 bool SegTriaInter( const gp_Ax1& lastSegment,
353 const SMDS_MeshNode* n0,
354 const SMDS_MeshNode* n1,
355 const SMDS_MeshNode* n2,
357 const double& epsilon) const;
358 gp_Ax1 LastSegment(double& segLen) const;
359 bool IsOnEdge() const { return _2neibors; }
360 void Copy( _LayerEdge& other, SMESH_MesherHelper& helper );
361 void SetCosin( double cosin );
365 bool operator () (const _LayerEdge* e1, const _LayerEdge* e2) const
367 const bool cmpNodes = ( e1 && e2 && e1->_nodes.size() && e2->_nodes.size() );
368 return cmpNodes ? ( e1->_nodes[0]->GetID() < e2->_nodes[0]->GetID()) : ( e1 < e2 );
371 //--------------------------------------------------------------------------------
373 typedef map< const SMDS_MeshNode*, _LayerEdge*, TIDCompare > TNode2Edge;
375 //--------------------------------------------------------------------------------
377 * \brief Data of a SOLID
382 const StdMeshers_ViscousLayers* _hyp;
383 _MeshOfSolid* _proxyMesh;
384 set<TGeomID> _reversedFaceIds;
386 double _stepSize, _stepSizeCoeff;
387 const SMDS_MeshNode* _stepSizeNodes[2];
390 // edges of _n2eMap. We keep same data in two containers because
391 // iteration over the map is 5 time longer than over the vector
392 vector< _LayerEdge* > _edges;
394 // key: an id of shape (EDGE or VERTEX) shared by a FACE with
395 // layers and a FACE w/o layers
396 // value: the shape (FACE or EDGE) to shrink mesh on.
397 // _LayerEdge's basing on nodes on key shape are inflated along the value shape
398 map< TGeomID, TopoDS_Shape > _shrinkShape2Shape;
400 // FACE's WOL, srink on which is forbiden due to algo on the adjacent SOLID
401 set< TGeomID > _noShrinkFaces;
403 // <EDGE to smooth on> to <it's curve>
404 map< TGeomID,Handle(Geom_Curve)> _edge2curve;
406 // end indices in _edges of _LayerEdge on one shape to smooth
407 vector< int > _endEdgeToSmooth;
409 double _epsilon; // precision for SegTriaInter()
411 int _index; // for debug
413 _SolidData(const TopoDS_Shape& s=TopoDS_Shape(),
414 const StdMeshers_ViscousLayers* h=0,
415 _MeshOfSolid* m=0) :_solid(s), _hyp(h), _proxyMesh(m) {}
418 Handle(Geom_Curve) CurveForSmooth( const TopoDS_Edge& E,
421 Handle(Geom_Surface)& surface,
422 const TopoDS_Face& F,
423 SMESH_MesherHelper& helper);
425 //--------------------------------------------------------------------------------
427 * \brief Data of node on a shrinked FACE
431 const SMDS_MeshNode* _node;
432 //vector<const SMDS_MeshNode*> _nodesAround;
433 vector<_Simplex> _simplices; // for quality check
435 bool Smooth(int& badNb,
436 Handle(Geom_Surface)& surface,
437 SMESH_MesherHelper& helper,
438 const double refSign,
442 //--------------------------------------------------------------------------------
444 * \brief Builder of viscous layers
446 class _ViscousBuilder
451 SMESH_ComputeErrorPtr Compute(SMESH_Mesh& mesh,
452 const TopoDS_Shape& shape);
454 // restore event listeners used to clear an inferior dim sub-mesh modified by viscous layers
455 void RestoreListeners();
457 // computes SMESH_ProxyMesh::SubMesh::_n2n;
458 bool MakeN2NMap( _MeshOfSolid* pm );
462 bool findSolidsWithLayers();
463 bool findFacesWithLayers();
464 bool makeLayer(_SolidData& data);
465 bool setEdgeData(_LayerEdge& edge, const set<TGeomID>& subIds,
466 SMESH_MesherHelper& helper, _SolidData& data);
467 bool findNeiborsOnEdge(const _LayerEdge* edge,
468 const SMDS_MeshNode*& n1,
469 const SMDS_MeshNode*& n2,
471 void getSimplices( const SMDS_MeshNode* node, vector<_Simplex>& simplices,
472 const set<TGeomID>& ingnoreShapes,
473 const _SolidData* dataToCheckOri = 0,
474 const bool toSort = false);
475 bool sortEdges( _SolidData& data,
476 vector< vector<_LayerEdge*> >& edgesByGeom);
477 void limitStepSize( _SolidData& data,
478 const SMDS_MeshElement* face,
480 void limitStepSize( _SolidData& data, const double minSize);
481 bool inflate(_SolidData& data);
482 bool smoothAndCheck(_SolidData& data, const int nbSteps, double & distToIntersection);
483 bool smoothAnalyticEdge( _SolidData& data,
486 Handle(Geom_Surface)& surface,
487 const TopoDS_Face& F,
488 SMESH_MesherHelper& helper);
489 bool updateNormals( _SolidData& data, SMESH_MesherHelper& helper );
490 bool refine(_SolidData& data);
492 bool prepareEdgeToShrink( _LayerEdge& edge, const TopoDS_Face& F,
493 SMESH_MesherHelper& helper,
494 const SMESHDS_SubMesh* faceSubMesh );
495 void fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper);
496 bool addBoundaryElements();
498 bool error( const string& text, int solidID=-1 );
499 SMESHDS_Mesh* getMeshDS() { return _mesh->GetMeshDS(); }
502 void makeGroupOfLE();
505 SMESH_ComputeErrorPtr _error;
507 vector< _SolidData > _sdVec;
508 set<TGeomID> _ignoreShapeIds;
511 //--------------------------------------------------------------------------------
513 * \brief Shrinker of nodes on the EDGE
517 vector<double> _initU;
518 vector<double> _normPar;
519 vector<const SMDS_MeshNode*> _nodes;
520 const _LayerEdge* _edges[2];
523 void AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper );
524 void Compute(bool set3D, SMESH_MesherHelper& helper);
525 void RestoreParams();
526 void SwapSrcTgtNodes(SMESHDS_Mesh* mesh);
528 //--------------------------------------------------------------------------------
530 * \brief Class of temporary mesh face.
531 * We can't use SMDS_FaceOfNodes since it's impossible to set it's ID which is
532 * needed because SMESH_ElementSearcher internaly uses set of elements sorted by ID
534 struct TmpMeshFace : public SMDS_MeshElement
536 vector<const SMDS_MeshNode* > _nn;
537 TmpMeshFace( const vector<const SMDS_MeshNode*>& nodes, int id):
538 SMDS_MeshElement(id), _nn(nodes) {}
539 virtual const SMDS_MeshNode* GetNode(const int ind) const { return _nn[ind]; }
540 virtual SMDSAbs_ElementType GetType() const { return SMDSAbs_Face; }
541 virtual vtkIdType GetVtkType() const { return -1; }
542 virtual SMDSAbs_EntityType GetEntityType() const { return SMDSEntity_Last; }
543 virtual SMDSAbs_GeometryType GetGeomType() const { return SMDSGeom_TRIANGLE; }
544 virtual SMDS_ElemIteratorPtr elementsIterator(SMDSAbs_ElementType type) const
545 { return SMDS_ElemIteratorPtr( new SMDS_NodeVectorElemIterator( _nn.begin(), _nn.end()));}
547 //--------------------------------------------------------------------------------
549 * \brief Class of temporary mesh face storing _LayerEdge it's based on
551 struct TmpMeshFaceOnEdge : public TmpMeshFace
553 _LayerEdge *_le1, *_le2;
554 TmpMeshFaceOnEdge( _LayerEdge* le1, _LayerEdge* le2, int ID ):
555 TmpMeshFace( vector<const SMDS_MeshNode*>(4), ID ), _le1(le1), _le2(le2)
557 _nn[0]=_le1->_nodes[0];
558 _nn[1]=_le1->_nodes.back();
559 _nn[2]=_le2->_nodes.back();
560 _nn[3]=_le2->_nodes[0];
563 } // namespace VISCOUS_3D
565 //================================================================================
566 // StdMeshers_ViscousLayers hypothesis
568 StdMeshers_ViscousLayers::StdMeshers_ViscousLayers(int hypId, int studyId, SMESH_Gen* gen)
569 :SMESH_Hypothesis(hypId, studyId, gen),
570 _nbLayers(1), _thickness(1), _stretchFactor(1)
572 _name = StdMeshers_ViscousLayers::GetHypType();
573 _param_algo_dim = -3; // auxiliary hyp used by 3D algos
574 } // --------------------------------------------------------------------------------
575 void StdMeshers_ViscousLayers::SetBndShapesToIgnore(const std::vector<int>& faceIds)
577 if ( faceIds != _ignoreBndShapeIds )
578 _ignoreBndShapeIds = faceIds, NotifySubMeshesHypothesisModification();
579 } // --------------------------------------------------------------------------------
580 bool StdMeshers_ViscousLayers::IsIgnoredShape(const int shapeID) const
582 return ( find( _ignoreBndShapeIds.begin(), _ignoreBndShapeIds.end(), shapeID )
583 != _ignoreBndShapeIds.end() );
584 } // --------------------------------------------------------------------------------
585 void StdMeshers_ViscousLayers::SetTotalThickness(double thickness)
587 if ( thickness != _thickness )
588 _thickness = thickness, NotifySubMeshesHypothesisModification();
589 } // --------------------------------------------------------------------------------
590 void StdMeshers_ViscousLayers::SetNumberLayers(int nb)
592 if ( _nbLayers != nb )
593 _nbLayers = nb, NotifySubMeshesHypothesisModification();
594 } // --------------------------------------------------------------------------------
595 void StdMeshers_ViscousLayers::SetStretchFactor(double factor)
597 if ( _stretchFactor != factor )
598 _stretchFactor = factor, NotifySubMeshesHypothesisModification();
599 } // --------------------------------------------------------------------------------
601 StdMeshers_ViscousLayers::Compute(SMESH_Mesh& theMesh,
602 const TopoDS_Shape& theShape,
603 const bool toMakeN2NMap) const
605 using namespace VISCOUS_3D;
606 _ViscousBuilder bulder;
607 SMESH_ComputeErrorPtr err = bulder.Compute( theMesh, theShape );
608 if ( err && !err->IsOK() )
609 return SMESH_ProxyMesh::Ptr();
611 vector<SMESH_ProxyMesh::Ptr> components;
612 TopExp_Explorer exp( theShape, TopAbs_SOLID );
613 for ( ; exp.More(); exp.Next() )
615 if ( _MeshOfSolid* pm =
616 _ViscousListener::GetSolidMesh( &theMesh, exp.Current(), /*toCreate=*/false))
618 if ( toMakeN2NMap && !pm->_n2nMapComputed )
619 if ( !bulder.MakeN2NMap( pm ))
620 return SMESH_ProxyMesh::Ptr();
621 components.push_back( SMESH_ProxyMesh::Ptr( pm ));
622 pm->myIsDeletable = false; // it will de deleted by boost::shared_ptr
624 _ViscousListener::RemoveSolidMesh ( &theMesh, exp.Current() );
626 switch ( components.size() )
630 case 1: return components[0];
632 default: return SMESH_ProxyMesh::Ptr( new SMESH_ProxyMesh( components ));
634 return SMESH_ProxyMesh::Ptr();
635 } // --------------------------------------------------------------------------------
636 std::ostream & StdMeshers_ViscousLayers::SaveTo(std::ostream & save)
638 save << " " << _nbLayers
640 << " " << _stretchFactor
641 << " " << _ignoreBndShapeIds.size();
642 for ( unsigned i = 0; i < _ignoreBndShapeIds.size(); ++i )
643 save << " " << _ignoreBndShapeIds[i];
645 } // --------------------------------------------------------------------------------
646 std::istream & StdMeshers_ViscousLayers::LoadFrom(std::istream & load)
649 load >> _nbLayers >> _thickness >> _stretchFactor >> nbFaces;
650 while ( _ignoreBndShapeIds.size() < nbFaces && load >> faceID )
651 _ignoreBndShapeIds.push_back( faceID );
653 } // --------------------------------------------------------------------------------
654 bool StdMeshers_ViscousLayers::SetParametersByMesh(const SMESH_Mesh* theMesh,
655 const TopoDS_Shape& theShape)
660 // END StdMeshers_ViscousLayers hypothesis
661 //================================================================================
665 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const TopoDS_Vertex& fromV )
669 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
670 gp_Pnt p = BRep_Tool::Pnt( fromV );
671 double distF = p.SquareDistance( c->Value( f ));
672 double distL = p.SquareDistance( c->Value( l ));
673 c->D1(( distF < distL ? f : l), p, dir );
674 if ( distL < distF ) dir.Reverse();
677 //--------------------------------------------------------------------------------
678 gp_XYZ getEdgeDir( const TopoDS_Edge& E, const SMDS_MeshNode* atNode,
679 SMESH_MesherHelper& helper)
682 double f,l; gp_Pnt p;
683 Handle(Geom_Curve) c = BRep_Tool::Curve( E, f, l );
684 double u = helper.GetNodeU( E, atNode );
688 //--------------------------------------------------------------------------------
689 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Edge& fromE,
690 const SMDS_MeshNode* node, SMESH_MesherHelper& helper, bool& ok)
692 gp_XY uv = helper.GetNodeUV( F, node, 0, &ok );
693 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
694 gp_Pnt p; gp_Vec du, dv, norm;
695 surface->D1( uv.X(),uv.Y(), p, du,dv );
699 Handle(Geom_Curve) c = BRep_Tool::Curve( fromE, f, l );
700 double u = helper.GetNodeU( fromE, node, 0, &ok );
702 TopAbs_Orientation o = helper.GetSubShapeOri( F.Oriented(TopAbs_FORWARD), fromE);
703 if ( o == TopAbs_REVERSED )
706 gp_Vec dir = norm ^ du;
708 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_VERTEX &&
709 helper.IsClosedEdge( fromE ))
711 if ( fabs(u-f) < fabs(u-l )) c->D1( l, p, dv );
712 else c->D1( f, p, dv );
713 if ( o == TopAbs_REVERSED )
715 gp_Vec dir2 = norm ^ dv;
716 dir = dir.Normalized() + dir2.Normalized();
720 //--------------------------------------------------------------------------------
721 gp_XYZ getFaceDir( const TopoDS_Face& F, const TopoDS_Vertex& fromV,
722 const SMDS_MeshNode* node, SMESH_MesherHelper& helper,
723 bool& ok, double* cosin=0)
725 double f,l; TopLoc_Location loc;
726 vector< TopoDS_Edge > edges; // sharing a vertex
727 PShapeIteratorPtr eIt = helper.GetAncestors( fromV, *helper.GetMesh(), TopAbs_EDGE);
730 const TopoDS_Edge* e = static_cast<const TopoDS_Edge*>( eIt->next() );
731 if ( helper.IsSubShape( *e, F ) && !BRep_Tool::Curve( *e, loc,f,l).IsNull() )
732 edges.push_back( *e );
735 if ( !( ok = ( edges.size() > 0 ))) return dir;
736 // get average dir of edges going fromV
738 //if ( edges.size() > 1 )
739 for ( unsigned i = 0; i < edges.size(); ++i )
741 edgeDir = getEdgeDir( edges[i], fromV );
742 double size2 = edgeDir.SquareModulus();
743 if ( size2 > numeric_limits<double>::min() )
744 edgeDir /= sqrt( size2 );
749 gp_XYZ fromEdgeDir = getFaceDir( F, edges[0], node, helper, ok );
750 if ( edges.size() == 1 )
752 else if ( dir.SquareModulus() < 0.1 ) // ~< 20 degrees
753 dir = fromEdgeDir + getFaceDir( F, edges[1], node, helper, ok );
754 else if ( dir * fromEdgeDir < 0 )
758 //dir /= edges.size();
760 double angle = gp_Vec( edgeDir ).Angle( dir );
761 *cosin = cos( angle );
766 //================================================================================
768 * \brief Returns true if a FACE is bound by a concave EDGE
770 //================================================================================
772 bool isConcave( const TopoDS_Face& F, SMESH_MesherHelper& helper )
776 TopExp_Explorer eExp( F.Oriented( TopAbs_FORWARD ), TopAbs_EDGE );
777 for ( ; eExp.More(); eExp.Next() )
779 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
780 if ( BRep_Tool::Degenerated( E )) continue;
781 // check if 2D curve is concave
782 BRepAdaptor_Curve2d curve( E, F );
783 const int nbIntervals = curve.NbIntervals( GeomAbs_C2 );
784 TColStd_Array1OfReal intervals(1, nbIntervals + 1 );
785 curve.Intervals( intervals, GeomAbs_C2 );
786 bool isConvex = true;
787 for ( int i = 1; i <= nbIntervals && isConvex; ++i )
789 double u1 = intervals( i );
790 double u2 = intervals( i+1 );
791 curve.D2( 0.5*( u1+u2 ), p, drv1, drv2 );
792 double cross = drv2 ^ drv1;
793 if ( E.Orientation() == TopAbs_REVERSED )
795 isConvex = ( cross < 1e-9 );
797 // check if concavity is strong enough to care about it
798 //const double maxAngle = 5 * Standard_PI180;
801 //cout << "Concave FACE " << helper.GetMeshDS()->ShapeToIndex( F ) << endl;
803 // map< double, const SMDS_MeshNode* > u2nodes;
804 // if ( !SMESH_Algo::GetSortedNodesOnEdge( helper.GetMeshDS(), E,
805 // /*ignoreMedium=*/true, u2nodes))
807 // map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
808 // gp_Pnt2d uvPrev = helper.GetNodeUV( F, u2n->second );
809 // double uPrev = u2n->first;
810 // for ( ++u2n; u2n != u2nodes.end(); ++u2n )
812 // gp_Pnt2d uv = helper.GetNodeUV( F, u2n->second );
813 // gp_Vec2d segmentDir( uvPrev, uv );
814 // curve.D1( uPrev, p, drv1 );
816 // if ( fabs( segmentDir.Angle( drv1 )) > maxAngle )
821 // uPrev = u2n->first;
827 //--------------------------------------------------------------------------------
828 // DEBUG. Dump intermediate node positions into a python script
833 const char* fname = "/tmp/viscous.py";
834 cout << "execfile('"<<fname<<"')"<<endl;
835 py = new ofstream(fname);
836 *py << "from smesh import *" << endl
837 << "meshSO = GetCurrentStudy().FindObjectID('0:1:2:3')" << endl
838 << "mesh = Mesh( meshSO.GetObject() )"<<endl;
842 *py << "mesh.MakeGroup('Viscous Prisms',VOLUME,FT_ElemGeomType,'=',Geom_PENTA)"<<endl;
845 ~PyDump() { Finish(); }
847 #define dumpFunction(f) { _dumpFunction(f, __LINE__);}
848 #define dumpMove(n) { _dumpMove(n, __LINE__);}
849 #define dumpCmd(txt) { _dumpCmd(txt, __LINE__);}
850 void _dumpFunction(const string& fun, int ln)
851 { if (py) *py<< "def "<<fun<<"(): # "<< ln <<endl; cout<<fun<<"()"<<endl;}
852 void _dumpMove(const SMDS_MeshNode* n, int ln)
853 { if (py) *py<< " mesh.MoveNode( "<<n->GetID()<< ", "<< n->X()
854 << ", "<<n->Y()<<", "<< n->Z()<< ")\t\t # "<< ln <<endl; }
855 void _dumpCmd(const string& txt, int ln)
856 { if (py) *py<< " "<<txt<<" # "<< ln <<endl; }
857 void dumpFunctionEnd()
858 { if (py) *py<< " return"<< endl; }
859 void dumpChangeNodes( const SMDS_MeshElement* f )
860 { if (py) { *py<< " mesh.ChangeElemNodes( " << f->GetID()<<", [";
861 for ( int i=1; i < f->NbNodes(); ++i ) *py << f->GetNode(i-1)->GetID()<<", ";
862 *py << f->GetNode( f->NbNodes()-1 )->GetID() << " ])"<< endl; }}
864 struct PyDump { void Finish() {} };
865 #define dumpFunction(f) f
868 #define dumpFunctionEnd()
869 #define dumpChangeNodes(f)
873 using namespace VISCOUS_3D;
875 //================================================================================
877 * \brief Constructor of _ViscousBuilder
879 //================================================================================
881 _ViscousBuilder::_ViscousBuilder()
883 _error = SMESH_ComputeError::New(COMPERR_OK);
887 //================================================================================
889 * \brief Stores error description and returns false
891 //================================================================================
893 bool _ViscousBuilder::error(const string& text, int solidId )
895 _error->myName = COMPERR_ALGO_FAILED;
896 _error->myComment = string("Viscous layers builder: ") + text;
899 SMESH_subMesh* sm = _mesh->GetSubMeshContaining( solidId );
900 if ( !sm && !_sdVec.empty() )
901 sm = _mesh->GetSubMeshContaining( _sdVec[0]._index );
902 if ( sm && sm->GetSubShape().ShapeType() == TopAbs_SOLID )
904 SMESH_ComputeErrorPtr& smError = sm->GetComputeError();
905 if ( smError && smError->myAlgo )
906 _error->myAlgo = smError->myAlgo;
910 makeGroupOfLE(); // debug
915 //================================================================================
917 * \brief At study restoration, restore event listeners used to clear an inferior
918 * dim sub-mesh modified by viscous layers
920 //================================================================================
922 void _ViscousBuilder::RestoreListeners()
927 //================================================================================
929 * \brief computes SMESH_ProxyMesh::SubMesh::_n2n
931 //================================================================================
933 bool _ViscousBuilder::MakeN2NMap( _MeshOfSolid* pm )
935 SMESH_subMesh* solidSM = pm->mySubMeshes.front();
936 TopExp_Explorer fExp( solidSM->GetSubShape(), TopAbs_FACE );
937 for ( ; fExp.More(); fExp.Next() )
939 SMESHDS_SubMesh* srcSmDS = pm->GetMeshDS()->MeshElements( fExp.Current() );
940 const SMESH_ProxyMesh::SubMesh* prxSmDS = pm->GetProxySubMesh( fExp.Current() );
942 if ( !srcSmDS || !prxSmDS || !srcSmDS->NbElements() || !prxSmDS->NbElements() )
944 if ( srcSmDS->GetElements()->next() == prxSmDS->GetElements()->next())
947 if ( srcSmDS->NbElements() != prxSmDS->NbElements() )
948 return error( "Different nb elements in a source and a proxy sub-mesh", solidSM->GetId());
950 SMDS_ElemIteratorPtr srcIt = srcSmDS->GetElements();
951 SMDS_ElemIteratorPtr prxIt = prxSmDS->GetElements();
952 while( prxIt->more() )
954 const SMDS_MeshElement* fSrc = srcIt->next();
955 const SMDS_MeshElement* fPrx = prxIt->next();
956 if ( fSrc->NbNodes() != fPrx->NbNodes())
957 return error( "Different elements in a source and a proxy sub-mesh", solidSM->GetId());
958 for ( int i = 0 ; i < fPrx->NbNodes(); ++i )
959 pm->setNode2Node( fSrc->GetNode(i), fPrx->GetNode(i), prxSmDS );
962 pm->_n2nMapComputed = true;
966 //================================================================================
968 * \brief Does its job
970 //================================================================================
972 SMESH_ComputeErrorPtr _ViscousBuilder::Compute(SMESH_Mesh& theMesh,
973 const TopoDS_Shape& theShape)
975 // TODO: set priority of solids during Gen::Compute()
979 // check if proxy mesh already computed
980 TopExp_Explorer exp( theShape, TopAbs_SOLID );
982 return error("No SOLID's in theShape"), _error;
984 if ( _ViscousListener::GetSolidMesh( _mesh, exp.Current(), /*toCreate=*/false))
985 return SMESH_ComputeErrorPtr(); // everything already computed
989 // TODO: ignore already computed SOLIDs
990 if ( !findSolidsWithLayers())
993 if ( !findFacesWithLayers() )
996 for ( unsigned i = 0; i < _sdVec.size(); ++i )
998 if ( ! makeLayer(_sdVec[i]) )
1001 if ( _sdVec[i]._edges.size() == 0 )
1004 if ( ! inflate(_sdVec[i]) )
1007 if ( ! refine(_sdVec[i]) )
1013 addBoundaryElements();
1015 makeGroupOfLE(); // debug
1021 //================================================================================
1023 * \brief Finds SOLIDs to compute using viscous layers. Fills _sdVec
1025 //================================================================================
1027 bool _ViscousBuilder::findSolidsWithLayers()
1030 TopTools_IndexedMapOfShape allSolids;
1031 TopExp::MapShapes( _mesh->GetShapeToMesh(), TopAbs_SOLID, allSolids );
1032 _sdVec.reserve( allSolids.Extent());
1034 SMESH_Gen* gen = _mesh->GetGen();
1035 for ( int i = 1; i <= allSolids.Extent(); ++i )
1037 // find StdMeshers_ViscousLayers hyp assigned to the i-th solid
1038 SMESH_Algo* algo = gen->GetAlgo( *_mesh, allSolids(i) );
1039 if ( !algo ) continue;
1040 // TODO: check if algo is hidden
1041 const list <const SMESHDS_Hypothesis *> & allHyps =
1042 algo->GetUsedHypothesis(*_mesh, allSolids(i), /*ignoreAuxiliary=*/false);
1043 list< const SMESHDS_Hypothesis *>::const_iterator hyp = allHyps.begin();
1044 const StdMeshers_ViscousLayers* viscHyp = 0;
1045 for ( ; hyp != allHyps.end() && !viscHyp; ++hyp )
1046 viscHyp = dynamic_cast<const StdMeshers_ViscousLayers*>( *hyp );
1049 _MeshOfSolid* proxyMesh = _ViscousListener::GetSolidMesh( _mesh,
1052 _sdVec.push_back( _SolidData( allSolids(i), viscHyp, proxyMesh ));
1053 _sdVec.back()._index = getMeshDS()->ShapeToIndex( allSolids(i));
1056 if ( _sdVec.empty() )
1058 ( SMESH_Comment(StdMeshers_ViscousLayers::GetHypType()) << " hypothesis not found",0);
1063 //================================================================================
1067 //================================================================================
1069 bool _ViscousBuilder::findFacesWithLayers()
1071 // collect all faces to ignore defined by hyp
1072 vector<TopoDS_Shape> ignoreFaces;
1073 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1075 vector<TGeomID> ids = _sdVec[i]._hyp->GetBndShapesToIgnore();
1076 for ( unsigned i = 0; i < ids.size(); ++i )
1078 const TopoDS_Shape& s = getMeshDS()->IndexToShape( ids[i] );
1079 if ( !s.IsNull() && s.ShapeType() == TopAbs_FACE )
1081 _ignoreShapeIds.insert( ids[i] );
1082 ignoreFaces.push_back( s );
1087 // ignore internal faces
1088 SMESH_MesherHelper helper( *_mesh );
1089 TopExp_Explorer exp;
1090 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1092 exp.Init( _sdVec[i]._solid.Oriented( TopAbs_FORWARD ), TopAbs_FACE );
1093 for ( ; exp.More(); exp.Next() )
1095 TGeomID faceInd = getMeshDS()->ShapeToIndex( exp.Current() );
1096 if ( helper.NbAncestors( exp.Current(), *_mesh, TopAbs_SOLID ) > 1 )
1098 _ignoreShapeIds.insert( faceInd );
1099 ignoreFaces.push_back( exp.Current() );
1100 if ( helper.IsReversedSubMesh( TopoDS::Face( exp.Current() )))
1101 _sdVec[i]._reversedFaceIds.insert( faceInd );
1106 // Find faces to shrink mesh on (solution 2 in issue 0020832);
1107 TopTools_IndexedMapOfShape shapes;
1108 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1111 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_EDGE, shapes);
1112 for ( int iE = 1; iE <= shapes.Extent(); ++iE )
1114 const TopoDS_Shape& edge = shapes(iE);
1115 // find 2 faces sharing an edge
1117 PShapeIteratorPtr fIt = helper.GetAncestors(edge, *_mesh, TopAbs_FACE);
1118 while ( fIt->more())
1120 const TopoDS_Shape* f = fIt->next();
1121 if ( helper.IsSubShape( *f, _sdVec[i]._solid))
1122 FF[ int( !FF[0].IsNull()) ] = *f;
1124 if( FF[1].IsNull() ) continue; // seam edge can be shared by 1 FACE only
1125 // check presence of layers on them
1127 for ( int j = 0; j < 2; ++j )
1128 ignore[j] = _ignoreShapeIds.count ( getMeshDS()->ShapeToIndex( FF[j] ));
1129 if ( ignore[0] == ignore[1] ) continue; // nothing interesting
1130 TopoDS_Shape fWOL = FF[ ignore[0] ? 0 : 1 ];
1132 TGeomID edgeInd = getMeshDS()->ShapeToIndex( edge );
1133 _sdVec[i]._shrinkShape2Shape.insert( make_pair( edgeInd, fWOL ));
1136 // Exclude from _shrinkShape2Shape FACE's that can't be shrinked since
1137 // the algo of the SOLID sharing the FACE does not support it
1138 set< string > notSupportAlgos; notSupportAlgos.insert("Hexa_3D");
1139 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1141 TopTools_MapOfShape noShrinkVertices;
1142 map< TGeomID, TopoDS_Shape >::iterator e2f = _sdVec[i]._shrinkShape2Shape.begin();
1143 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); ++e2f )
1145 const TopoDS_Shape& fWOL = e2f->second;
1146 TGeomID edgeID = e2f->first;
1147 bool notShrinkFace = false;
1148 PShapeIteratorPtr soIt = helper.GetAncestors(fWOL, *_mesh, TopAbs_SOLID);
1149 while ( soIt->more())
1151 const TopoDS_Shape* solid = soIt->next();
1152 if ( _sdVec[i]._solid.IsSame( *solid )) continue;
1153 SMESH_Algo* algo = _mesh->GetGen()->GetAlgo( *_mesh, *solid );
1154 if ( !algo || !notSupportAlgos.count( algo->GetName() )) continue;
1155 notShrinkFace = true;
1156 for ( unsigned j = 0; j < _sdVec.size(); ++j )
1158 if ( _sdVec[j]._solid.IsSame( *solid ) )
1159 if ( _sdVec[j]._shrinkShape2Shape.count( edgeID ))
1160 notShrinkFace = false;
1163 if ( notShrinkFace )
1165 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( fWOL ));
1166 for ( TopExp_Explorer vExp( fWOL, TopAbs_VERTEX ); vExp.More(); vExp.Next() )
1167 noShrinkVertices.Add( vExp.Current() );
1170 // erase from _shrinkShape2Shape all srink EDGE's of a SOLID connected
1171 // to the found not shrinked fWOL's
1172 e2f = _sdVec[i]._shrinkShape2Shape.begin();
1173 for ( ; e2f != _sdVec[i]._shrinkShape2Shape.end(); )
1175 TGeomID edgeID = e2f->first;
1176 TopoDS_Vertex VV[2];
1177 TopExp::Vertices( TopoDS::Edge( getMeshDS()->IndexToShape( edgeID )),VV[0],VV[1]);
1178 if ( noShrinkVertices.Contains( VV[0] ) || noShrinkVertices.Contains( VV[1] ))
1180 _sdVec[i]._noShrinkFaces.insert( getMeshDS()->ShapeToIndex( e2f->second ));
1181 _sdVec[i]._shrinkShape2Shape.erase( e2f++ );
1190 // Find the SHAPE along which to inflate _LayerEdge based on VERTEX
1192 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1195 TopExp::MapShapes(_sdVec[i]._solid, TopAbs_VERTEX, shapes);
1196 for ( int iV = 1; iV <= shapes.Extent(); ++iV )
1198 const TopoDS_Shape& vertex = shapes(iV);
1199 // find faces WOL sharing the vertex
1200 vector< TopoDS_Shape > facesWOL;
1201 int totalNbFaces = 0;
1202 PShapeIteratorPtr fIt = helper.GetAncestors(vertex, *_mesh, TopAbs_FACE);
1203 while ( fIt->more())
1205 const TopoDS_Shape* f = fIt->next();
1206 const int fID = getMeshDS()->ShapeToIndex( *f );
1207 if ( helper.IsSubShape( *f, _sdVec[i]._solid ) )
1210 if ( _ignoreShapeIds.count ( fID ) && ! _sdVec[i]._noShrinkFaces.count( fID ))
1211 facesWOL.push_back( *f );
1214 if ( facesWOL.size() == totalNbFaces || facesWOL.empty() )
1215 continue; // no layers at this vertex or no WOL
1216 TGeomID vInd = getMeshDS()->ShapeToIndex( vertex );
1217 switch ( facesWOL.size() )
1221 helper.SetSubShape( facesWOL[0] );
1222 if ( helper.IsRealSeam( vInd )) // inflate along a seam edge?
1224 TopoDS_Shape seamEdge;
1225 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1226 while ( eIt->more() && seamEdge.IsNull() )
1228 const TopoDS_Shape* e = eIt->next();
1229 if ( helper.IsRealSeam( *e ) )
1232 if ( !seamEdge.IsNull() )
1234 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, seamEdge ));
1238 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, facesWOL[0] ));
1243 // find an edge shared by 2 faces
1244 PShapeIteratorPtr eIt = helper.GetAncestors(vertex, *_mesh, TopAbs_EDGE);
1245 while ( eIt->more())
1247 const TopoDS_Shape* e = eIt->next();
1248 if ( helper.IsSubShape( *e, facesWOL[0]) &&
1249 helper.IsSubShape( *e, facesWOL[1]))
1251 _sdVec[i]._shrinkShape2Shape.insert( make_pair( vInd, *e )); break;
1257 return error("Not yet supported case", _sdVec[i]._index);
1265 //================================================================================
1267 * \brief Create the inner surface of the viscous layer and prepare data for infation
1269 //================================================================================
1271 bool _ViscousBuilder::makeLayer(_SolidData& data)
1273 // get all sub-shapes to make layers on
1274 set<TGeomID> subIds, faceIds;
1275 subIds = data._noShrinkFaces;
1276 TopExp_Explorer exp( data._solid, TopAbs_FACE );
1277 for ( ; exp.More(); exp.Next() )
1278 if ( ! _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
1280 SMESH_subMesh* fSubM = _mesh->GetSubMesh( exp.Current() );
1281 faceIds.insert( fSubM->GetId() );
1282 SMESH_subMeshIteratorPtr subIt =
1283 fSubM->getDependsOnIterator(/*includeSelf=*/true, /*complexShapeFirst=*/false);
1284 while ( subIt->more() )
1285 subIds.insert( subIt->next()->GetId() );
1288 // make a map to find new nodes on sub-shapes shared with other SOLID
1289 map< TGeomID, TNode2Edge* > s2neMap;
1290 map< TGeomID, TNode2Edge* >::iterator s2ne;
1291 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
1292 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
1294 TGeomID shapeInd = s2s->first;
1295 for ( unsigned i = 0; i < _sdVec.size(); ++i )
1297 if ( _sdVec[i]._index == data._index ) continue;
1298 map< TGeomID, TopoDS_Shape >::iterator s2s2 = _sdVec[i]._shrinkShape2Shape.find( shapeInd );
1299 if ( s2s2 != _sdVec[i]._shrinkShape2Shape.end() &&
1300 *s2s == *s2s2 && !_sdVec[i]._n2eMap.empty() )
1302 s2neMap.insert( make_pair( shapeInd, &_sdVec[i]._n2eMap ));
1308 // Create temporary faces and _LayerEdge's
1310 dumpFunction(SMESH_Comment("makeLayers_")<<data._index);
1312 data._stepSize = Precision::Infinite();
1313 data._stepSizeNodes[0] = 0;
1315 SMESH_MesherHelper helper( *_mesh );
1316 helper.SetSubShape( data._solid );
1317 helper.SetElementsOnShape(true);
1319 vector< const SMDS_MeshNode*> newNodes; // of a mesh face
1320 TNode2Edge::iterator n2e2;
1322 // collect _LayerEdge's of shapes they are based on
1323 const int nbShapes = getMeshDS()->MaxShapeIndex();
1324 vector< vector<_LayerEdge*> > edgesByGeom( nbShapes+1 );
1326 for ( set<TGeomID>::iterator id = faceIds.begin(); id != faceIds.end(); ++id )
1328 SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( *id );
1329 if ( !smDS ) return error(SMESH_Comment("Not meshed face ") << *id, data._index );
1331 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( *id ));
1332 SMESH_ProxyMesh::SubMesh* proxySub =
1333 data._proxyMesh->getFaceSubM( F, /*create=*/true);
1335 SMDS_ElemIteratorPtr eIt = smDS->GetElements();
1336 while ( eIt->more() )
1338 const SMDS_MeshElement* face = eIt->next();
1339 newNodes.resize( face->NbCornerNodes() );
1340 double faceMaxCosin = -1;
1341 for ( int i = 0 ; i < face->NbCornerNodes(); ++i )
1343 const SMDS_MeshNode* n = face->GetNode(i);
1344 TNode2Edge::iterator n2e = data._n2eMap.insert( make_pair( n, (_LayerEdge*)0 )).first;
1345 if ( !(*n2e).second )
1348 _LayerEdge* edge = new _LayerEdge();
1350 edge->_nodes.push_back( n );
1351 const int shapeID = n->getshapeId();
1352 edgesByGeom[ shapeID ].push_back( edge );
1354 // set edge data or find already refined _LayerEdge and get data from it
1355 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
1356 ( s2ne = s2neMap.find( shapeID )) != s2neMap.end() &&
1357 ( n2e2 = (*s2ne).second->find( n )) != s2ne->second->end())
1359 _LayerEdge* foundEdge = (*n2e2).second;
1360 edge->Copy( *foundEdge, helper );
1361 // location of the last node is modified but we can restore
1362 // it by node position on _sWOL stored by the node
1363 const_cast< SMDS_MeshNode* >
1364 ( edge->_nodes.back() )->setXYZ( n->X(), n->Y(), n->Z() );
1368 edge->_nodes.push_back( helper.AddNode( n->X(), n->Y(), n->Z() ));
1369 if ( !setEdgeData( *edge, subIds, helper, data ))
1372 dumpMove(edge->_nodes.back());
1373 if ( edge->_cosin > 0.01 )
1375 if ( edge->_cosin > faceMaxCosin )
1376 faceMaxCosin = edge->_cosin;
1379 newNodes[ i ] = n2e->second->_nodes.back();
1381 // create a temporary face
1382 const SMDS_MeshElement* newFace = new TmpMeshFace( newNodes, --_tmpFaceID );
1383 proxySub->AddElement( newFace );
1385 // compute inflation step size by min size of element on a convex surface
1386 if ( faceMaxCosin > 0.1 )
1387 limitStepSize( data, face, faceMaxCosin );
1388 } // loop on 2D elements on a FACE
1389 } // loop on FACEs of a SOLID
1391 data._epsilon = 1e-7;
1392 if ( data._stepSize < 1. )
1393 data._epsilon *= data._stepSize;
1395 // Put _LayerEdge's into the vector data._edges
1397 if ( !sortEdges( data, edgesByGeom ))
1400 // Set target nodes into _Simplex and _2NearEdges
1401 TNode2Edge::iterator n2e;
1402 for ( unsigned i = 0; i < data._edges.size(); ++i )
1404 if ( data._edges[i]->IsOnEdge())
1405 for ( int j = 0; j < 2; ++j )
1407 if ( data._edges[i]->_nodes.back()->NbInverseElements(SMDSAbs_Volume) > 0 )
1408 break; // _LayerEdge is shared by two _SolidData's
1409 const SMDS_MeshNode* & n = data._edges[i]->_2neibors->_nodes[j];
1410 if (( n2e = data._n2eMap.find( n )) == data._n2eMap.end() )
1411 return error("_LayerEdge not found by src node", data._index);
1412 n = (*n2e).second->_nodes.back();
1413 data._edges[i]->_2neibors->_edges[j] = n2e->second;
1416 for ( unsigned j = 0; j < data._edges[i]->_simplices.size(); ++j )
1418 _Simplex& s = data._edges[i]->_simplices[j];
1419 s._nNext = data._n2eMap[ s._nNext ]->_nodes.back();
1420 s._nPrev = data._n2eMap[ s._nPrev ]->_nodes.back();
1428 //================================================================================
1430 * \brief Compute inflation step size by min size of element on a convex surface
1432 //================================================================================
1434 void _ViscousBuilder::limitStepSize( _SolidData& data,
1435 const SMDS_MeshElement* face,
1439 double minSize = 10 * data._stepSize;
1440 const int nbNodes = face->NbCornerNodes();
1441 for ( int i = 0; i < nbNodes; ++i )
1443 const SMDS_MeshNode* nextN = face->GetNode( SMESH_MesherHelper::WrapIndex( i+1, nbNodes ));
1444 const SMDS_MeshNode* curN = face->GetNode( i );
1445 if ( nextN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE ||
1446 curN->GetPosition()->GetTypeOfPosition() == SMDS_TOP_FACE )
1448 double dist = SMESH_TNodeXYZ( face->GetNode(i)).Distance( nextN );
1449 if ( dist < minSize )
1450 minSize = dist, iN = i;
1453 double newStep = 0.8 * minSize / cosin;
1454 if ( newStep < data._stepSize )
1456 data._stepSize = newStep;
1457 data._stepSizeCoeff = 0.8 / cosin;
1458 data._stepSizeNodes[0] = face->GetNode( iN );
1459 data._stepSizeNodes[1] = face->GetNode( SMESH_MesherHelper::WrapIndex( iN+1, nbNodes ));
1463 //================================================================================
1465 * \brief Compute inflation step size by min size of element on a convex surface
1467 //================================================================================
1469 void _ViscousBuilder::limitStepSize( _SolidData& data, const double minSize)
1471 if ( minSize < data._stepSize )
1473 data._stepSize = minSize;
1474 if ( data._stepSizeNodes[0] )
1477 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
1478 data._stepSizeCoeff = data._stepSize / dist;
1483 //================================================================================
1485 * \brief Separate shapes (and _LayerEdge's on them) to smooth from the rest ones
1487 //================================================================================
1489 bool _ViscousBuilder::sortEdges( _SolidData& data,
1490 vector< vector<_LayerEdge*> >& edgesByGeom)
1492 // Find shapes needing smoothing; such a shape has _LayerEdge._normal on it's
1493 // boundry inclined at a sharp angle to the shape
1495 list< TGeomID > shapesToSmooth;
1497 SMESH_MesherHelper helper( *_mesh );
1500 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1502 vector<_LayerEdge*>& eS = edgesByGeom[iS];
1503 if ( eS.empty() ) continue;
1504 TopoDS_Shape S = getMeshDS()->IndexToShape( iS );
1505 bool needSmooth = false;
1506 switch ( S.ShapeType() )
1510 bool isShrinkEdge = !eS[0]->_sWOL.IsNull();
1511 for ( TopoDS_Iterator vIt( S ); vIt.More() && !needSmooth; vIt.Next() )
1513 TGeomID iV = getMeshDS()->ShapeToIndex( vIt.Value() );
1514 vector<_LayerEdge*>& eV = edgesByGeom[ iV ];
1515 if ( eV.empty() ) continue;
1516 double cosin = eV[0]->_cosin;
1518 ( !eV[0]->_sWOL.IsNull() && ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE || !isShrinkEdge));
1522 if ( eV[0]->_sWOL.ShapeType() == TopAbs_EDGE )
1523 dir1 = getEdgeDir( TopoDS::Edge( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ));
1525 dir1 = getFaceDir( TopoDS::Face( eV[0]->_sWOL ), TopoDS::Vertex( vIt.Value() ),
1526 eV[0]->_nodes[0], helper, ok);
1527 dir2 = getEdgeDir( TopoDS::Edge( S ), TopoDS::Vertex( vIt.Value() ));
1528 double angle = dir1.Angle( dir2 );
1529 cosin = cos( angle );
1531 needSmooth = ( cosin > 0.1 );
1537 for ( TopExp_Explorer eExp( S, TopAbs_EDGE ); eExp.More() && !needSmooth; eExp.Next() )
1539 TGeomID iE = getMeshDS()->ShapeToIndex( eExp.Current() );
1540 vector<_LayerEdge*>& eE = edgesByGeom[ iE ];
1541 if ( eE.empty() ) continue;
1542 if ( eE[0]->_sWOL.IsNull() )
1544 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1545 needSmooth = ( eE[i]->_cosin > 0.1 );
1549 const TopoDS_Face& F1 = TopoDS::Face( S );
1550 const TopoDS_Face& F2 = TopoDS::Face( eE[0]->_sWOL );
1551 const TopoDS_Edge& E = TopoDS::Edge( eExp.Current() );
1552 for ( unsigned i = 0; i < eE.size() && !needSmooth; ++i )
1554 gp_Vec dir1 = getFaceDir( F1, E, eE[i]->_nodes[0], helper, ok );
1555 gp_Vec dir2 = getFaceDir( F2, E, eE[i]->_nodes[0], helper, ok );
1556 double angle = dir1.Angle( dir2 );
1557 double cosin = cos( angle );
1558 needSmooth = ( cosin > 0.1 );
1570 if ( S.ShapeType() == TopAbs_EDGE ) shapesToSmooth.push_front( iS );
1571 else shapesToSmooth.push_back ( iS );
1574 } // loop on edgesByGeom
1576 data._edges.reserve( data._n2eMap.size() );
1577 data._endEdgeToSmooth.clear();
1579 // first we put _LayerEdge's on shapes to smooth
1580 list< TGeomID >::iterator gIt = shapesToSmooth.begin();
1581 for ( ; gIt != shapesToSmooth.end(); ++gIt )
1583 vector<_LayerEdge*>& eVec = edgesByGeom[ *gIt ];
1584 if ( eVec.empty() ) continue;
1585 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1586 data._endEdgeToSmooth.push_back( data._edges.size() );
1590 // then the rest _LayerEdge's
1591 for ( unsigned iS = 0; iS < edgesByGeom.size(); ++iS )
1593 vector<_LayerEdge*>& eVec = edgesByGeom[iS];
1594 data._edges.insert( data._edges.end(), eVec.begin(), eVec.end() );
1601 //================================================================================
1603 * \brief Set data of _LayerEdge needed for smoothing
1604 * \param subIds - ids of sub-shapes of a SOLID to take into account faces from
1606 //================================================================================
1608 bool _ViscousBuilder::setEdgeData(_LayerEdge& edge,
1609 const set<TGeomID>& subIds,
1610 SMESH_MesherHelper& helper,
1613 SMESH_MeshEditor editor(_mesh);
1615 const SMDS_MeshNode* node = edge._nodes[0]; // source node
1616 SMDS_TypeOfPosition posType = node->GetPosition()->GetTypeOfPosition();
1620 edge._curvature = 0;
1622 // --------------------------
1623 // Compute _normal and _cosin
1624 // --------------------------
1627 edge._normal.SetCoord(0,0,0);
1629 int totalNbFaces = 0;
1631 gp_Vec du, dv, geomNorm;
1634 TGeomID shapeInd = node->getshapeId();
1635 map< TGeomID, TopoDS_Shape >::const_iterator s2s = data._shrinkShape2Shape.find( shapeInd );
1636 bool onShrinkShape ( s2s != data._shrinkShape2Shape.end() );
1637 TopoDS_Shape vertEdge;
1639 if ( onShrinkShape ) // one of faces the node is on has no layers
1641 vertEdge = getMeshDS()->IndexToShape( s2s->first ); // vertex or edge
1642 if ( s2s->second.ShapeType() == TopAbs_EDGE )
1644 // inflate from VERTEX along EDGE
1645 edge._normal = getEdgeDir( TopoDS::Edge( s2s->second ), TopoDS::Vertex( vertEdge ));
1647 else if ( vertEdge.ShapeType() == TopAbs_VERTEX )
1649 // inflate from VERTEX along FACE
1650 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Vertex( vertEdge ),
1651 node, helper, normOK, &edge._cosin);
1655 // inflate from EDGE along FACE
1656 edge._normal = getFaceDir( TopoDS::Face( s2s->second ), TopoDS::Edge( vertEdge ),
1657 node, helper, normOK);
1660 else // layers are on all faces of SOLID the node is on
1662 // find indices of geom faces the node lies on
1663 set<TGeomID> faceIds;
1664 if ( posType == SMDS_TOP_FACE )
1666 faceIds.insert( node->getshapeId() );
1670 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1671 while ( fIt->more() )
1672 faceIds.insert( editor.FindShape(fIt->next()));
1675 set<TGeomID>::iterator id = faceIds.begin();
1677 for ( ; id != faceIds.end(); ++id )
1679 const TopoDS_Shape& s = getMeshDS()->IndexToShape( *id );
1680 if ( s.IsNull() || s.ShapeType() != TopAbs_FACE || !subIds.count( *id ))
1683 //nbLayerFaces += subIds.count( *id );
1684 F = TopoDS::Face( s );
1686 gp_XY uv = helper.GetNodeUV( F, node, 0, &normOK );
1687 Handle(Geom_Surface) surface = BRep_Tool::Surface( F );
1688 surface->D1( uv.X(),uv.Y(), p, du,dv );
1690 double size2 = geomNorm.SquareMagnitude();
1691 if ( size2 > numeric_limits<double>::min() )
1692 geomNorm /= sqrt( size2 );
1695 if ( helper.GetSubShapeOri( data._solid, F ) != TopAbs_REVERSED )
1697 edge._normal += geomNorm.XYZ();
1699 if ( totalNbFaces == 0 )
1700 return error(SMESH_Comment("Can't get normal to node ") << node->GetID(), data._index);
1702 edge._normal /= totalNbFaces;
1707 edge._cosin = 0; break;
1709 case SMDS_TOP_EDGE: {
1710 TopoDS_Edge E = TopoDS::Edge( helper.GetSubShapeByNode( node, getMeshDS()));
1711 gp_Vec inFaceDir = getFaceDir( F, E, node, helper, normOK);
1712 double angle = inFaceDir.Angle( edge._normal ); // [0,PI]
1713 edge._cosin = cos( angle );
1714 //cout << "Cosin on EDGE " << edge._cosin << " node " << node->GetID() << endl;
1717 case SMDS_TOP_VERTEX: {
1718 TopoDS_Vertex V = TopoDS::Vertex( helper.GetSubShapeByNode( node, getMeshDS()));
1719 gp_XYZ inFaceDir = getFaceDir( F, V, node, helper, normOK);
1720 double angle = gp_Vec( inFaceDir).Angle( edge._normal ); // [0,PI]
1721 edge._cosin = cos( angle );
1722 //cout << "Cosin on VERTEX " << edge._cosin << " node " << node->GetID() << endl;
1726 return error(SMESH_Comment("Invalid shape position of node ")<<node, data._index);
1730 double normSize = edge._normal.SquareModulus();
1731 if ( normSize < numeric_limits<double>::min() )
1732 return error(SMESH_Comment("Bad normal at node ")<< node->GetID(), data._index );
1734 edge._normal /= sqrt( normSize );
1736 // TODO: if ( !normOK ) then get normal by mesh faces
1738 // Set the rest data
1739 // --------------------
1740 if ( onShrinkShape )
1742 edge._sWOL = (*s2s).second;
1744 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( edge._nodes.back() );
1745 if ( SMESHDS_SubMesh* sm = getMeshDS()->MeshElements( data._solid ))
1746 sm->RemoveNode( tgtNode , /*isNodeDeleted=*/false );
1748 // set initial position which is parameters on _sWOL in this case
1749 if ( edge._sWOL.ShapeType() == TopAbs_EDGE )
1751 double u = helper.GetNodeU( TopoDS::Edge( edge._sWOL ), node, 0, &normOK );
1752 edge._pos.push_back( gp_XYZ( u, 0, 0));
1753 getMeshDS()->SetNodeOnEdge( tgtNode, TopoDS::Edge( edge._sWOL ), u );
1757 gp_XY uv = helper.GetNodeUV( TopoDS::Face( edge._sWOL ), node, 0, &normOK );
1758 edge._pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1759 getMeshDS()->SetNodeOnFace( tgtNode, TopoDS::Face( edge._sWOL ), uv.X(), uv.Y() );
1764 edge._pos.push_back( SMESH_TNodeXYZ( node ));
1766 if ( posType == SMDS_TOP_FACE )
1768 getSimplices( node, edge._simplices, _ignoreShapeIds, &data );
1769 double avgNormProj = 0, avgLen = 0;
1770 for ( unsigned i = 0; i < edge._simplices.size(); ++i )
1772 gp_XYZ vec = edge._pos.back() - SMESH_TNodeXYZ( edge._simplices[i]._nPrev );
1773 avgNormProj += edge._normal * vec;
1774 avgLen += vec.Modulus();
1776 avgNormProj /= edge._simplices.size();
1777 avgLen /= edge._simplices.size();
1778 edge._curvature = _Curvature::New( avgNormProj, avgLen );
1782 // Set neighbour nodes for a _LayerEdge based on EDGE
1784 if ( posType == SMDS_TOP_EDGE /*||
1785 ( onShrinkShape && posType == SMDS_TOP_VERTEX && fabs( edge._cosin ) < 1e-10 )*/)
1787 edge._2neibors = new _2NearEdges;
1788 // target node instead of source ones will be set later
1789 if ( ! findNeiborsOnEdge( &edge,
1790 edge._2neibors->_nodes[0],
1791 edge._2neibors->_nodes[1],
1794 edge.SetDataByNeighbors( edge._2neibors->_nodes[0],
1795 edge._2neibors->_nodes[1],
1799 edge.SetCosin( edge._cosin ); // to update edge._lenFactor
1804 //================================================================================
1806 * \brief Find 2 neigbor nodes of a node on EDGE
1808 //================================================================================
1810 bool _ViscousBuilder::findNeiborsOnEdge(const _LayerEdge* edge,
1811 const SMDS_MeshNode*& n1,
1812 const SMDS_MeshNode*& n2,
1815 const SMDS_MeshNode* node = edge->_nodes[0];
1816 const int shapeInd = node->getshapeId();
1817 SMESHDS_SubMesh* edgeSM = 0;
1818 if ( node->GetPosition()->GetTypeOfPosition() == SMDS_TOP_EDGE )
1821 edgeSM = getMeshDS()->MeshElements( shapeInd );
1822 if ( !edgeSM || edgeSM->NbElements() == 0 )
1823 return error(SMESH_Comment("Not meshed EDGE ") << shapeInd, data._index);
1827 SMDS_ElemIteratorPtr eIt = node->GetInverseElementIterator(SMDSAbs_Edge);
1828 while ( eIt->more() && !n2 )
1830 const SMDS_MeshElement* e = eIt->next();
1831 const SMDS_MeshNode* nNeibor = e->GetNode( 0 );
1832 if ( nNeibor == node ) nNeibor = e->GetNode( 1 );
1835 if (!edgeSM->Contains(e)) continue;
1839 TopoDS_Shape s = SMESH_MesherHelper::GetSubShapeByNode(nNeibor, getMeshDS() );
1840 if ( !SMESH_MesherHelper::IsSubShape( s, edge->_sWOL )) continue;
1842 ( iN++ ? n2 : n1 ) = nNeibor;
1845 return error(SMESH_Comment("Wrongly meshed EDGE ") << shapeInd, data._index);
1849 //================================================================================
1851 * \brief Set _curvature and _2neibors->_plnNorm by 2 neigbor nodes residing the same EDGE
1853 //================================================================================
1855 void _LayerEdge::SetDataByNeighbors( const SMDS_MeshNode* n1,
1856 const SMDS_MeshNode* n2,
1857 SMESH_MesherHelper& helper)
1859 if ( _nodes[0]->GetPosition()->GetTypeOfPosition() != SMDS_TOP_EDGE )
1862 gp_XYZ pos = SMESH_TNodeXYZ( _nodes[0] );
1863 gp_XYZ vec1 = pos - SMESH_TNodeXYZ( n1 );
1864 gp_XYZ vec2 = pos - SMESH_TNodeXYZ( n2 );
1868 double sumLen = vec1.Modulus() + vec2.Modulus();
1869 _2neibors->_wgt[0] = 1 - vec1.Modulus() / sumLen;
1870 _2neibors->_wgt[1] = 1 - vec2.Modulus() / sumLen;
1871 double avgNormProj = 0.5 * ( _normal * vec1 + _normal * vec2 );
1872 double avgLen = 0.5 * ( vec1.Modulus() + vec2.Modulus() );
1873 if ( _curvature ) delete _curvature;
1874 _curvature = _Curvature::New( avgNormProj, avgLen );
1876 // if ( _curvature )
1877 // cout << _nodes[0]->GetID()
1878 // << " CURV r,k: " << _curvature->_r<<","<<_curvature->_k
1879 // << " proj = "<<avgNormProj<< " len = " << avgLen << "| lenDelta(0) = "
1880 // << _curvature->lenDelta(0) << endl;
1885 if ( _sWOL.IsNull() )
1887 TopoDS_Shape S = helper.GetSubShapeByNode( _nodes[0], helper.GetMeshDS() );
1888 gp_XYZ dirE = getEdgeDir( TopoDS::Edge( S ), _nodes[0], helper );
1889 gp_XYZ plnNorm = dirE ^ _normal;
1890 double proj0 = plnNorm * vec1;
1891 double proj1 = plnNorm * vec2;
1892 if ( fabs( proj0 ) > 1e-10 || fabs( proj1 ) > 1e-10 )
1894 if ( _2neibors->_plnNorm ) delete _2neibors->_plnNorm;
1895 _2neibors->_plnNorm = new gp_XYZ( plnNorm.Normalized() );
1900 //================================================================================
1902 * \brief Copy data from a _LayerEdge of other SOLID and based on the same node;
1903 * this and other _LayerEdge's are inflated along a FACE or an EDGE
1905 //================================================================================
1907 void _LayerEdge::Copy( _LayerEdge& other, SMESH_MesherHelper& helper )
1909 _nodes = other._nodes;
1910 _normal = other._normal;
1912 _lenFactor = other._lenFactor;
1913 _cosin = other._cosin;
1914 _sWOL = other._sWOL;
1915 _2neibors = other._2neibors;
1916 _curvature = 0; std::swap( _curvature, other._curvature );
1917 _2neibors = 0; std::swap( _2neibors, other._2neibors );
1919 if ( _sWOL.ShapeType() == TopAbs_EDGE )
1921 double u = helper.GetNodeU( TopoDS::Edge( _sWOL ), _nodes[0] );
1922 _pos.push_back( gp_XYZ( u, 0, 0));
1926 gp_XY uv = helper.GetNodeUV( TopoDS::Face( _sWOL ), _nodes[0]);
1927 _pos.push_back( gp_XYZ( uv.X(), uv.Y(), 0));
1931 //================================================================================
1933 * \brief Set _cosin and _lenFactor
1935 //================================================================================
1937 void _LayerEdge::SetCosin( double cosin )
1940 _lenFactor = ( _cosin > 0.1 ) ? 1./sqrt(1-_cosin*_cosin) : 1.0;
1943 //================================================================================
1945 * \brief Fills a vector<_Simplex >
1947 //================================================================================
1949 void _ViscousBuilder::getSimplices( const SMDS_MeshNode* node,
1950 vector<_Simplex>& simplices,
1951 const set<TGeomID>& ingnoreShapes,
1952 const _SolidData* dataToCheckOri,
1955 SMDS_ElemIteratorPtr fIt = node->GetInverseElementIterator(SMDSAbs_Face);
1956 while ( fIt->more() )
1958 const SMDS_MeshElement* f = fIt->next();
1959 const TGeomID shapeInd = f->getshapeId();
1960 if ( ingnoreShapes.count( shapeInd )) continue;
1961 const int nbNodes = f->NbCornerNodes();
1962 int srcInd = f->GetNodeIndex( node );
1963 const SMDS_MeshNode* nPrev = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd-1, nbNodes ));
1964 const SMDS_MeshNode* nNext = f->GetNode( SMESH_MesherHelper::WrapIndex( srcInd+1, nbNodes ));
1965 if ( dataToCheckOri && dataToCheckOri->_reversedFaceIds.count( shapeInd ))
1966 std::swap( nPrev, nNext );
1967 simplices.push_back( _Simplex( nPrev, nNext ));
1972 vector<_Simplex> sortedSimplices( simplices.size() );
1973 sortedSimplices[0] = simplices[0];
1975 for ( size_t i = 1; i < simplices.size(); ++i )
1977 for ( size_t j = 1; j < simplices.size(); ++j )
1978 if ( sortedSimplices[i-1]._nNext == simplices[j]._nPrev )
1980 sortedSimplices[i] = simplices[j];
1985 if ( nbFound == simplices.size() - 1 )
1986 simplices.swap( sortedSimplices );
1990 //================================================================================
1992 * \brief DEBUG. Create groups contating temorary data of _LayerEdge's
1994 //================================================================================
1996 void _ViscousBuilder::makeGroupOfLE()
1999 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
2001 if ( _sdVec[i]._edges.empty() ) continue;
2002 // string name = SMESH_Comment("_LayerEdge's_") << i;
2004 // SMESH_Group* g = _mesh->AddGroup(SMDSAbs_Edge, name.c_str(), id );
2005 // SMESHDS_Group* gDS = (SMESHDS_Group*)g->GetGroupDS();
2006 // SMESHDS_Mesh* mDS = _mesh->GetMeshDS();
2008 dumpFunction( SMESH_Comment("make_LayerEdge_") << i );
2009 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2011 _LayerEdge* le = _sdVec[i]._edges[j];
2012 for ( unsigned iN = 1; iN < le->_nodes.size(); ++iN )
2013 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<le->_nodes[iN-1]->GetID()
2014 << ", " << le->_nodes[iN]->GetID() <<"])");
2015 //gDS->SMDSGroup().Add( mDS->AddEdge( le->_nodes[iN-1], le->_nodes[iN]));
2019 dumpFunction( SMESH_Comment("makeNormals") << i );
2020 for ( unsigned j = 0 ; j < _sdVec[i]._edges.size(); ++j )
2022 _LayerEdge& edge = *_sdVec[i]._edges[j];
2023 SMESH_TNodeXYZ nXYZ( edge._nodes[0] );
2024 nXYZ += edge._normal * _sdVec[i]._stepSize;
2025 dumpCmd(SMESH_Comment("mesh.AddEdge([ ") <<edge._nodes[0]->GetID()
2026 << ", mesh.AddNode( " << nXYZ.X()<<","<< nXYZ.Y()<<","<< nXYZ.Z()<<")])");
2030 // name = SMESH_Comment("tmp_faces ") << i;
2031 // g = _mesh->AddGroup(SMDSAbs_Face, name.c_str(), id );
2032 // gDS = (SMESHDS_Group*)g->GetGroupDS();
2033 // SMESH_MeshEditor editor( _mesh );
2034 dumpFunction( SMESH_Comment("makeTmpFaces_") << i );
2035 TopExp_Explorer fExp( _sdVec[i]._solid, TopAbs_FACE );
2036 for ( ; fExp.More(); fExp.Next() )
2038 if (const SMESHDS_SubMesh* sm = _sdVec[i]._proxyMesh->GetProxySubMesh( fExp.Current()))
2040 SMDS_ElemIteratorPtr fIt = sm->GetElements();
2041 while ( fIt->more())
2043 const SMDS_MeshElement* e = fIt->next();
2044 SMESH_Comment cmd("mesh.AddFace([");
2045 for ( int j=0; j < e->NbCornerNodes(); ++j )
2046 cmd << e->GetNode(j)->GetID() << (j+1<e->NbCornerNodes() ? ",": "])");
2048 //vector<const SMDS_MeshNode*> nodes( e->begin_nodes(), e->end_nodes() );
2049 //gDS->SMDSGroup().Add( editor.AddElement( nodes, e->GetType(), e->IsPoly()));
2058 //================================================================================
2060 * \brief Increase length of _LayerEdge's to reach the required thickness of layers
2062 //================================================================================
2064 bool _ViscousBuilder::inflate(_SolidData& data)
2066 SMESH_MesherHelper helper( *_mesh );
2068 // Limit inflation step size by geometry size found by itersecting
2069 // normals of _LayerEdge's with mesh faces
2070 double geomSize = Precision::Infinite(), intersecDist;
2071 auto_ptr<SMESH_ElementSearcher> searcher
2072 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2073 data._proxyMesh->GetFaces( data._solid )) );
2074 for ( unsigned i = 0; i < data._edges.size(); ++i )
2076 if ( data._edges[i]->IsOnEdge() ) continue;
2077 data._edges[i]->FindIntersection( *searcher, intersecDist, data._epsilon );
2078 if ( geomSize > intersecDist && intersecDist > 0 )
2079 geomSize = intersecDist;
2081 if ( data._stepSize > 0.3 * geomSize )
2082 limitStepSize( data, 0.3 * geomSize );
2084 const double tgtThick = data._hyp->GetTotalThickness();
2085 if ( data._stepSize > tgtThick )
2086 limitStepSize( data, tgtThick );
2088 if ( data._stepSize < 1. )
2089 data._epsilon = data._stepSize * 1e-7;
2092 cout << "-- geomSize = " << geomSize << ", stepSize = " << data._stepSize << endl;
2095 double avgThick = 0, curThick = 0, distToIntersection = Precision::Infinite();
2096 int nbSteps = 0, nbRepeats = 0;
2097 while ( 1.01 * avgThick < tgtThick )
2099 // new target length
2100 curThick += data._stepSize;
2101 if ( curThick > tgtThick )
2103 curThick = tgtThick + ( tgtThick-avgThick ) * nbRepeats;
2107 // Elongate _LayerEdge's
2108 dumpFunction(SMESH_Comment("inflate")<<data._index<<"_step"<<nbSteps); // debug
2109 for ( unsigned i = 0; i < data._edges.size(); ++i )
2111 data._edges[i]->SetNewLength( curThick, helper );
2116 if ( !updateNormals( data, helper ) )
2119 // Improve and check quality
2120 if ( !smoothAndCheck( data, nbSteps, distToIntersection ))
2124 dumpFunction(SMESH_Comment("invalidate")<<data._index<<"_step"<<nbSteps); // debug
2125 for ( unsigned i = 0; i < data._edges.size(); ++i )
2127 data._edges[i]->InvalidateStep( nbSteps+1 );
2131 break; // no more inflating possible
2135 // Evaluate achieved thickness
2137 for ( unsigned i = 0; i < data._edges.size(); ++i )
2138 avgThick += data._edges[i]->_len;
2139 avgThick /= data._edges.size();
2141 cout << "-- Thickness " << avgThick << " reached" << endl;
2144 if ( distToIntersection < avgThick*1.5 )
2147 cout << "-- Stop inflation since distToIntersection( "<<distToIntersection<<" ) < avgThick( "
2148 << avgThick << " ) * 1.5" << endl;
2153 limitStepSize( data, 0.25 * distToIntersection );
2154 if ( data._stepSizeNodes[0] )
2155 data._stepSize = data._stepSizeCoeff *
2156 SMESH_TNodeXYZ(data._stepSizeNodes[0]).Distance(data._stepSizeNodes[1]);
2160 return error("failed at the very first inflation step", data._index);
2165 //================================================================================
2167 * \brief Improve quality of layer inner surface and check intersection
2169 //================================================================================
2171 bool _ViscousBuilder::smoothAndCheck(_SolidData& data,
2173 double & distToIntersection)
2175 if ( data._endEdgeToSmooth.empty() )
2176 return true; // no shapes needing smoothing
2178 bool moved, improved;
2180 SMESH_MesherHelper helper(*_mesh);
2181 Handle(Geom_Surface) surface;
2185 for ( unsigned iS = 0; iS < data._endEdgeToSmooth.size(); ++iS )
2188 iEnd = data._endEdgeToSmooth[ iS ];
2190 if ( !data._edges[ iBeg ]->_sWOL.IsNull() &&
2191 data._edges[ iBeg ]->_sWOL.ShapeType() == TopAbs_FACE )
2193 if ( !F.IsSame( data._edges[ iBeg ]->_sWOL )) {
2194 F = TopoDS::Face( data._edges[ iBeg ]->_sWOL );
2195 helper.SetSubShape( F );
2196 surface = BRep_Tool::Surface( F );
2201 F.Nullify(); surface.Nullify();
2203 TGeomID sInd = data._edges[ iBeg ]->_nodes[0]->getshapeId();
2205 if ( data._edges[ iBeg ]->IsOnEdge() )
2207 dumpFunction(SMESH_Comment("smooth")<<data._index << "_Ed"<<sInd <<"_InfStep"<<nbSteps);
2209 // try a simple solution on an analytic EDGE
2210 if ( !smoothAnalyticEdge( data, iBeg, iEnd, surface, F, helper ))
2216 for ( int i = iBeg; i < iEnd; ++i )
2218 moved |= data._edges[i]->SmoothOnEdge(surface, F, helper);
2220 dumpCmd( SMESH_Comment("# end step ")<<step);
2222 while ( moved && step++ < 5 );
2223 //cout << " NB STEPS: " << step << endl;
2230 int step = 0, badNb = 0; moved = true;
2231 while (( ++step <= 5 && moved ) || improved )
2233 dumpFunction(SMESH_Comment("smooth")<<data._index<<"_Fa"<<sInd
2234 <<"_InfStep"<<nbSteps<<"_"<<step); // debug
2235 int oldBadNb = badNb;
2238 for ( int i = iBeg; i < iEnd; ++i )
2239 moved |= data._edges[i]->Smooth(badNb);
2240 improved = ( badNb < oldBadNb );
2247 for ( int i = iBeg; i < iEnd; ++i )
2249 _LayerEdge* edge = data._edges[i];
2250 SMESH_TNodeXYZ tgtXYZ( edge->_nodes.back() );
2251 for ( unsigned j = 0; j < edge->_simplices.size(); ++j )
2252 if ( !edge->_simplices[j].IsForward( edge->_nodes[0], &tgtXYZ ))
2254 cout << "Bad simplex ( " << edge->_nodes[0]->GetID()<< " "<< tgtXYZ._node->GetID()
2255 << " "<< edge->_simplices[j]._nPrev->GetID()
2256 << " "<< edge->_simplices[j]._nNext->GetID() << " )" << endl;
2264 } // loop on shapes to smooth
2266 // Check if the last segments of _LayerEdge intersects 2D elements;
2267 // checked elements are either temporary faces or faces on surfaces w/o the layers
2269 auto_ptr<SMESH_ElementSearcher> searcher
2270 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(),
2271 data._proxyMesh->GetFaces( data._solid )) );
2273 distToIntersection = Precision::Infinite();
2275 const SMDS_MeshElement* intFace = 0;
2277 const SMDS_MeshElement* closestFace = 0;
2280 for ( unsigned i = 0; i < data._edges.size(); ++i )
2282 if ( data._edges[i]->FindIntersection( *searcher, dist, data._epsilon, &intFace ))
2284 if ( distToIntersection > dist )
2286 distToIntersection = dist;
2289 closestFace = intFace;
2296 SMDS_MeshElement::iterator nIt = closestFace->begin_nodes();
2297 cout << "Shortest distance: _LayerEdge nodes: tgt " << data._edges[iLE]->_nodes.back()->GetID()
2298 << " src " << data._edges[iLE]->_nodes[0]->GetID()<< ", intersection with face ("
2299 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2300 << ") distance = " << distToIntersection<< endl;
2307 //================================================================================
2309 * \brief Return a curve of the EDGE to be used for smoothing and arrange
2310 * _LayerEdge's to be in a consequent order
2312 //================================================================================
2314 Handle(Geom_Curve) _SolidData::CurveForSmooth( const TopoDS_Edge& E,
2317 Handle(Geom_Surface)& surface,
2318 const TopoDS_Face& F,
2319 SMESH_MesherHelper& helper)
2321 TGeomID eIndex = helper.GetMeshDS()->ShapeToIndex( E );
2323 map< TGeomID, Handle(Geom_Curve)>::iterator i2curve = _edge2curve.find( eIndex );
2325 if ( i2curve == _edge2curve.end() )
2327 // sort _LayerEdge's by position on the EDGE
2329 map< double, _LayerEdge* > u2edge;
2330 for ( int i = iFrom; i < iTo; ++i )
2331 u2edge.insert( make_pair( helper.GetNodeU( E, _edges[i]->_nodes[0] ), _edges[i] ));
2333 ASSERT( u2edge.size() == iTo - iFrom );
2334 map< double, _LayerEdge* >::iterator u2e = u2edge.begin();
2335 for ( int i = iFrom; i < iTo; ++i, ++u2e )
2336 _edges[i] = u2e->second;
2338 // set _2neibors according to the new order
2339 for ( int i = iFrom; i < iTo-1; ++i )
2340 if ( _edges[i]->_2neibors->_nodes[1] != _edges[i+1]->_nodes.back() )
2341 _edges[i]->_2neibors->reverse();
2342 if ( u2edge.size() > 1 &&
2343 _edges[iTo-1]->_2neibors->_nodes[0] != _edges[iTo-2]->_nodes.back() )
2344 _edges[iTo-1]->_2neibors->reverse();
2347 SMESHDS_SubMesh* smDS = helper.GetMeshDS()->MeshElements( eIndex );
2349 TopLoc_Location loc; double f,l;
2351 Handle(Geom_Line) line;
2352 Handle(Geom_Circle) circle;
2353 bool isLine, isCirc;
2354 if ( F.IsNull() ) // 3D case
2356 // check if the EDGE is a line
2357 Handle(Geom_Curve) curve = BRep_Tool::Curve( E, loc, f, l);
2358 if ( curve->IsKind( STANDARD_TYPE( Geom_TrimmedCurve )))
2359 curve = Handle(Geom_TrimmedCurve)::DownCast( curve )->BasisCurve();
2361 line = Handle(Geom_Line)::DownCast( curve );
2362 circle = Handle(Geom_Circle)::DownCast( curve );
2363 isLine = (!line.IsNull());
2364 isCirc = (!circle.IsNull());
2366 if ( !isLine && !isCirc ) // Check if the EDGE is close to a line
2369 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2370 while ( nIt->more() )
2371 bndBox.Add( SMESH_TNodeXYZ( nIt->next() ));
2372 gp_XYZ size = bndBox.CornerMax() - bndBox.CornerMin();
2374 SMESH_TNodeXYZ p0( _edges[iFrom]->_2neibors->_nodes[0] );
2375 SMESH_TNodeXYZ p1( _edges[iFrom]->_2neibors->_nodes[1] );
2376 const double lineTol = 1e-2 * ( p0 - p1 ).Modulus();
2377 for ( int i = 0; i < 3 && !isLine; ++i )
2378 isLine = ( size.Coord( i+1 ) <= lineTol );
2380 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2387 // check if the EDGE is a line
2388 Handle(Geom2d_Curve) curve = BRep_Tool::CurveOnSurface( E, F, f, l);
2389 if ( curve->IsKind( STANDARD_TYPE( Geom2d_TrimmedCurve )))
2390 curve = Handle(Geom2d_TrimmedCurve)::DownCast( curve )->BasisCurve();
2392 Handle(Geom2d_Line) line2d = Handle(Geom2d_Line)::DownCast( curve );
2393 Handle(Geom2d_Circle) circle2d = Handle(Geom2d_Circle)::DownCast( curve );
2394 isLine = (!line2d.IsNull());
2395 isCirc = (!circle2d.IsNull());
2397 if ( !isLine && !isCirc) // Check if the EDGE is close to a line
2400 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
2401 while ( nIt->more() )
2402 bndBox.Add( helper.GetNodeUV( F, nIt->next() ));
2403 gp_XY size = bndBox.CornerMax() - bndBox.CornerMin();
2405 const double lineTol = 1e-2 * sqrt( bndBox.SquareExtent() );
2406 for ( int i = 0; i < 2 && !isLine; ++i )
2407 isLine = ( size.Coord( i+1 ) <= lineTol );
2409 if ( !isLine && !isCirc && iTo-iFrom > 2) // Check if the EDGE is close to a circle
2415 line = new Geom_Line( gp::OX() ); // only type does matter
2419 gp_Pnt2d p = circle2d->Location();
2420 gp_Ax2 ax( gp_Pnt( p.X(), p.Y(), 0), gp::DX());
2421 circle = new Geom_Circle( ax, 1.); // only center position does matter
2425 Handle(Geom_Curve)& res = _edge2curve[ eIndex ];
2433 return i2curve->second;
2436 //================================================================================
2438 * \brief smooth _LayerEdge's on a staight EDGE or circular EDGE
2440 //================================================================================
2442 bool _ViscousBuilder::smoothAnalyticEdge( _SolidData& data,
2445 Handle(Geom_Surface)& surface,
2446 const TopoDS_Face& F,
2447 SMESH_MesherHelper& helper)
2449 TopoDS_Shape S = helper.GetSubShapeByNode( data._edges[ iFrom ]->_nodes[0],
2450 helper.GetMeshDS());
2451 TopoDS_Edge E = TopoDS::Edge( S );
2453 Handle(Geom_Curve) curve = data.CurveForSmooth( E, iFrom, iTo, surface, F, helper );
2454 if ( curve.IsNull() ) return false;
2456 // compute a relative length of segments
2457 vector< double > len( iTo-iFrom+1 );
2459 double curLen, prevLen = len[0] = 1.0;
2460 for ( int i = iFrom; i < iTo; ++i )
2462 curLen = prevLen * data._edges[i]->_2neibors->_wgt[0] / data._edges[i]->_2neibors->_wgt[1];
2463 len[i-iFrom+1] = len[i-iFrom] + curLen;
2468 if ( curve->IsKind( STANDARD_TYPE( Geom_Line )))
2470 if ( F.IsNull() ) // 3D
2472 SMESH_TNodeXYZ p0( data._edges[iFrom]->_2neibors->_nodes[0]);
2473 SMESH_TNodeXYZ p1( data._edges[iTo-1]->_2neibors->_nodes[1]);
2474 for ( int i = iFrom; i < iTo; ++i )
2476 double r = len[i-iFrom] / len.back();
2477 gp_XYZ newPos = p0 * ( 1. - r ) + p1 * r;
2478 data._edges[i]->_pos.back() = newPos;
2479 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2480 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2481 dumpMove( tgtNode );
2486 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2487 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2488 if ( data._edges[iFrom]->_2neibors->_nodes[0] ==
2489 data._edges[iTo-1]->_2neibors->_nodes[1] ) // closed edge
2491 int iPeriodic = helper.GetPeriodicIndex();
2492 if ( iPeriodic == 1 || iPeriodic == 2 )
2494 uv1.SetCoord( iPeriodic, helper.GetOtherParam( uv1.Coord( iPeriodic )));
2495 if ( uv0.Coord( iPeriodic ) > uv1.Coord( iPeriodic ))
2496 std::swap( uv0, uv1 );
2499 const gp_XY rangeUV = uv1 - uv0;
2500 for ( int i = iFrom; i < iTo; ++i )
2502 double r = len[i-iFrom] / len.back();
2503 gp_XY newUV = uv0 + r * rangeUV;
2504 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2506 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2507 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2508 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2509 dumpMove( tgtNode );
2511 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2512 pos->SetUParameter( newUV.X() );
2513 pos->SetVParameter( newUV.Y() );
2519 if ( curve->IsKind( STANDARD_TYPE( Geom_Circle )))
2521 Handle(Geom_Circle) circle = Handle(Geom_Circle)::DownCast( curve );
2522 gp_Pnt center3D = circle->Location();
2524 if ( F.IsNull() ) // 3D
2526 return false; // TODO ???
2530 const gp_XY center( center3D.X(), center3D.Y() );
2532 gp_XY uv0 = helper.GetNodeUV( F, data._edges[iFrom]->_2neibors->_nodes[0]);
2533 gp_XY uvM = helper.GetNodeUV( F, data._edges[iFrom]->_nodes.back());
2534 gp_XY uv1 = helper.GetNodeUV( F, data._edges[iTo-1]->_2neibors->_nodes[1]);
2535 gp_Vec2d vec0( center, uv0 );
2536 gp_Vec2d vecM( center, uvM );
2537 gp_Vec2d vec1( center, uv1 );
2538 double uLast = vec0.Angle( vec1 ); // -PI - +PI
2539 double uMidl = vec0.Angle( vecM );
2540 if ( uLast * uMidl < 0. )
2541 uLast += ( uMidl > 0 ? +2. : -2. ) * M_PI;
2542 const double radius = 0.5 * ( vec0.Magnitude() + vec1.Magnitude() );
2544 gp_Ax2d axis( center, vec0 );
2545 gp_Circ2d circ( axis, radius );
2546 for ( int i = iFrom; i < iTo; ++i )
2548 double newU = uLast * len[i-iFrom] / len.back();
2549 gp_Pnt2d newUV = ElCLib::Value( newU, circ );
2550 data._edges[i]->_pos.back().SetCoord( newUV.X(), newUV.Y(), 0 );
2552 gp_Pnt newPos = surface->Value( newUV.X(), newUV.Y() );
2553 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( data._edges[i]->_nodes.back() );
2554 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
2555 dumpMove( tgtNode );
2557 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
2558 pos->SetUParameter( newUV.X() );
2559 pos->SetVParameter( newUV.Y() );
2568 //================================================================================
2570 * \brief Modify normals of _LayerEdge's on EDGE's to avoid intersection with
2571 * _LayerEdge's on neighbor EDGE's
2573 //================================================================================
2575 bool _ViscousBuilder::updateNormals( _SolidData& data,
2576 SMESH_MesherHelper& helper )
2578 // make temporary quadrangles got by extrusion of
2579 // mesh edges along _LayerEdge._normal's
2581 vector< const SMDS_MeshElement* > tmpFaces;
2583 set< SMESH_TLink > extrudedLinks; // contains target nodes
2584 vector< const SMDS_MeshNode*> nodes(4); // of a tmp mesh face
2586 dumpFunction(SMESH_Comment("makeTmpFacesOnEdges")<<data._index);
2587 for ( unsigned i = 0; i < data._edges.size(); ++i )
2589 _LayerEdge* edge = data._edges[i];
2590 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2591 const SMDS_MeshNode* tgt1 = edge->_nodes.back();
2592 for ( int j = 0; j < 2; ++j ) // loop on _2NearEdges
2594 const SMDS_MeshNode* tgt2 = edge->_2neibors->_nodes[j];
2595 pair< set< SMESH_TLink >::iterator, bool > link_isnew =
2596 extrudedLinks.insert( SMESH_TLink( tgt1, tgt2 ));
2597 if ( !link_isnew.second )
2599 extrudedLinks.erase( link_isnew.first );
2600 continue; // already extruded and will no more encounter
2602 // look for a _LayerEdge containg tgt2
2603 // _LayerEdge* neiborEdge = 0;
2604 // unsigned di = 0; // check _edges[i+di] and _edges[i-di]
2605 // while ( !neiborEdge && ++di <= data._edges.size() )
2607 // if ( i+di < data._edges.size() && data._edges[i+di]->_nodes.back() == tgt2 )
2608 // neiborEdge = data._edges[i+di];
2609 // else if ( di <= i && data._edges[i-di]->_nodes.back() == tgt2 )
2610 // neiborEdge = data._edges[i-di];
2612 // if ( !neiborEdge )
2613 // return error("updateNormals(): neighbor _LayerEdge not found", data._index);
2614 _LayerEdge* neiborEdge = edge->_2neibors->_edges[j];
2616 TmpMeshFaceOnEdge* f = new TmpMeshFaceOnEdge( edge, neiborEdge, --_tmpFaceID );
2617 tmpFaces.push_back( f );
2619 dumpCmd(SMESH_Comment("mesh.AddFace([ ")
2620 <<f->_nn[0]->GetID()<<", "<<f->_nn[1]->GetID()<<", "
2621 <<f->_nn[2]->GetID()<<", "<<f->_nn[3]->GetID()<<" ])");
2626 // Check if _LayerEdge's based on EDGE's intersects tmpFaces.
2627 // Perform two loops on _LayerEdge on EDGE's:
2628 // 1) to find and fix intersection
2629 // 2) to check that no new intersection appears as result of 1)
2631 SMDS_ElemIteratorPtr fIt( new SMDS_ElementVectorIterator( tmpFaces.begin(),
2633 auto_ptr<SMESH_ElementSearcher> searcher
2634 ( SMESH_MeshAlgos::GetElementSearcher( *getMeshDS(), fIt ));
2636 // 1) Find intersections
2638 const SMDS_MeshElement* face;
2639 typedef map< _LayerEdge*, set< _LayerEdge*, _LayerEdgeCmp >, _LayerEdgeCmp > TLEdge2LEdgeSet;
2640 TLEdge2LEdgeSet edge2CloseEdge;
2642 const double eps = data._epsilon * data._epsilon;
2643 for ( unsigned i = 0; i < data._edges.size(); ++i )
2645 _LayerEdge* edge = data._edges[i];
2646 if ( !edge->IsOnEdge() || !edge->_sWOL.IsNull() ) continue;
2647 if ( edge->FindIntersection( *searcher, dist, eps, &face ))
2649 const TmpMeshFaceOnEdge* f = (const TmpMeshFaceOnEdge*) face;
2650 set< _LayerEdge*, _LayerEdgeCmp > & ee = edge2CloseEdge[ edge ];
2651 ee.insert( f->_le1 );
2652 ee.insert( f->_le2 );
2653 if ( f->_le1->IsOnEdge() && f->_le1->_sWOL.IsNull() )
2654 edge2CloseEdge[ f->_le1 ].insert( edge );
2655 if ( f->_le2->IsOnEdge() && f->_le2->_sWOL.IsNull() )
2656 edge2CloseEdge[ f->_le2 ].insert( edge );
2660 // Set _LayerEdge._normal
2662 if ( !edge2CloseEdge.empty() )
2664 dumpFunction(SMESH_Comment("updateNormals")<<data._index);
2666 TLEdge2LEdgeSet::iterator e2ee = edge2CloseEdge.begin();
2667 for ( ; e2ee != edge2CloseEdge.end(); ++e2ee )
2669 _LayerEdge* edge1 = e2ee->first;
2670 _LayerEdge* edge2 = 0;
2671 set< _LayerEdge*, _LayerEdgeCmp >& ee = e2ee->second;
2673 // find EDGEs the edges reside
2675 TopoDS_Shape S = helper.GetSubShapeByNode( edge1->_nodes[0], getMeshDS() );
2676 if ( S.ShapeType() != TopAbs_EDGE )
2677 continue; // TODO: find EDGE by VERTEX
2678 E1 = TopoDS::Edge( S );
2679 set< _LayerEdge*, _LayerEdgeCmp >::iterator eIt = ee.begin();
2680 while ( E2.IsNull() && eIt != ee.end())
2682 _LayerEdge* e2 = *eIt++;
2683 TopoDS_Shape S = helper.GetSubShapeByNode( e2->_nodes[0], getMeshDS() );
2684 if ( S.ShapeType() == TopAbs_EDGE )
2685 E2 = TopoDS::Edge( S ), edge2 = e2;
2687 if ( E2.IsNull() ) continue; // TODO: find EDGE by VERTEX
2689 // find 3 FACEs sharing 2 EDGEs
2691 TopoDS_Face FF1[2], FF2[2];
2692 PShapeIteratorPtr fIt = helper.GetAncestors(E1, *_mesh, TopAbs_FACE);
2693 while ( fIt->more() && FF1[1].IsNull())
2695 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2696 if ( helper.IsSubShape( *F, data._solid))
2697 FF1[ FF1[0].IsNull() ? 0 : 1 ] = *F;
2699 fIt = helper.GetAncestors(E2, *_mesh, TopAbs_FACE);
2700 while ( fIt->more() && FF2[1].IsNull())
2702 const TopoDS_Face *F = (const TopoDS_Face*) fIt->next();
2703 if ( helper.IsSubShape( *F, data._solid))
2704 FF2[ FF2[0].IsNull() ? 0 : 1 ] = *F;
2706 // exclude a FACE common to E1 and E2 (put it at [1] in FF* )
2707 if ( FF1[0].IsSame( FF2[0]) || FF1[0].IsSame( FF2[1]))
2708 std::swap( FF1[0], FF1[1] );
2709 if ( FF2[0].IsSame( FF1[0]) )
2710 std::swap( FF2[0], FF2[1] );
2711 if ( FF1[0].IsNull() || FF2[0].IsNull() )
2714 // // get a new normal for edge1
2716 gp_Vec dir1 = edge1->_normal, dir2 = edge2->_normal;
2717 if ( edge1->_cosin < 0 )
2718 dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok ).Normalized();
2719 if ( edge2->_cosin < 0 )
2720 dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok ).Normalized();
2721 // gp_Vec dir1 = getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2722 // gp_Vec dir2 = getFaceDir( FF2[0], E2, edge2->_nodes[0], helper, ok2 );
2723 // double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2724 // double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2725 // gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2726 // newNorm.Normalize();
2728 double wgt1 = ( edge1->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2729 double wgt2 = ( edge2->_cosin + 1 ) / ( edge1->_cosin + edge2->_cosin + 2 );
2730 gp_Vec newNorm = wgt1 * dir1 + wgt2 * dir2;
2731 newNorm.Normalize();
2733 edge1->_normal = newNorm.XYZ();
2735 // update data of edge1 depending on _normal
2736 const SMDS_MeshNode *n1, *n2;
2737 n1 = edge1->_2neibors->_edges[0]->_nodes[0];
2738 n2 = edge1->_2neibors->_edges[1]->_nodes[0];
2739 //if ( !findNeiborsOnEdge( edge1, n1, n2, data ))
2741 edge1->SetDataByNeighbors( n1, n2, helper );
2743 if ( edge1->_cosin < 0 )
2746 getFaceDir( FF1[0], E1, edge1->_nodes[0], helper, ok );
2747 double angle = dir1.Angle( edge1->_normal ); // [0,PI]
2748 edge1->SetCosin( cos( angle ));
2750 // limit data._stepSize
2751 if ( edge1->_cosin > 0.1 )
2753 SMDS_ElemIteratorPtr fIt = edge1->_nodes[0]->GetInverseElementIterator(SMDSAbs_Face);
2754 while ( fIt->more() )
2755 limitStepSize( data, fIt->next(), edge1->_cosin );
2757 // set new XYZ of target node
2758 edge1->InvalidateStep( 1 );
2760 edge1->SetNewLength( data._stepSize, helper );
2763 // Update normals and other dependent data of not intersecting _LayerEdge's
2764 // neighboring the intersecting ones
2766 for ( e2ee = edge2CloseEdge.begin(); e2ee != edge2CloseEdge.end(); ++e2ee )
2768 _LayerEdge* edge1 = e2ee->first;
2769 if ( !edge1->_2neibors )
2771 for ( int j = 0; j < 2; ++j ) // loop on 2 neighbors
2773 _LayerEdge* neighbor = edge1->_2neibors->_edges[j];
2774 if ( edge2CloseEdge.count ( neighbor ))
2775 continue; // j-th neighbor is also intersected
2776 _LayerEdge* prevEdge = edge1;
2777 const int nbSteps = 6;
2778 for ( int step = nbSteps; step; --step ) // step from edge1 in j-th direction
2780 if ( !neighbor->_2neibors )
2781 break; // neighbor is on VERTEX
2783 _LayerEdge* nextEdge = neighbor->_2neibors->_edges[iNext];
2784 if ( nextEdge == prevEdge )
2785 nextEdge = neighbor->_2neibors->_edges[ ++iNext ];
2786 // const double& wgtPrev = neighbor->_2neibors->_wgt[1-iNext];
2787 // const double& wgtNext = neighbor->_2neibors->_wgt[iNext];
2788 double r = double(step-1)/nbSteps;
2789 if ( !nextEdge->_2neibors )
2792 gp_XYZ newNorm = prevEdge->_normal * r + nextEdge->_normal * (1-r);
2793 newNorm.Normalize();
2795 neighbor->_normal = newNorm;
2796 neighbor->SetCosin( prevEdge->_cosin * r + nextEdge->_cosin * (1-r) );
2797 neighbor->SetDataByNeighbors( prevEdge->_nodes[0], nextEdge->_nodes[0], helper );
2799 neighbor->InvalidateStep( 1 );
2801 neighbor->SetNewLength( data._stepSize, helper );
2803 // goto the next neighbor
2804 prevEdge = neighbor;
2805 neighbor = nextEdge;
2811 // 2) Check absence of intersections
2814 for ( unsigned i = 0 ; i < tmpFaces.size(); ++i )
2820 //================================================================================
2822 * \brief Looks for intersection of it's last segment with faces
2823 * \param distance - returns shortest distance from the last node to intersection
2825 //================================================================================
2827 bool _LayerEdge::FindIntersection( SMESH_ElementSearcher& searcher,
2829 const double& epsilon,
2830 const SMDS_MeshElement** face)
2832 vector< const SMDS_MeshElement* > suspectFaces;
2834 gp_Ax1 lastSegment = LastSegment(segLen);
2835 searcher.GetElementsNearLine( lastSegment, SMDSAbs_Face, suspectFaces );
2837 bool segmentIntersected = false;
2838 distance = Precision::Infinite();
2839 int iFace = -1; // intersected face
2840 for ( unsigned j = 0 ; j < suspectFaces.size() && !segmentIntersected; ++j )
2842 const SMDS_MeshElement* face = suspectFaces[j];
2843 if ( face->GetNodeIndex( _nodes.back() ) >= 0 ||
2844 face->GetNodeIndex( _nodes[0] ) >= 0 )
2845 continue; // face sharing _LayerEdge node
2846 const int nbNodes = face->NbCornerNodes();
2847 bool intFound = false;
2849 SMDS_MeshElement::iterator nIt = face->begin_nodes();
2852 intFound = SegTriaInter( lastSegment, *nIt++, *nIt++, *nIt++, dist, epsilon );
2856 const SMDS_MeshNode* tria[3];
2859 for ( int n2 = 2; n2 < nbNodes && !intFound; ++n2 )
2862 intFound = SegTriaInter(lastSegment, tria[0], tria[1], tria[2], dist, epsilon );
2868 if ( dist < segLen*(1.01) && dist > -(_len-segLen) )
2869 segmentIntersected = true;
2870 if ( distance > dist )
2871 distance = dist, iFace = j;
2874 if ( iFace != -1 && face ) *face = suspectFaces[iFace];
2875 // if ( distance && iFace > -1 )
2877 // // distance is used to limit size of inflation step which depends on
2878 // // whether the intersected face bears viscous layers or not
2879 // bool faceHasVL = suspectFaces[iFace]->GetID() < 1;
2883 if ( segmentIntersected )
2886 SMDS_MeshElement::iterator nIt = suspectFaces[iFace]->begin_nodes();
2887 gp_XYZ intP( lastSegment.Location().XYZ() + lastSegment.Direction().XYZ() * distance );
2888 cout << "nodes: tgt " << _nodes.back()->GetID() << " src " << _nodes[0]->GetID()
2889 << ", intersection with face ("
2890 << (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()<<" "<< (*nIt++)->GetID()
2891 << ") at point (" << intP.X() << ", " << intP.Y() << ", " << intP.Z()
2892 << ") distance = " << distance - segLen<< endl;
2898 return segmentIntersected;
2901 //================================================================================
2903 * \brief Returns size and direction of the last segment
2905 //================================================================================
2907 gp_Ax1 _LayerEdge::LastSegment(double& segLen) const
2909 // find two non-coincident positions
2910 gp_XYZ orig = _pos.back();
2912 int iPrev = _pos.size() - 2;
2913 while ( iPrev >= 0 )
2915 dir = orig - _pos[iPrev];
2916 if ( dir.SquareModulus() > 1e-100 )
2926 segDir.SetLocation( SMESH_TNodeXYZ( _nodes[0] ));
2927 segDir.SetDirection( _normal );
2932 gp_Pnt pPrev = _pos[ iPrev ];
2933 if ( !_sWOL.IsNull() )
2935 TopLoc_Location loc;
2936 if ( _sWOL.ShapeType() == TopAbs_EDGE )
2939 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
2940 pPrev = curve->Value( pPrev.X() ).Transformed( loc );
2944 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
2945 pPrev = surface->Value( pPrev.X(), pPrev.Y() ).Transformed( loc );
2947 dir = SMESH_TNodeXYZ( _nodes.back() ) - pPrev.XYZ();
2949 segDir.SetLocation( pPrev );
2950 segDir.SetDirection( dir );
2951 segLen = dir.Modulus();
2957 //================================================================================
2959 * \brief Test intersection of the last segment with a given triangle
2960 * using Moller-Trumbore algorithm
2961 * Intersection is detected if distance to intersection is less than _LayerEdge._len
2963 //================================================================================
2965 bool _LayerEdge::SegTriaInter( const gp_Ax1& lastSegment,
2966 const SMDS_MeshNode* n0,
2967 const SMDS_MeshNode* n1,
2968 const SMDS_MeshNode* n2,
2970 const double& EPSILON) const
2972 //const double EPSILON = 1e-6;
2974 gp_XYZ orig = lastSegment.Location().XYZ();
2975 gp_XYZ dir = lastSegment.Direction().XYZ();
2977 SMESH_TNodeXYZ vert0( n0 );
2978 SMESH_TNodeXYZ vert1( n1 );
2979 SMESH_TNodeXYZ vert2( n2 );
2981 /* calculate distance from vert0 to ray origin */
2982 gp_XYZ tvec = orig - vert0;
2984 if ( tvec * dir > EPSILON )
2985 // intersected face is at back side of the temporary face this _LayerEdge belongs to
2988 gp_XYZ edge1 = vert1 - vert0;
2989 gp_XYZ edge2 = vert2 - vert0;
2991 /* begin calculating determinant - also used to calculate U parameter */
2992 gp_XYZ pvec = dir ^ edge2;
2994 /* if determinant is near zero, ray lies in plane of triangle */
2995 double det = edge1 * pvec;
2997 if (det > -EPSILON && det < EPSILON)
2999 double inv_det = 1.0 / det;
3001 /* calculate U parameter and test bounds */
3002 double u = ( tvec * pvec ) * inv_det;
3003 if (u < 0.0 || u > 1.0)
3006 /* prepare to test V parameter */
3007 gp_XYZ qvec = tvec ^ edge1;
3009 /* calculate V parameter and test bounds */
3010 double v = (dir * qvec) * inv_det;
3011 if ( v < 0.0 || u + v > 1.0 )
3014 /* calculate t, ray intersects triangle */
3015 t = (edge2 * qvec) * inv_det;
3017 // if (det < EPSILON)
3020 // /* calculate distance from vert0 to ray origin */
3021 // gp_XYZ tvec = orig - vert0;
3023 // /* calculate U parameter and test bounds */
3024 // double u = tvec * pvec;
3025 // if (u < 0.0 || u > det)
3028 // /* prepare to test V parameter */
3029 // gp_XYZ qvec = tvec ^ edge1;
3031 // /* calculate V parameter and test bounds */
3032 // double v = dir * qvec;
3033 // if (v < 0.0 || u + v > det)
3036 // /* calculate t, scale parameters, ray intersects triangle */
3037 // double t = edge2 * qvec;
3038 // double inv_det = 1.0 / det;
3046 //================================================================================
3048 * \brief Perform smooth of _LayerEdge's based on EDGE's
3049 * \retval bool - true if node has been moved
3051 //================================================================================
3053 bool _LayerEdge::SmoothOnEdge(Handle(Geom_Surface)& surface,
3054 const TopoDS_Face& F,
3055 SMESH_MesherHelper& helper)
3057 ASSERT( IsOnEdge() );
3059 SMDS_MeshNode* tgtNode = const_cast<SMDS_MeshNode*>( _nodes.back() );
3060 SMESH_TNodeXYZ oldPos( tgtNode );
3061 double dist01, distNewOld;
3063 SMESH_TNodeXYZ p0( _2neibors->_nodes[0]);
3064 SMESH_TNodeXYZ p1( _2neibors->_nodes[1]);
3065 dist01 = p0.Distance( _2neibors->_nodes[1] );
3067 gp_Pnt newPos = p0 * _2neibors->_wgt[0] + p1 * _2neibors->_wgt[1];
3068 double lenDelta = 0;
3071 //lenDelta = _curvature->lenDelta( _len );
3072 lenDelta = _curvature->lenDeltaByDist( dist01 );
3073 newPos.ChangeCoord() += _normal * lenDelta;
3076 distNewOld = newPos.Distance( oldPos );
3080 if ( _2neibors->_plnNorm )
3082 // put newPos on the plane defined by source node and _plnNorm
3083 gp_XYZ new2src = SMESH_TNodeXYZ( _nodes[0] ) - newPos.XYZ();
3084 double new2srcProj = (*_2neibors->_plnNorm) * new2src;
3085 newPos.ChangeCoord() += (*_2neibors->_plnNorm) * new2srcProj;
3087 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3088 _pos.back() = newPos.XYZ();
3092 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3093 gp_XY uv( Precision::Infinite(), 0 );
3094 helper.CheckNodeUV( F, tgtNode, uv, 1e-10, /*force=*/true );
3095 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3097 newPos = surface->Value( uv.X(), uv.Y() );
3098 tgtNode->setXYZ( newPos.X(), newPos.Y(), newPos.Z() );
3101 if ( _curvature && lenDelta < 0 )
3103 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3104 _len -= prevPos.Distance( oldPos );
3105 _len += prevPos.Distance( newPos );
3107 bool moved = distNewOld > dist01/50;
3109 dumpMove( tgtNode ); // debug
3114 //================================================================================
3116 * \brief Perform laplacian smooth in 3D of nodes inflated from FACE
3117 * \retval bool - true if _tgtNode has been moved
3119 //================================================================================
3121 bool _LayerEdge::Smooth(int& badNb)
3123 if ( _simplices.size() < 2 )
3124 return false; // _LayerEdge inflated along EDGE or FACE
3126 // compute new position for the last _pos
3127 gp_XYZ newPos (0,0,0);
3128 for ( unsigned i = 0; i < _simplices.size(); ++i )
3129 newPos += SMESH_TNodeXYZ( _simplices[i]._nPrev );
3130 newPos /= _simplices.size();
3133 newPos += _normal * _curvature->lenDelta( _len );
3135 gp_Pnt prevPos( _pos[ _pos.size()-2 ]);
3136 // if ( _cosin < -0.1)
3138 // // Avoid decreasing length of edge on concave surface
3139 // //gp_Vec oldMove( _pos[ _pos.size()-2 ], _pos.back() );
3140 // gp_Vec newMove( prevPos, newPos );
3141 // newPos = _pos.back() + newMove.XYZ();
3143 // else if ( _cosin > 0.3 )
3145 // // Avoid increasing length of edge too much
3148 // count quality metrics (orientation) of tetras around _tgtNode
3150 SMESH_TNodeXYZ tgtXYZ( _nodes.back() );
3151 for ( unsigned i = 0; i < _simplices.size(); ++i )
3152 nbOkBefore += _simplices[i].IsForward( _nodes[0], &tgtXYZ );
3155 for ( unsigned i = 0; i < _simplices.size(); ++i )
3156 nbOkAfter += _simplices[i].IsForward( _nodes[0], &newPos );
3158 if ( nbOkAfter < nbOkBefore )
3161 SMDS_MeshNode* n = const_cast< SMDS_MeshNode* >( _nodes.back() );
3163 _len -= prevPos.Distance(SMESH_TNodeXYZ( n ));
3164 _len += prevPos.Distance(newPos);
3166 n->setXYZ( newPos.X(), newPos.Y(), newPos.Z());
3167 _pos.back() = newPos;
3169 badNb += _simplices.size() - nbOkAfter;
3176 //================================================================================
3178 * \brief Add a new segment to _LayerEdge during inflation
3180 //================================================================================
3182 void _LayerEdge::SetNewLength( double len, SMESH_MesherHelper& helper )
3184 if ( _len - len > -1e-6 )
3186 _pos.push_back( _pos.back() );
3190 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3191 SMESH_TNodeXYZ oldXYZ( n );
3192 gp_XYZ nXYZ = oldXYZ + _normal * ( len - _len ) * _lenFactor;
3193 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3195 _pos.push_back( nXYZ );
3197 if ( !_sWOL.IsNull() )
3200 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3202 double u = Precision::Infinite(); // to force projection w/o distance check
3203 helper.CheckNodeU( TopoDS::Edge( _sWOL ), n, u, 1e-10, /*force=*/true, distXYZ );
3204 _pos.back().SetCoord( u, 0, 0 );
3205 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3206 pos->SetUParameter( u );
3210 gp_XY uv( Precision::Infinite(), 0 );
3211 helper.CheckNodeUV( TopoDS::Face( _sWOL ), n, uv, 1e-10, /*force=*/true, distXYZ );
3212 _pos.back().SetCoord( uv.X(), uv.Y(), 0 );
3213 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3214 pos->SetUParameter( uv.X() );
3215 pos->SetVParameter( uv.Y() );
3217 n->setXYZ( distXYZ[1], distXYZ[2], distXYZ[3]);
3219 dumpMove( n ); //debug
3222 //================================================================================
3224 * \brief Remove last inflation step
3226 //================================================================================
3228 void _LayerEdge::InvalidateStep( int curStep )
3230 if ( _pos.size() > curStep )
3232 _pos.resize( curStep );
3233 gp_Pnt nXYZ = _pos.back();
3234 SMDS_MeshNode* n = const_cast< SMDS_MeshNode*>( _nodes.back() );
3235 if ( !_sWOL.IsNull() )
3237 TopLoc_Location loc;
3238 if ( _sWOL.ShapeType() == TopAbs_EDGE )
3240 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( n->GetPosition() );
3241 pos->SetUParameter( nXYZ.X() );
3243 Handle(Geom_Curve) curve = BRep_Tool::Curve( TopoDS::Edge( _sWOL ), loc, f,l);
3244 nXYZ = curve->Value( nXYZ.X() ).Transformed( loc );
3248 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( n->GetPosition() );
3249 pos->SetUParameter( nXYZ.X() );
3250 pos->SetVParameter( nXYZ.Y() );
3251 Handle(Geom_Surface) surface = BRep_Tool::Surface( TopoDS::Face(_sWOL), loc );
3252 nXYZ = surface->Value( nXYZ.X(), nXYZ.Y() ).Transformed( loc );
3255 n->setXYZ( nXYZ.X(), nXYZ.Y(), nXYZ.Z() );
3260 //================================================================================
3262 * \brief Create layers of prisms
3264 //================================================================================
3266 bool _ViscousBuilder::refine(_SolidData& data)
3268 SMESH_MesherHelper helper( *_mesh );
3269 helper.SetSubShape( data._solid );
3270 helper.SetElementsOnShape(false);
3272 Handle(Geom_Curve) curve;
3273 Handle(Geom_Surface) surface;
3274 TopoDS_Edge geomEdge;
3275 TopoDS_Face geomFace;
3276 TopLoc_Location loc;
3277 double f,l, u/*, distXYZ[4]*/;
3281 for ( unsigned i = 0; i < data._edges.size(); ++i )
3283 _LayerEdge& edge = *data._edges[i];
3285 // get accumulated length of segments
3286 vector< double > segLen( edge._pos.size() );
3288 for ( unsigned j = 1; j < edge._pos.size(); ++j )
3289 segLen[j] = segLen[j-1] + (edge._pos[j-1] - edge._pos[j] ).Modulus();
3291 // allocate memory for new nodes if it is not yet refined
3292 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3293 if ( edge._nodes.size() == 2 )
3295 edge._nodes.resize( data._hyp->GetNumberLayers() + 1, 0 );
3297 edge._nodes.back() = tgtNode;
3299 if ( !edge._sWOL.IsNull() )
3301 isOnEdge = ( edge._sWOL.ShapeType() == TopAbs_EDGE );
3302 // restore position of the last node
3306 geomEdge = TopoDS::Edge( edge._sWOL );
3307 curve = BRep_Tool::Curve( geomEdge, loc, f,l);
3308 // double u = helper.GetNodeU( tgtNode );
3309 // p = curve->Value( u );
3313 geomFace = TopoDS::Face( edge._sWOL );
3314 surface = BRep_Tool::Surface( geomFace, loc );
3315 // gp_XY uv = helper.GetNodeUV( tgtNode );
3316 // p = surface->Value( uv.X(), uv.Y() );
3318 // p.Transform( loc );
3319 // const_cast< SMDS_MeshNode* >( tgtNode )->setXYZ( p.X(), p.Y(), p.Z() );
3321 // calculate height of the first layer
3323 const double T = segLen.back(); //data._hyp.GetTotalThickness();
3324 const double f = data._hyp->GetStretchFactor();
3325 const int N = data._hyp->GetNumberLayers();
3326 const double fPowN = pow( f, N );
3327 if ( fPowN - 1 <= numeric_limits<double>::min() )
3330 h0 = T * ( f - 1 )/( fPowN - 1 );
3332 const double zeroLen = std::numeric_limits<double>::min();
3334 // create intermediate nodes
3335 double hSum = 0, hi = h0/f;
3337 for ( unsigned iStep = 1; iStep < edge._nodes.size(); ++iStep )
3339 // compute an intermediate position
3342 while ( hSum > segLen[iSeg] && iSeg < segLen.size()-1)
3344 int iPrevSeg = iSeg-1;
3345 while ( fabs( segLen[iPrevSeg] - segLen[iSeg]) <= zeroLen && iPrevSeg > 0 )
3347 double r = ( segLen[iSeg] - hSum ) / ( segLen[iSeg] - segLen[iPrevSeg] );
3348 gp_Pnt pos = r * edge._pos[iPrevSeg] + (1-r) * edge._pos[iSeg];
3350 SMDS_MeshNode*& node = const_cast< SMDS_MeshNode*& >(edge._nodes[ iStep ]);
3351 if ( !edge._sWOL.IsNull() )
3353 // compute XYZ by parameters <pos>
3357 pos = curve->Value( u ).Transformed(loc);
3361 uv.SetCoord( pos.X(), pos.Y() );
3362 pos = surface->Value( pos.X(), pos.Y() ).Transformed(loc);
3365 // create or update the node
3368 node = helper.AddNode( pos.X(), pos.Y(), pos.Z());
3369 if ( !edge._sWOL.IsNull() )
3372 getMeshDS()->SetNodeOnEdge( node, geomEdge, u );
3374 getMeshDS()->SetNodeOnFace( node, geomFace, uv.X(), uv.Y() );
3378 getMeshDS()->SetNodeInVolume( node, helper.GetSubShapeID() );
3383 if ( !edge._sWOL.IsNull() )
3385 // make average pos from new and current parameters
3388 u = 0.5 * ( u + helper.GetNodeU( geomEdge, node ));
3389 pos = curve->Value( u ).Transformed(loc);
3393 uv = 0.5 * ( uv + helper.GetNodeUV( geomFace, node ));
3394 pos = surface->Value( uv.X(), uv.Y()).Transformed(loc);
3397 node->setXYZ( pos.X(), pos.Y(), pos.Z() );
3402 if ( !getMeshDS()->IsEmbeddedMode() )
3403 // Log node movement
3404 for ( unsigned i = 0; i < data._edges.size(); ++i )
3406 _LayerEdge& edge = *data._edges[i];
3407 SMESH_TNodeXYZ p ( edge._nodes.back() );
3408 getMeshDS()->MoveNode( p._node, p.X(), p.Y(), p.Z() );
3411 // TODO: make quadratic prisms and polyhedrons(?)
3413 helper.SetElementsOnShape(true);
3415 TopExp_Explorer exp( data._solid, TopAbs_FACE );
3416 for ( ; exp.More(); exp.Next() )
3418 if ( _ignoreShapeIds.count( getMeshDS()->ShapeToIndex( exp.Current() )))
3420 SMESHDS_SubMesh* fSubM = getMeshDS()->MeshElements( exp.Current() );
3421 SMDS_ElemIteratorPtr fIt = fSubM->GetElements();
3422 vector< vector<const SMDS_MeshNode*>* > nnVec;
3423 while ( fIt->more() )
3425 const SMDS_MeshElement* face = fIt->next();
3426 int nbNodes = face->NbCornerNodes();
3427 nnVec.resize( nbNodes );
3428 SMDS_ElemIteratorPtr nIt = face->nodesIterator();
3429 for ( int iN = 0; iN < nbNodes; ++iN )
3431 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3432 nnVec[ iN ] = & data._n2eMap[ n ]->_nodes;
3435 int nbZ = nnVec[0]->size();
3439 for ( int iZ = 1; iZ < nbZ; ++iZ )
3440 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1], (*nnVec[2])[iZ-1],
3441 (*nnVec[0])[iZ], (*nnVec[1])[iZ], (*nnVec[2])[iZ]);
3444 for ( int iZ = 1; iZ < nbZ; ++iZ )
3445 helper.AddVolume( (*nnVec[0])[iZ-1], (*nnVec[1])[iZ-1],
3446 (*nnVec[2])[iZ-1], (*nnVec[3])[iZ-1],
3447 (*nnVec[0])[iZ], (*nnVec[1])[iZ],
3448 (*nnVec[2])[iZ], (*nnVec[3])[iZ]);
3451 return error("Not supported type of element", data._index);
3458 //================================================================================
3460 * \brief Shrink 2D mesh on faces to let space for inflated layers
3462 //================================================================================
3464 bool _ViscousBuilder::shrink()
3466 // make map of (ids of FACEs to shrink mesh on) to (_SolidData containing _LayerEdge's
3467 // inflated along FACE or EDGE)
3468 map< TGeomID, _SolidData* > f2sdMap;
3469 for ( unsigned i = 0 ; i < _sdVec.size(); ++i )
3471 _SolidData& data = _sdVec[i];
3472 TopTools_MapOfShape FFMap;
3473 map< TGeomID, TopoDS_Shape >::iterator s2s = data._shrinkShape2Shape.begin();
3474 for (; s2s != data._shrinkShape2Shape.end(); ++s2s )
3475 if ( s2s->second.ShapeType() == TopAbs_FACE )
3477 f2sdMap.insert( make_pair( getMeshDS()->ShapeToIndex( s2s->second ), &data ));
3479 if ( FFMap.Add( (*s2s).second ))
3480 // Put mesh faces on the shrinked FACE to the proxy sub-mesh to avoid
3481 // usage of mesh faces made in addBoundaryElements() by the 3D algo or
3482 // by StdMeshers_QuadToTriaAdaptor
3483 if ( SMESHDS_SubMesh* smDS = getMeshDS()->MeshElements( s2s->second ))
3485 SMESH_ProxyMesh::SubMesh* proxySub =
3486 data._proxyMesh->getFaceSubM( TopoDS::Face( s2s->second ), /*create=*/true);
3487 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3488 while ( fIt->more() )
3489 proxySub->AddElement( fIt->next() );
3490 // as a result 3D algo will use elements from proxySub and not from smDS
3495 SMESH_MesherHelper helper( *_mesh );
3496 helper.ToFixNodeParameters( true );
3499 map< TGeomID, _Shrinker1D > e2shrMap;
3501 // loop on FACES to srink mesh on
3502 map< TGeomID, _SolidData* >::iterator f2sd = f2sdMap.begin();
3503 for ( ; f2sd != f2sdMap.end(); ++f2sd )
3505 _SolidData& data = *f2sd->second;
3506 TNode2Edge& n2eMap = data._n2eMap;
3507 const TopoDS_Face& F = TopoDS::Face( getMeshDS()->IndexToShape( f2sd->first ));
3509 Handle(Geom_Surface) surface = BRep_Tool::Surface(F);
3511 SMESH_subMesh* sm = _mesh->GetSubMesh( F );
3512 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
3514 helper.SetSubShape(F);
3516 // ===========================
3517 // Prepare data for shrinking
3518 // ===========================
3520 // Collect nodes to smooth, as src nodes are not yet replaced by tgt ones
3521 // and thus all nodes on a FACE connected to 2d elements are to be smoothed
3522 vector < const SMDS_MeshNode* > smoothNodes;
3524 SMDS_NodeIteratorPtr nIt = smDS->GetNodes();
3525 while ( nIt->more() )
3527 const SMDS_MeshNode* n = nIt->next();
3528 if ( n->NbInverseElements( SMDSAbs_Face ) > 0 )
3529 smoothNodes.push_back( n );
3532 // Find out face orientation
3534 const set<TGeomID> ignoreShapes;
3536 if ( !smoothNodes.empty() )
3538 vector<_Simplex> simplices;
3539 getSimplices( smoothNodes[0], simplices, ignoreShapes );
3540 helper.GetNodeUV( F, simplices[0]._nPrev, 0, &isOkUV ); // fix UV of silpmex nodes
3541 helper.GetNodeUV( F, simplices[0]._nNext, 0, &isOkUV );
3542 gp_XY uv = helper.GetNodeUV( F, smoothNodes[0], 0, &isOkUV );
3543 if ( !simplices[0].IsForward(uv, smoothNodes[0], F, helper,refSign) )
3547 // Find _LayerEdge's inflated along F
3548 vector< _LayerEdge* > lEdges;
3550 SMESH_subMeshIteratorPtr subIt =
3551 sm->getDependsOnIterator(/*includeSelf=*/false, /*complexShapeFirst=*/false);
3552 while ( subIt->more() )
3554 SMESH_subMesh* sub = subIt->next();
3555 SMESHDS_SubMesh* subDS = sub->GetSubMeshDS();
3556 if ( subDS->NbNodes() == 0 || !n2eMap.count( subDS->GetNodes()->next() ))
3558 SMDS_NodeIteratorPtr nIt = subDS->GetNodes();
3559 while ( nIt->more() )
3561 _LayerEdge* edge = n2eMap[ nIt->next() ];
3562 lEdges.push_back( edge );
3563 prepareEdgeToShrink( *edge, F, helper, smDS );
3568 // Replace source nodes by target nodes in mesh faces to shrink
3569 const SMDS_MeshNode* nodes[20];
3570 for ( unsigned i = 0; i < lEdges.size(); ++i )
3572 _LayerEdge& edge = *lEdges[i];
3573 const SMDS_MeshNode* srcNode = edge._nodes[0];
3574 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3575 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3576 while ( fIt->more() )
3578 const SMDS_MeshElement* f = fIt->next();
3579 if ( !smDS->Contains( f ))
3581 SMDS_ElemIteratorPtr nIt = f->nodesIterator();
3582 for ( int iN = 0; iN < f->NbNodes(); ++iN )
3584 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
3585 nodes[iN] = ( n == srcNode ? tgtNode : n );
3587 helper.GetMeshDS()->ChangeElementNodes( f, nodes, f->NbNodes() );
3591 // find out if a FACE is concave
3592 const bool isConcaveFace = isConcave( F, helper );
3594 // Create _SmoothNode's on face F
3595 vector< _SmoothNode > nodesToSmooth( smoothNodes.size() );
3597 dumpFunction(SMESH_Comment("beforeShrinkFace")<<f2sd->first); // debug
3598 for ( unsigned i = 0; i < smoothNodes.size(); ++i )
3600 const SMDS_MeshNode* n = smoothNodes[i];
3601 nodesToSmooth[ i ]._node = n;
3602 // src nodes must be replaced by tgt nodes to have tgt nodes in _simplices
3603 getSimplices( n, nodesToSmooth[ i ]._simplices, ignoreShapes, NULL, isConcaveFace );
3604 // fix up incorrect uv of nodes on the FACE
3605 helper.GetNodeUV( F, n, 0, &isOkUV);
3610 //if ( nodesToSmooth.empty() ) continue;
3612 // Find EDGE's to shrink
3613 set< _Shrinker1D* > eShri1D;
3615 for ( unsigned i = 0; i < lEdges.size(); ++i )
3617 _LayerEdge* edge = lEdges[i];
3618 if ( edge->_sWOL.ShapeType() == TopAbs_EDGE )
3620 TGeomID edgeIndex = getMeshDS()->ShapeToIndex( edge->_sWOL );
3621 _Shrinker1D& srinker = e2shrMap[ edgeIndex ];
3622 eShri1D.insert( & srinker );
3623 srinker.AddEdge( edge, helper );
3624 VISCOUS_3D::ToClearSubWithMain( _mesh->GetSubMesh( edge->_sWOL ), data._solid );
3625 // restore params of nodes on EGDE if the EDGE has been already
3626 // srinked while srinking another FACE
3627 srinker.RestoreParams();
3632 // ==================
3633 // Perform shrinking
3634 // ==================
3636 bool shrinked = true;
3637 int badNb, shriStep=0, smooStep=0;
3640 // Move boundary nodes (actually just set new UV)
3641 // -----------------------------------------------
3642 dumpFunction(SMESH_Comment("moveBoundaryOnF")<<f2sd->first<<"_st"<<shriStep++ ); // debug
3644 for ( unsigned i = 0; i < lEdges.size(); ++i )
3646 shrinked |= lEdges[i]->SetNewLength2d( surface,F,helper );
3650 // Move nodes on EDGE's
3651 set< _Shrinker1D* >::iterator shr = eShri1D.begin();
3652 for ( ; shr != eShri1D.end(); ++shr )
3653 (*shr)->Compute( /*set3D=*/false, helper );
3656 // -----------------
3657 int nbNoImpSteps = 0;
3660 while (( nbNoImpSteps < 5 && badNb > 0) && moved)
3662 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3664 int oldBadNb = badNb;
3667 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3669 moved |= nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3670 /*isCentroidal=*/isConcaveFace,
3671 /*set3D=*/isConcaveFace);
3673 if ( badNb < oldBadNb )
3681 return error(SMESH_Comment("Can't shrink 2D mesh on face ") << f2sd->first );
3683 // No wrongly shaped faces remain; final smooth. Set node XYZ.
3684 // First, find out a needed quality of smoothing (high for quadrangles only)
3687 const bool hasTria = _mesh->NbTriangles(), hasQuad = _mesh->NbQuadrangles();
3688 if ( hasTria != hasQuad ) {
3689 highQuality = hasQuad;
3692 set<int> nbNodesSet;
3693 SMDS_ElemIteratorPtr fIt = smDS->GetElements();
3694 while ( fIt->more() && nbNodesSet.size() < 2 )
3695 nbNodesSet.insert( fIt->next()->NbCornerNodes() );
3696 highQuality = ( *nbNodesSet.begin() == 4 );
3699 if ( !highQuality && isConcaveFace )
3700 fixBadFaces( F, helper ); // fix narrow faces by swaping diagonals
3701 for ( int st = highQuality ? 10 : 3; st; --st )
3703 dumpFunction(SMESH_Comment("shrinkFace")<<f2sd->first<<"_st"<<++smooStep); // debug
3704 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3705 nodesToSmooth[i].Smooth( badNb,surface,helper,refSign,
3706 /*isCentroidal=*/isConcaveFace,/*set3D=*/st==1 );
3709 // Set an event listener to clear FACE sub-mesh together with SOLID sub-mesh
3710 VISCOUS_3D::ToClearSubWithMain( sm, data._solid );
3712 if ( !getMeshDS()->IsEmbeddedMode() )
3713 // Log node movement
3714 for ( unsigned i = 0; i < nodesToSmooth.size(); ++i )
3716 SMESH_TNodeXYZ p ( nodesToSmooth[i]._node );
3717 getMeshDS()->MoveNode( nodesToSmooth[i]._node, p.X(), p.Y(), p.Z() );
3720 } // loop on FACES to srink mesh on
3723 // Replace source nodes by target nodes in shrinked mesh edges
3725 map< int, _Shrinker1D >::iterator e2shr = e2shrMap.begin();
3726 for ( ; e2shr != e2shrMap.end(); ++e2shr )
3727 e2shr->second.SwapSrcTgtNodes( getMeshDS() );
3732 //================================================================================
3734 * \brief Computes 2d shrink direction and finds nodes limiting shrinking
3736 //================================================================================
3738 bool _ViscousBuilder::prepareEdgeToShrink( _LayerEdge& edge,
3739 const TopoDS_Face& F,
3740 SMESH_MesherHelper& helper,
3741 const SMESHDS_SubMesh* faceSubMesh)
3743 const SMDS_MeshNode* srcNode = edge._nodes[0];
3744 const SMDS_MeshNode* tgtNode = edge._nodes.back();
3748 if ( edge._sWOL.ShapeType() == TopAbs_FACE )
3750 gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3751 gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3752 gp_Vec2d uvDir( srcUV, tgtUV );
3753 double uvLen = uvDir.Magnitude();
3755 edge._normal.SetCoord( uvDir.X(),uvDir.Y(), 0);
3757 // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3758 vector<const SMDS_MeshElement*> faces;
3759 multimap< double, const SMDS_MeshNode* > proj2node;
3760 SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3761 while ( fIt->more() )
3763 const SMDS_MeshElement* f = fIt->next();
3764 if ( faceSubMesh->Contains( f ))
3765 faces.push_back( f );
3767 for ( unsigned i = 0; i < faces.size(); ++i )
3769 const int nbNodes = faces[i]->NbCornerNodes();
3770 for ( int j = 0; j < nbNodes; ++j )
3772 const SMDS_MeshNode* n = faces[i]->GetNode(j);
3773 if ( n == srcNode ) continue;
3774 if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE &&
3775 ( faces.size() > 1 || nbNodes > 3 ))
3777 gp_Pnt2d uv = helper.GetNodeUV( F, n );
3778 gp_Vec2d uvDirN( srcUV, uv );
3779 double proj = uvDirN * uvDir;
3780 proj2node.insert( make_pair( proj, n ));
3784 multimap< double, const SMDS_MeshNode* >::iterator p2n = proj2node.begin(), p2nEnd;
3785 const double minProj = p2n->first;
3786 const double projThreshold = 1.1 * uvLen;
3787 if ( minProj > projThreshold )
3789 // tgtNode is located so that it does not make faces with wrong orientation
3792 edge._pos.resize(1);
3793 edge._pos[0].SetCoord( tgtUV.X(), tgtUV.Y(), 0 );
3795 // store most risky nodes in _simplices
3796 p2nEnd = proj2node.lower_bound( projThreshold );
3797 int nbSimpl = ( std::distance( p2n, p2nEnd ) + 1) / 2;
3798 edge._simplices.resize( nbSimpl );
3799 for ( int i = 0; i < nbSimpl; ++i )
3801 edge._simplices[i]._nPrev = p2n->second;
3802 if ( ++p2n != p2nEnd )
3803 edge._simplices[i]._nNext = p2n->second;
3805 // set UV of source node to target node
3806 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
3807 pos->SetUParameter( srcUV.X() );
3808 pos->SetVParameter( srcUV.Y() );
3810 else // _sWOL is TopAbs_EDGE
3812 TopoDS_Edge E = TopoDS::Edge( edge._sWOL);
3813 SMESHDS_SubMesh* edgeSM = getMeshDS()->MeshElements( E );
3814 if ( !edgeSM || edgeSM->NbElements() == 0 )
3815 return error(SMESH_Comment("Not meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3817 const SMDS_MeshNode* n2 = 0;
3818 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
3819 while ( eIt->more() && !n2 )
3821 const SMDS_MeshElement* e = eIt->next();
3822 if ( !edgeSM->Contains(e)) continue;
3823 n2 = e->GetNode( 0 );
3824 if ( n2 == srcNode ) n2 = e->GetNode( 1 );
3827 return error(SMESH_Comment("Wrongly meshed EDGE ") << getMeshDS()->ShapeToIndex( E ));
3829 double uSrc = helper.GetNodeU( E, srcNode, n2 );
3830 double uTgt = helper.GetNodeU( E, tgtNode, srcNode );
3831 double u2 = helper.GetNodeU( E, n2, srcNode );
3833 if ( fabs( uSrc-uTgt ) < 0.99 * fabs( uSrc-u2 ))
3835 // tgtNode is located so that it does not make faces with wrong orientation
3838 edge._pos.resize(1);
3839 edge._pos[0].SetCoord( U_TGT, uTgt );
3840 edge._pos[0].SetCoord( U_SRC, uSrc );
3841 edge._pos[0].SetCoord( LEN_TGT, fabs( uSrc-uTgt ));
3843 edge._simplices.resize( 1 );
3844 edge._simplices[0]._nPrev = n2;
3846 // set UV of source node to target node
3847 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
3848 pos->SetUParameter( uSrc );
3852 //================================================================================
3854 * \brief Compute positions (UV) to set to a node on edge moved during shrinking
3856 //================================================================================
3858 // Compute UV to follow during shrinking
3860 // const SMDS_MeshNode* srcNode = edge._nodes[0];
3861 // const SMDS_MeshNode* tgtNode = edge._nodes.back();
3863 // gp_XY srcUV = helper.GetNodeUV( F, srcNode );
3864 // gp_XY tgtUV = helper.GetNodeUV( F, tgtNode );
3865 // gp_Vec2d uvDir( srcUV, tgtUV );
3866 // double uvLen = uvDir.Magnitude();
3869 // // Select shrinking step such that not to make faces with wrong orientation.
3870 // // IMPORTANT to have src nodes NOT yet REPLACED by tgt nodes in shrinked faces
3871 // const double minStepSize = uvLen / 20;
3872 // double stepSize = uvLen;
3873 // SMDS_ElemIteratorPtr fIt = srcNode->GetInverseElementIterator(SMDSAbs_Face);
3874 // while ( fIt->more() )
3876 // const SMDS_MeshElement* f = fIt->next();
3877 // if ( !faceSubMesh->Contains( f )) continue;
3878 // const int nbNodes = f->NbCornerNodes();
3879 // for ( int i = 0; i < nbNodes; ++i )
3881 // const SMDS_MeshNode* n = f->GetNode(i);
3882 // if ( n->GetPosition()->GetTypeOfPosition() != SMDS_TOP_FACE || n == srcNode)
3884 // gp_XY uv = helper.GetNodeUV( F, n );
3885 // gp_Vec2d uvDirN( srcUV, uv );
3886 // double proj = uvDirN * uvDir;
3887 // if ( proj < stepSize && proj > minStepSize )
3893 // const int nbSteps = ceil( uvLen / stepSize );
3894 // gp_XYZ srcUV0( srcUV.X(), srcUV.Y(), 0 );
3895 // gp_XYZ tgtUV0( tgtUV.X(), tgtUV.Y(), 0 );
3896 // edge._pos.resize( nbSteps );
3897 // edge._pos[0] = tgtUV0;
3898 // for ( int i = 1; i < nbSteps; ++i )
3900 // double r = i / double( nbSteps );
3901 // edge._pos[i] = (1-r) * tgtUV0 + r * srcUV0;
3906 //================================================================================
3908 * \brief Try to fix triangles with high aspect ratio by swaping diagonals
3910 //================================================================================
3912 void _ViscousBuilder::fixBadFaces(const TopoDS_Face& F, SMESH_MesherHelper& helper)
3914 SMESH::Controls::AspectRatio qualifier;
3915 SMESH::Controls::TSequenceOfXYZ points(3), points1(3), points2(3);
3916 const double maxAspectRatio = 4.;
3918 // find bad triangles
3920 vector< const SMDS_MeshElement* > badTrias;
3921 vector< double > badAspects;
3922 SMESHDS_SubMesh* sm = helper.GetMeshDS()->MeshElements( F );
3923 SMDS_ElemIteratorPtr fIt = sm->GetElements();
3924 while ( fIt->more() )
3926 const SMDS_MeshElement * f = fIt->next();
3927 if ( f->NbCornerNodes() != 3 ) continue;
3928 for ( int iP = 0; iP < 3; ++iP ) points(iP+1) = SMESH_TNodeXYZ( f->GetNode(iP));
3929 double aspect = qualifier.GetValue( points );
3930 if ( aspect > maxAspectRatio )
3932 badTrias.push_back( f );
3933 badAspects.push_back( aspect );
3936 if ( badTrias.empty() )
3939 // find couples of faces to swap diagonal
3941 typedef pair < const SMDS_MeshElement* , const SMDS_MeshElement* > T2Trias;
3942 vector< T2Trias > triaCouples;
3944 TIDSortedElemSet involvedFaces, emptySet;
3945 for ( size_t iTia = 0; iTia < badTrias.size(); ++iTia )
3948 double aspRatio [3];
3951 involvedFaces.insert( badTrias[iTia] );
3952 for ( int iP = 0; iP < 3; ++iP )
3953 points(iP+1) = SMESH_TNodeXYZ( badTrias[iTia]->GetNode(iP));
3955 // find triangles adjacent to badTrias[iTia] with better aspect ratio after diag-swaping
3956 int bestCouple = -1;
3957 for ( int iSide = 0; iSide < 3; ++iSide )
3959 const SMDS_MeshNode* n1 = badTrias[iTia]->GetNode( iSide );
3960 const SMDS_MeshNode* n2 = badTrias[iTia]->GetNode(( iSide+1 ) % 3 );
3961 trias [iSide].first = badTrias[iTia];
3962 trias [iSide].second = SMESH_MeshAlgos::FindFaceInSet( n1, n2, emptySet, involvedFaces,
3964 if ( ! trias[iSide].second || trias[iSide].second->NbCornerNodes() != 3 )
3967 // aspect ratio of an adjacent tria
3968 for ( int iP = 0; iP < 3; ++iP )
3969 points2(iP+1) = SMESH_TNodeXYZ( trias[iSide].second->GetNode(iP));
3970 double aspectInit = qualifier.GetValue( points2 );
3972 // arrange nodes as after diag-swaping
3973 if ( helper.WrapIndex( i1+1, 3 ) == i2 )
3974 i3 = helper.WrapIndex( i1-1, 3 );
3976 i3 = helper.WrapIndex( i1+1, 3 );
3978 points1( 1+ iSide ) = points2( 1+ i3 );
3979 points2( 1+ i2 ) = points1( 1+ ( iSide+2 ) % 3 );
3981 // aspect ratio after diag-swaping
3982 aspRatio[ iSide ] = qualifier.GetValue( points1 ) + qualifier.GetValue( points2 );
3983 if ( aspRatio[ iSide ] > aspectInit + badAspects[ iTia ] )
3986 if ( bestCouple < 0 || aspRatio[ bestCouple ] > aspRatio[ iSide ] )
3990 if ( bestCouple >= 0 )
3992 triaCouples.push_back( trias[bestCouple] );
3993 involvedFaces.insert ( trias[bestCouple].second );
3997 involvedFaces.erase( badTrias[iTia] );
4000 if ( triaCouples.empty() )
4005 SMESH_MeshEditor editor( helper.GetMesh() );
4006 dumpFunction(SMESH_Comment("beforeSwapDiagonals_F")<<helper.GetSubShapeID());
4007 for ( size_t i = 0; i < triaCouples.size(); ++i )
4009 dumpChangeNodes( triaCouples[i].first );
4010 dumpChangeNodes( triaCouples[i].second );
4011 editor.InverseDiag( triaCouples[i].first, triaCouples[i].second );
4015 // just for debug dump resulting triangles
4016 dumpFunction(SMESH_Comment("swapDiagonals_F")<<helper.GetSubShapeID());
4017 for ( size_t i = 0; i < triaCouples.size(); ++i )
4019 dumpChangeNodes( triaCouples[i].first );
4020 dumpChangeNodes( triaCouples[i].second );
4024 //================================================================================
4026 * \brief Move target node to it's final position on the FACE during shrinking
4028 //================================================================================
4030 bool _LayerEdge::SetNewLength2d( Handle(Geom_Surface)& surface,
4031 const TopoDS_Face& F,
4032 SMESH_MesherHelper& helper )
4035 return false; // already at the target position
4037 SMDS_MeshNode* tgtNode = const_cast< SMDS_MeshNode*& >( _nodes.back() );
4039 if ( _sWOL.ShapeType() == TopAbs_FACE )
4041 gp_XY curUV = helper.GetNodeUV( F, tgtNode );
4042 gp_Pnt2d tgtUV( _pos[0].X(), _pos[0].Y());
4043 gp_Vec2d uvDir( _normal.X(), _normal.Y() );
4044 const double uvLen = tgtUV.Distance( curUV );
4046 // Select shrinking step such that not to make faces with wrong orientation.
4047 const double kSafe = 0.8;
4048 const double minStepSize = uvLen / 10;
4049 double stepSize = uvLen;
4050 for ( unsigned i = 0; i < _simplices.size(); ++i )
4052 const SMDS_MeshNode* nn[2] = { _simplices[i]._nPrev, _simplices[i]._nNext };
4053 for ( int j = 0; j < 2; ++j )
4054 if ( const SMDS_MeshNode* n = nn[j] )
4056 gp_XY uv = helper.GetNodeUV( F, n );
4057 gp_Vec2d uvDirN( curUV, uv );
4058 double proj = uvDirN * uvDir * kSafe;
4059 if ( proj < stepSize && proj > minStepSize )
4065 if ( stepSize == uvLen )
4072 newUV = curUV + uvDir.XY() * stepSize;
4075 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( tgtNode->GetPosition() );
4076 pos->SetUParameter( newUV.X() );
4077 pos->SetVParameter( newUV.Y() );
4080 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4081 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4082 dumpMove( tgtNode );
4085 else // _sWOL is TopAbs_EDGE
4087 TopoDS_Edge E = TopoDS::Edge( _sWOL );
4088 const SMDS_MeshNode* n2 = _simplices[0]._nPrev;
4090 const double u2 = helper.GetNodeU( E, n2, tgtNode );
4091 const double uSrc = _pos[0].Coord( U_SRC );
4092 const double lenTgt = _pos[0].Coord( LEN_TGT );
4094 double newU = _pos[0].Coord( U_TGT );
4095 if ( lenTgt < 0.99 * fabs( uSrc-u2 ))
4101 newU = 0.1 * uSrc + 0.9 * u2;
4103 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( tgtNode->GetPosition() );
4104 pos->SetUParameter( newU );
4106 gp_XY newUV = helper.GetNodeUV( F, tgtNode, _nodes[0]);
4107 gp_Pnt p = surface->Value( newUV.X(), newUV.Y() );
4108 tgtNode->setXYZ( p.X(), p.Y(), p.Z() );
4109 dumpMove( tgtNode );
4115 //================================================================================
4117 * \brief Perform smooth on the FACE
4118 * \retval bool - true if the node has been moved
4120 //================================================================================
4122 bool _SmoothNode::Smooth(int& badNb,
4123 Handle(Geom_Surface)& surface,
4124 SMESH_MesherHelper& helper,
4125 const double refSign,
4129 const TopoDS_Face& face = TopoDS::Face( helper.GetSubShape() );
4131 // get uv of surrounding nodes
4132 vector<gp_XY> uv( _simplices.size() );
4133 for ( size_t i = 0; i < _simplices.size(); ++i )
4134 uv[i] = helper.GetNodeUV( face, _simplices[i]._nPrev, _node );
4136 // compute new UV for the node
4138 if ( isCentroidal && _simplices.size() > 3 )
4140 // average centers of diagonals wieghted with their reciprocal lengths
4141 if ( _simplices.size() == 4 )
4143 double w1 = 1. / ( uv[2]-uv[0] ).SquareModulus();
4144 double w2 = 1. / ( uv[3]-uv[1] ).SquareModulus();
4145 newPos = ( w1 * ( uv[2]+uv[0] ) + w2 * ( uv[3]+uv[1] )) / ( w1+w2 ) / 2;
4149 double sumWeight = 0;
4150 int nb = _simplices.size() == 4 ? 2 : _simplices.size();
4151 for ( int i = 0; i < nb; ++i )
4154 int iTo = i + _simplices.size() - 1;
4155 for ( int j = iFrom; j < iTo; ++j )
4157 int i2 = SMESH_MesherHelper::WrapIndex( j, _simplices.size() );
4158 double w = 1. / ( uv[i]-uv[i2] ).SquareModulus();
4160 newPos += w * ( uv[i]+uv[i2] );
4163 newPos /= 2 * sumWeight;
4169 isCentroidal = false;
4170 for ( size_t i = 0; i < _simplices.size(); ++i )
4172 newPos /= _simplices.size();
4175 // count quality metrics (orientation) of triangles around the node
4177 gp_XY tgtUV = helper.GetNodeUV( face, _node );
4178 for ( unsigned i = 0; i < _simplices.size(); ++i )
4179 nbOkBefore += _simplices[i].IsForward( tgtUV, _node, face, helper, refSign );
4182 for ( unsigned i = 0; i < _simplices.size(); ++i )
4183 nbOkAfter += _simplices[i].IsForward( newPos, _node, face, helper, refSign );
4185 if ( nbOkAfter < nbOkBefore )
4187 // if ( isCentroidal )
4188 // return Smooth( badNb, surface, helper, refSign, !isCentroidal, set3D );
4189 badNb += _simplices.size() - nbOkBefore;
4193 SMDS_FacePosition* pos = static_cast<SMDS_FacePosition*>( _node->GetPosition() );
4194 pos->SetUParameter( newPos.X() );
4195 pos->SetVParameter( newPos.Y() );
4202 gp_Pnt p = surface->Value( newPos.X(), newPos.Y() );
4203 const_cast< SMDS_MeshNode* >( _node )->setXYZ( p.X(), p.Y(), p.Z() );
4207 badNb += _simplices.size() - nbOkAfter;
4208 return ( (tgtUV-newPos).SquareModulus() > 1e-10 );
4211 //================================================================================
4213 * \brief Delete _SolidData
4215 //================================================================================
4217 _SolidData::~_SolidData()
4219 for ( unsigned i = 0; i < _edges.size(); ++i )
4221 if ( _edges[i] && _edges[i]->_2neibors )
4222 delete _edges[i]->_2neibors;
4227 //================================================================================
4229 * \brief Add a _LayerEdge inflated along the EDGE
4231 //================================================================================
4233 void _Shrinker1D::AddEdge( const _LayerEdge* e, SMESH_MesherHelper& helper )
4236 if ( _nodes.empty() )
4238 _edges[0] = _edges[1] = 0;
4242 if ( e == _edges[0] || e == _edges[1] )
4244 if ( e->_sWOL.IsNull() || e->_sWOL.ShapeType() != TopAbs_EDGE )
4245 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4246 if ( _edges[0] && _edges[0]->_sWOL != e->_sWOL )
4247 throw SALOME_Exception(LOCALIZED("Wrong _LayerEdge is added"));
4250 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4252 BRep_Tool::Range( E, f,l );
4253 double u = helper.GetNodeU( E, e->_nodes[0], e->_nodes.back());
4254 _edges[ u < 0.5*(f+l) ? 0 : 1 ] = e;
4258 const SMDS_MeshNode* tgtNode0 = _edges[0] ? _edges[0]->_nodes.back() : 0;
4259 const SMDS_MeshNode* tgtNode1 = _edges[1] ? _edges[1]->_nodes.back() : 0;
4261 if ( _nodes.empty() )
4263 SMESHDS_SubMesh * eSubMesh = helper.GetMeshDS()->MeshElements( E );
4264 if ( !eSubMesh || eSubMesh->NbNodes() < 1 )
4266 TopLoc_Location loc;
4267 Handle(Geom_Curve) C = BRep_Tool::Curve(E, loc, f,l);
4268 GeomAdaptor_Curve aCurve(C, f,l);
4269 const double totLen = GCPnts_AbscissaPoint::Length(aCurve, f, l);
4271 int nbExpectNodes = eSubMesh->NbNodes();
4272 _initU .reserve( nbExpectNodes );
4273 _normPar.reserve( nbExpectNodes );
4274 _nodes .reserve( nbExpectNodes );
4275 SMDS_NodeIteratorPtr nIt = eSubMesh->GetNodes();
4276 while ( nIt->more() )
4278 const SMDS_MeshNode* node = nIt->next();
4279 if ( node->NbInverseElements(SMDSAbs_Edge) == 0 ||
4280 node == tgtNode0 || node == tgtNode1 )
4281 continue; // refinement nodes
4282 _nodes.push_back( node );
4283 _initU.push_back( helper.GetNodeU( E, node ));
4284 double len = GCPnts_AbscissaPoint::Length(aCurve, f, _initU.back());
4285 _normPar.push_back( len / totLen );
4290 // remove target node of the _LayerEdge from _nodes
4292 for ( unsigned i = 0; i < _nodes.size(); ++i )
4293 if ( !_nodes[i] || _nodes[i] == tgtNode0 || _nodes[i] == tgtNode1 )
4294 _nodes[i] = 0, nbFound++;
4295 if ( nbFound == _nodes.size() )
4300 //================================================================================
4302 * \brief Move nodes on EDGE from ends where _LayerEdge's are inflated
4304 //================================================================================
4306 void _Shrinker1D::Compute(bool set3D, SMESH_MesherHelper& helper)
4308 if ( _done || _nodes.empty())
4310 const _LayerEdge* e = _edges[0];
4311 if ( !e ) e = _edges[1];
4314 _done = (( !_edges[0] || _edges[0]->_pos.empty() ) &&
4315 ( !_edges[1] || _edges[1]->_pos.empty() ));
4317 const TopoDS_Edge& E = TopoDS::Edge( e->_sWOL );
4319 if ( set3D || _done )
4321 Handle(Geom_Curve) C = BRep_Tool::Curve(E, f,l);
4322 GeomAdaptor_Curve aCurve(C, f,l);
4325 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4327 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4328 double totLen = GCPnts_AbscissaPoint::Length( aCurve, f, l );
4330 for ( unsigned i = 0; i < _nodes.size(); ++i )
4332 if ( !_nodes[i] ) continue;
4333 double len = totLen * _normPar[i];
4334 GCPnts_AbscissaPoint discret( aCurve, len, f );
4335 if ( !discret.IsDone() )
4336 return throw SALOME_Exception(LOCALIZED("GCPnts_AbscissaPoint failed"));
4337 double u = discret.Parameter();
4338 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4339 pos->SetUParameter( u );
4340 gp_Pnt p = C->Value( u );
4341 const_cast< SMDS_MeshNode*>( _nodes[i] )->setXYZ( p.X(), p.Y(), p.Z() );
4346 BRep_Tool::Range( E, f,l );
4348 f = helper.GetNodeU( E, _edges[0]->_nodes.back(), _nodes[0] );
4350 l = helper.GetNodeU( E, _edges[1]->_nodes.back(), _nodes.back() );
4352 for ( unsigned i = 0; i < _nodes.size(); ++i )
4354 if ( !_nodes[i] ) continue;
4355 double u = f * ( 1-_normPar[i] ) + l * _normPar[i];
4356 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4357 pos->SetUParameter( u );
4362 //================================================================================
4364 * \brief Restore initial parameters of nodes on EDGE
4366 //================================================================================
4368 void _Shrinker1D::RestoreParams()
4371 for ( unsigned i = 0; i < _nodes.size(); ++i )
4373 if ( !_nodes[i] ) continue;
4374 SMDS_EdgePosition* pos = static_cast<SMDS_EdgePosition*>( _nodes[i]->GetPosition() );
4375 pos->SetUParameter( _initU[i] );
4380 //================================================================================
4382 * \brief Replace source nodes by target nodes in shrinked mesh edges
4384 //================================================================================
4386 void _Shrinker1D::SwapSrcTgtNodes( SMESHDS_Mesh* mesh )
4388 const SMDS_MeshNode* nodes[3];
4389 for ( int i = 0; i < 2; ++i )
4391 if ( !_edges[i] ) continue;
4393 SMESHDS_SubMesh * eSubMesh = mesh->MeshElements( _edges[i]->_sWOL );
4394 if ( !eSubMesh ) return;
4395 const SMDS_MeshNode* srcNode = _edges[i]->_nodes[0];
4396 const SMDS_MeshNode* tgtNode = _edges[i]->_nodes.back();
4397 SMDS_ElemIteratorPtr eIt = srcNode->GetInverseElementIterator(SMDSAbs_Edge);
4398 while ( eIt->more() )
4400 const SMDS_MeshElement* e = eIt->next();
4401 if ( !eSubMesh->Contains( e ))
4403 SMDS_ElemIteratorPtr nIt = e->nodesIterator();
4404 for ( int iN = 0; iN < e->NbNodes(); ++iN )
4406 const SMDS_MeshNode* n = static_cast<const SMDS_MeshNode*>( nIt->next() );
4407 nodes[iN] = ( n == srcNode ? tgtNode : n );
4409 mesh->ChangeElementNodes( e, nodes, e->NbNodes() );
4414 //================================================================================
4416 * \brief Creates 2D and 1D elements on boundaries of new prisms
4418 //================================================================================
4420 bool _ViscousBuilder::addBoundaryElements()
4422 SMESH_MesherHelper helper( *_mesh );
4424 for ( unsigned i = 0; i < _sdVec.size(); ++i )
4426 _SolidData& data = _sdVec[i];
4427 TopTools_IndexedMapOfShape geomEdges;
4428 TopExp::MapShapes( data._solid, TopAbs_EDGE, geomEdges );
4429 for ( int iE = 1; iE <= geomEdges.Extent(); ++iE )
4431 const TopoDS_Edge& E = TopoDS::Edge( geomEdges(iE));
4433 // Get _LayerEdge's based on E
4435 map< double, const SMDS_MeshNode* > u2nodes;
4436 if ( !SMESH_Algo::GetSortedNodesOnEdge( getMeshDS(), E, /*ignoreMedium=*/false, u2nodes))
4439 vector< _LayerEdge* > ledges; ledges.reserve( u2nodes.size() );
4440 TNode2Edge & n2eMap = data._n2eMap;
4441 map< double, const SMDS_MeshNode* >::iterator u2n = u2nodes.begin();
4443 //check if 2D elements are needed on E
4444 TNode2Edge::iterator n2e = n2eMap.find( u2n->second );
4445 if ( n2e == n2eMap.end() ) continue; // no layers on vertex
4446 ledges.push_back( n2e->second );
4448 if (( n2e = n2eMap.find( u2n->second )) == n2eMap.end() )
4449 continue; // no layers on E
4450 ledges.push_back( n2eMap[ u2n->second ]);
4452 const SMDS_MeshNode* tgtN0 = ledges[0]->_nodes.back();
4453 const SMDS_MeshNode* tgtN1 = ledges[1]->_nodes.back();
4454 int nbSharedPyram = 0;
4455 SMDS_ElemIteratorPtr vIt = tgtN0->GetInverseElementIterator(SMDSAbs_Volume);
4456 while ( vIt->more() )
4458 const SMDS_MeshElement* v = vIt->next();
4459 nbSharedPyram += int( v->GetNodeIndex( tgtN1 ) >= 0 );
4461 if ( nbSharedPyram > 1 )
4462 continue; // not free border of the pyramid
4464 if ( getMeshDS()->FindFace( ledges[0]->_nodes[0], ledges[0]->_nodes[1],
4465 ledges[1]->_nodes[0], ledges[1]->_nodes[1]))
4466 continue; // faces already created
4468 for ( ++u2n; u2n != u2nodes.end(); ++u2n )
4469 ledges.push_back( n2eMap[ u2n->second ]);
4471 // Find out orientation and type of face to create
4473 bool reverse = false, isOnFace;
4475 map< TGeomID, TopoDS_Shape >::iterator e2f =
4476 data._shrinkShape2Shape.find( getMeshDS()->ShapeToIndex( E ));
4478 if (( isOnFace = ( e2f != data._shrinkShape2Shape.end() )))
4480 F = e2f->second.Oriented( TopAbs_FORWARD );
4481 reverse = ( helper.GetSubShapeOri( F, E ) == TopAbs_REVERSED );
4482 if ( helper.GetSubShapeOri( data._solid, F ) == TopAbs_REVERSED )
4483 reverse = !reverse, F.Reverse();
4484 if ( helper.IsReversedSubMesh( TopoDS::Face(F) ))
4489 // find FACE with layers sharing E
4490 PShapeIteratorPtr fIt = helper.GetAncestors( E, *_mesh, TopAbs_FACE );
4491 while ( fIt->more() && F.IsNull() )
4493 const TopoDS_Shape* pF = fIt->next();
4494 if ( helper.IsSubShape( *pF, data._solid) &&
4495 !_ignoreShapeIds.count( e2f->first ))
4499 // Find the sub-mesh to add new faces
4500 SMESHDS_SubMesh* sm = 0;
4502 sm = getMeshDS()->MeshElements( F );
4504 sm = data._proxyMesh->getFaceSubM( TopoDS::Face(F), /*create=*/true );
4506 return error("error in addBoundaryElements()", data._index);
4509 const int dj1 = reverse ? 0 : 1;
4510 const int dj2 = reverse ? 1 : 0;
4511 for ( unsigned j = 1; j < ledges.size(); ++j )
4513 vector< const SMDS_MeshNode*>& nn1 = ledges[j-dj1]->_nodes;
4514 vector< const SMDS_MeshNode*>& nn2 = ledges[j-dj2]->_nodes;
4516 for ( size_t z = 1; z < nn1.size(); ++z )
4517 sm->AddElement( getMeshDS()->AddFace( nn1[z-1], nn2[z-1], nn2[z], nn1[z] ));
4519 for ( size_t z = 1; z < nn1.size(); ++z )
4520 sm->AddElement( new SMDS_FaceOfNodes( nn1[z-1], nn2[z-1], nn2[z], nn1[z]));
4524 for ( int isFirst = 0; isFirst < 2; ++isFirst )
4526 _LayerEdge* edge = isFirst ? ledges.front() : ledges.back();
4527 if ( !edge->_sWOL.IsNull() && edge->_sWOL.ShapeType() == TopAbs_EDGE )
4529 vector< const SMDS_MeshNode*>& nn = edge->_nodes;
4530 if ( nn[1]->GetInverseElementIterator( SMDSAbs_Edge )->more() )
4532 helper.SetSubShape( edge->_sWOL );
4533 helper.SetElementsOnShape( true );
4534 for ( size_t z = 1; z < nn.size(); ++z )
4535 helper.AddEdge( nn[z-1], nn[z] );