Salome HOME
22491: EDF 2249 SMESH: Integration of a small python library for quadrangle meshing
[modules/smesh.git] / src / Tools / MacMesh / MacMesh / PublishGroups.py
1 # Copyright (C) 2007-2014  CEA/DEN, EDF R&D, OPEN CASCADE
2
3 # Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 # CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5
6 # This library is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU Lesser General Public
8 # License as published by the Free Software Foundation; either
9 # version 2.1 of the License, or (at your option) any later version.
10
11 # This library is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 # Lesser General Public License for more details.
15
16 # You should have received a copy of the GNU Lesser General Public
17 # License along with this library; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19
20 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21
22
23
24 import SMESH
25 import math
26 import Config
27
28 from salome.geom import geomBuilder
29 geompy = geomBuilder.New( Config.theStudy )
30
31 from salome.smesh import smeshBuilder
32 smesh = smeshBuilder.New( Config.theStudy )
33
34 ##########################################################################################################
35
36 def PublishGroups ():
37         aFilterManager = smesh.CreateFilterManager()
38
39         # Building geometric and mesh compounds and  groups ##############################################
40         if Config.debug : print "Searching for geometric groups and publishing final compound"
41         
42         TempGEOList = []
43         TempMESHList = []
44         
45         for MacroObj in Config.ListObj : 
46                 TempGEOList += MacroObj.GeoChildren
47                 TempMESHList += MacroObj.Mesh
48                 
49         FinalCompound = geompy.MakeCompound(TempGEOList)
50         geompy.addToStudy (FinalCompound,Config.StudyName)
51         MeshCompound = smesh.Concatenate(TempMESHList, 1, 1, 1e-5)
52         MeshCompound.SetName(Config.StudyName)
53         
54         GroupGEO = []
55         for group in Config.Groups :
56         
57                 # Geometric groups definition
58                 TempGEOList = []
59                 TempNames = []
60                 for MacroObj in Config.ListObj :
61                         if group in MacroObj.GroupNames :
62                                 Occurences = IndexMultiOcc(MacroObj.GroupNames, group)
63                                 for Occ in Occurences :
64                                         TempGEOList += MacroObj.GetBorder(Occ)
65                 GroupGEO.append(geompy.MakeCompound(TempGEOList))
66                 geompy.addToStudyInFather(FinalCompound,GroupGEO[-1],'GR_'+group)
67                 
68                 # Mesh groups definition
69                 Criterion = smesh.GetCriterion(SMESH.EDGE, SMESH.FT_BelongToGeom,'=',GroupGEO[-1],Tolerance=1e-06)
70                 #Criterion = smesh.Filter.Criterion(18,39,0,'GR_'+group,'GR_'+group,39,39,1e-06,smesh.EDGE,7)
71                 MeshCompound.MakeGroupByCriterion(group,Criterion)
72         
73         StudyBuilder = Config.theStudy.NewBuilder()
74         for MeshObj in TempMESHList:
75                 SO = Config.theStudy.FindObjectIOR(Config.theStudy.ConvertObjectToIOR(MeshObj))
76                 if SO is not None: StudyBuilder.RemoveObjectWithChildren(SO)
77         
78         return MeshCompound        
79                 
80
81 def IndexMultiOcc (Array,Element) :
82         """
83         This function returns the occurrences indices of Element in Array.
84         As opposed to Array.index(Element) method, this allows determining      
85         multiple entries rather than just the first one!
86         """
87         Output = []
88         try : Array.index(Element)
89         except ValueError : print "No more occurrences"
90         else : Output.append(Array.index(Element))
91                 
92         if not(Output == [-1]) and len(Array) > 1 :
93                 for index, ArrElem in enumerate(Array[Output[0]+1:]) :
94                         if ArrElem is Element : Output.append(index+Output[0]+1)
95                  
96         return Output
97             
98 def Publish (ObjToPublish):
99         for i,GeoObj in enumerate(ObjToPublish) : geompy.addToStudy(GeoObj,"Sub_"+str(i))
100         
101 def RevolveMesh(MainMesh,**args):
102         """
103         This function premits to revolute and scale a 2D mesh while transforming the edge
104         groups into face groups. Moreover, the function automatically creates the face groups 
105         corresponding to the symmetry lower and upper faces
106         Facultatif arguments are : 
107                 - Center [X,Y,Z], origin being the default
108                 - Direction [VX,VY,VZ], x-axis being the default
109                 - AngleDeg or AngleRad : ALPHA, 10 degrees being the default
110                 - Scale : BETA, no scaling being default
111         """
112         ################################################################################
113         # Reading input arguments and proceeding to defaults if necessary
114         ################################################################################       
115         if 'Center' in args : CenterCoor = [float(Coor) for Coor in args['Center']]
116         else : 
117                 print "\nThe coordinates of the center of revolution were not given\nThe origin is used by default."
118                 CenterCoor = [0.,0.,0.]
119         
120         if 'Direction' in args : Direction = [float(Dir) for Dir in args['Direction']]
121         else :
122                 print "\nThe axis vector of revolution was not given\nThe x-axis is used by default."
123                 Direction = [1.,0.,0.]
124         
125         if 'AngleDeg' in args : Angle = float(args['AngleDeg'])*math.pi/180.
126         elif 'AngleRad' in args : Angle = float(args['AngleRad'])
127         else :
128                 print "\nThe revolution angle was not given\nAn angle of 10 degrees is used by default."
129                 Angle = 10.*math.pi/180.
130                 
131         if 'Scale' in args : Scale = float(args['Scale'])
132         else : Scale = 1.
133         
134
135         # Creating the lower face group LOFAC
136         LOFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'LOFAC' )
137         LOFAC.AddFrom(MainMesh.GetMesh())
138
139         GR_Names = MainMesh.GetGroupNames()
140         GRs = MainMesh.GetGroups()
141         Rev3DMeshGroups = MainMesh.RotationSweepObject2D( MainMesh, SMESH.AxisStruct( CenterCoor[0], CenterCoor[1], CenterCoor[2], Direction[0], Direction[1], Direction[2] ), Angle, 1, 1e-05 ,True)
142
143         # Adding an EDGE suffix to the edge groups (to be deleted eventually by the user...)
144         for GR in GRs:
145                 CurrentName = GR.GetName()
146                 if CurrentName in GR_Names and not(CurrentName=='LOFAC'):  # Meaning that this is an old edge group
147                         GR.SetName(CurrentName+'_EDGE')
148
149         # Removing the _rotated prefix from the rotated FACE groups
150         for GR in Rev3DMeshGroups:
151                 CurrentName = GR.GetName()
152                 if CurrentName.endswith( "_rotated"):
153                         if CurrentName.startswith( 'LOFAC_' ):
154                                 GR.SetName('VOL')
155                         else:
156                                 GR.SetName(CurrentName[:-8])
157                 elif CurrentName == 'LOFAC_top':
158                         GR.SetName('HIFAC')
159                         #Index = [ GR_Names[i] in CurrentName for i in range(0,len(GR_Names)) ].index(True)
160                         #GR.SetName(GR_Names[Index])
161
162         # Creating the upper face group HIFAC
163         ALLFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'ALLFAC' )
164         ALLFAC.AddFrom(MainMesh.GetMesh())
165
166         #HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Rev3DMeshGroups if not(MeshGroup.GetName()=='VOL') ], 'HIFAC' )
167         #HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Rev3DMeshGroups if ( not(MeshGroup.GetName()=='VOL') and MeshGroup.GetType() == SMESH.FACE )], 'HIFAC' )
168
169         # Scaling down the mesh to meter units
170         if not(Scale==1.):
171                 MeshEditor = MainMesh.GetMeshEditor()
172                 MeshEditor.Scale( MainMesh.GetMesh(), SMESH.PointStruct( 0, 0, 0 ) ,[ Scale, Scale, Scale ], 0 )
173      
174                 
175 def ExtrudeMesh(MainMesh,**args):
176         """
177         This function premits to extrude and scale a 2D mesh while transforming the edge
178         groups into face groups. Moreover, the function automatically creates the face groups 
179         corresponding to the symmetry lower and upper faces
180         Facultatif arguments are : 
181                 - Direction [VX,VY,VZ], z-axis being default
182                 - Distance : D, default is 1
183                 - NSteps : the object will be extruded by NSteps*Distance, default is Nsteps = 1
184                 - Scale : BETA, no scaling being default
185         """
186         ################################################################################
187         # Reading input arguments and proceeding to defaults if necessary
188         ################################################################################              
189         if 'Distance' in args : Distance = float(args['Distance'])
190         else :
191                 print "\nThe extrusion distance was not given\nA default value of 1 is used."
192                 Distance = 1.
193                 
194         if 'Direction' in args : Direction = NormalizeVector([float(Dir) for Dir in args['Direction']],Distance)
195         else :
196                 print "\nThe extrusion vector of revolution was not given\nThe z-axis is used by default."
197                 Direction = NormalizeVector([0.,0.,1.],Distance)
198                                 
199         if 'Scale' in args : Scale = float(args['Scale'])
200         else : Scale = 1.
201         
202         if 'NSteps' in args : NSteps = int(args['NSteps'])
203         else : NSteps = 1
204         
205         # Creating the lower face group LOFAC
206         LOFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'LOFAC' )
207         LOFAC.AddFrom(MainMesh.GetMesh())
208
209         GR_Names = MainMesh.GetGroupNames()
210         GRs = MainMesh.GetGroups()
211         Ext3DMeshGroups = MainMesh.ExtrusionSweepObject2D(MainMesh,SMESH.DirStruct(SMESH.PointStruct(Direction[0],Direction[1],Direction[2])), NSteps, True)
212
213         # Adding an EDGE suffix to the edge groups (to be deleted eventually by the user...)
214         for GR in GRs:
215                 CurrentName = GR.GetName()
216                 if CurrentName in GR_Names and not(CurrentName=='LOFAC'):  # Meaning that this is an old edge group
217                         GR.SetName(CurrentName+'_EDGE')
218
219         # Removing the _extruded suffix from the extruded FACE groups
220         for GR in Ext3DMeshGroups:
221                 CurrentName = GR.GetName()
222                 if CurrentName.endswith( "_extruded"):
223                         if CurrentName.startswith( 'LOFAC_' ):
224                                 GR.SetName('VOL')
225                         else:
226                                 GR.SetName(CurrentName[:-9])
227                 elif CurrentName == 'LOFAC_top':
228                         GR.SetName('HIFAC')
229
230         # Creating the upper face group HIFAC
231         ALLFAC = MainMesh.CreateEmptyGroup( SMESH.FACE, 'ALLFAC' )
232         ALLFAC.AddFrom(MainMesh.GetMesh())
233
234         #HIFAC = MainMesh.GetMesh().CutListOfGroups( [ ALLFAC ], [LOFAC] + [ MeshGroup for MeshGroup in Ext3DMeshGroups if not(MeshGroup.GetName()=='VOL') ], 'HIFAC' )
235
236         # Scaling down the mesh to meter units
237         if not(Scale==1.):
238                 MeshEditor = MainMesh.GetMeshEditor()
239                 MeshEditor.Scale( MainMesh.GetMesh(), SMESH.PointStruct( 0, 0, 0 ) ,[ Scale, Scale, Scale ], 0 )
240      
241                
242 def NormalizeVector (V,Norm):
243         """
244         This function returns a normalized vector (magnitude = Norm), parallel to the entered one
245         """
246         V = [float(Coor) for Coor in V]
247         Norm = float(Norm)
248         MagV = math.sqrt(V[0]*V[0]+V[1]*V[1]+V[2]*V[2])
249         return [Coor*Norm/MagV for Coor in V]
250