]> SALOME platform Git repositories - modules/shaper_study.git/blob - src/PY/SHAPERSTUDY.py
Salome HOME
Do not publish objects having no corresponding shaper object
[modules/shaper_study.git] / src / PY / SHAPERSTUDY.py
1 # Copyright (C) 2007-2019  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 import SHAPERSTUDY_ORB__POA
24 import SHAPERSTUDY_ORB
25 import SALOME_ComponentPy
26 import SALOME_DriverPy
27 import SALOMEDS
28 from SHAPERSTUDY_utils import findOrCreateComponent, moduleName, getStudy, getORB
29 import salome
30 import SHAPERSTUDY_Object
31 import SHAPERSTUDY_IOperations
32 import GEOM
33 import SMESH
34
35 __entry2IOR__ = {}
36
37
38 class SHAPERSTUDY(SHAPERSTUDY_ORB__POA.Gen,
39                   SALOME_ComponentPy.SALOME_ComponentPy_i,
40                   SALOME_DriverPy.SALOME_DriverPy_i):
41
42
43     ShapeType = {"AUTO":-1, "COMPOUND":0, "COMPSOLID":1, "SOLID":2, "SHELL":3, "FACE":4, "WIRE":5, "EDGE":6, "VERTEX":7, "SHAPE":8, "FLAT":9}
44     
45     ShaperIcons = {GEOM.COMPOUND:"SHAPER_ICON_COMPSOLID",
46         GEOM.COMPSOLID:"SHAPER_ICON_COMPSOLID",
47         GEOM.SOLID:"SHAPER_ICON_SOLID",
48         GEOM.SHELL:"SHAPER_ICON_SHELL",
49         GEOM.FACE:"SHAPER_ICON_FACE",
50         GEOM.WIRE:"SHAPER_ICON_WIRE",
51         GEOM.EDGE:"SHAPER_ICON_EDGE",
52         GEOM.VERTEX:"SHAPER_ICON_VERTEX",
53         GEOM.SHAPE:"SHAPER_ICON_SOLID",
54         GEOM.FLAT:"SHAPER_ICON_FACE"
55         }
56
57     def __init__ ( self, orb, poa, contID, containerName, instanceName, interfaceName ):
58         """
59         Construct an instance of SHAPERSTUDY module engine.
60         The class SHAPERSTUDY implements CORBA interface Gen (see SHAPERSTUDY_Gen.idl).
61         It is inherited (via GEOM_Gen) from the classes SALOME_ComponentPy_i (implementation of
62         Engines::EngineComponent CORBA interface - SALOME component) and SALOME_DriverPy_i
63         (implementation of SALOMEDS::Driver CORBA interface - SALOME module's engine).
64         """
65         SALOME_ComponentPy.SALOME_ComponentPy_i.__init__(self, orb, poa,
66                     contID, containerName, instanceName, interfaceName, False)
67         SALOME_DriverPy.SALOME_DriverPy_i.__init__(self, interfaceName)
68         #
69         #self._naming_service = SALOME_ComponentPy.SALOME_NamingServicePy_i( self._orb )
70         #
71         pass
72
73     def FindOrCreateShape( self, theInternalEntry ):
74         """
75         Searches existing or creates a new SHAPERSTUDY_Object to interact with SHAPER
76         """
77         # Searching in the study tree
78         aComponent = findOrCreateComponent()
79         aSOIter = getStudy().NewChildIterator(aComponent)
80         while aSOIter.More():
81           aSO = aSOIter.Value()
82           anIOR = aSO.GetIOR()
83           anObj = salome.orb.string_to_object(anIOR)
84           if isinstance(anObj, SHAPERSTUDY_ORB._objref_SHAPER_Object):
85             if anObj.GetEntry() == theInternalEntry:
86               return anObj
87           aSOIter.Next()
88
89         aShapeObj = SHAPERSTUDY_Object.SHAPERSTUDY_Object()
90         aShapeObj.SetEntry(theInternalEntry)
91         return aShapeObj._this()
92
93     def AddInStudy( self, theObject, theName, theFather ):
94         """
95         Adds in theStudy a object theObject under theFather with a name theName,
96         if theFather is not NULL the object is placed under theFather's SObject.
97         Returns a SObject where theObject is placed
98         """
99         if not theObject.GetEntry():
100             return None # object not existing in shaper
101         aStudy = getStudy()
102         aBuilder = aStudy.NewBuilder()
103         isGroup = theObject.GetType() == 37 or theObject.GetType() == 52
104         if not theFather:
105           if isGroup:
106             return None # Group may be added only under the shape-father
107           theFatherSO = findOrCreateComponent()
108         else:
109           theFatherSO = theFather.GetSO()
110         aResultSO = None
111         if isGroup: # add group to the third sub-label or later to keep space for reference and "History"
112           aTag = 3
113           anIter = aStudy.NewChildIterator(theFatherSO)
114           while anIter.More():
115             aCurrentTag = anIter.Value().Tag() + 1
116             if aTag < aCurrentTag:
117               aTag = aCurrentTag
118             anIter.Next()
119           aResultSO = aBuilder.NewObjectToTag(theFatherSO, aTag)
120         else:
121           aResultSO = aBuilder.NewObject(theFatherSO);
122         aResultSO.SetAttrString("AttributeName", theName)
123         if theObject is not None:
124             anIOR = salome.orb.object_to_string(theObject)
125             aResultSO.SetAttrString("AttributeIOR", anIOR)
126             theObject.SetSO(aResultSO)
127           
128             aAttr = aBuilder.FindOrCreateAttribute(aResultSO, "AttributePixMap")
129             aPixmap = aAttr._narrow(salome.SALOMEDS.AttributePixMap)
130             aType = 0
131             if isGroup:
132               aType = SHAPERSTUDY_Object.__shape_types__[theObject.GetSelectionType()]
133             else:
134               aType = theObject.GetShapeType()
135             aPixmap.SetPixMap(self.ShaperIcons[aType])
136             
137         # add a red-reference that means that this is an active reference to SHAPER result
138         if not isGroup:
139           aSub = aBuilder.NewObjectToTag(aResultSO, 1)
140           aBuilder.Addreference(aSub, aResultSO)
141
142         return aResultSO
143
144     def AddSubShape( theMainShape, theIndices ):
145         """
146         Add a sub-shape defined by indices in theIndices
147         (contains unique IDs of sub-shapes inside theMainShape)
148         """
149         # no sub-shapes for the moment
150         go = SHAPERSTUDY_Object()._this()
151         return go
152
153     # For now it is impossible to remove anything from the SHAPER-STUDY
154     def RemoveObject( self, theObject ):
155         """
156         Removes the object from the component
157         """
158         # can not be removed for the moment
159         return
160
161     def GetIFieldOperations( self ):
162         """
163         """
164         return SHAPERSTUDY_IOperations.SHAPERSTUDY_IFieldOperations()._this()
165
166     def GetIGroupOperations( self ):
167         """
168         """
169         return SHAPERSTUDY_IOperations.SHAPERSTUDY_IGroupOperations()._this()
170
171     def GetIShapesOperations( self ):
172         """
173         """
174         return SHAPERSTUDY_IOperations.SHAPERSTUDY_IShapesOperations()._this()
175
176     def GetIMeasureOperations( self ):
177         """
178         """
179         return SHAPERSTUDY_IOperations.SHAPERSTUDY_IMeasureOperations()._this()
180
181     def GetStringFromIOR( self, theObject ):
182         """
183         Returns a string which contains an IOR of the SHAPERSTUDY_Object
184         """
185         IOR = ""
186         if theObject and getORB():
187             IOR = getORB().object_to_string( theObject )
188             pass
189         return IOR
190
191     def GetAllDumpNames( self ):
192         """
193         Returns all names with which Object's was dumped
194         into python script to avoid the same names in SMESH script
195         """
196         return []
197
198     def GetDumpName( self, theStudyEntry ):
199         """
200         Returns a name with which a GEOM_Object was dumped into python script
201
202         Parameters:
203             theStudyEntry is an entry of the Object in the study
204         """
205         return "test"
206
207     def Save( self, component, URL, isMultiFile ):
208         """
209         Saves data: all objects into one file
210         """
211         aResult = "" # string-pairs of internal entries and shape streams
212         aStudy = getStudy()
213         # get all sub-SObjects with IOR defined
214         anIters = [aStudy.NewChildIterator(findOrCreateComponent())]
215         aSOList = []
216         while len(anIters):
217           aLast = anIters[len(anIters) - 1]
218           if aLast.More():
219             aSO = aLast.Value()
220             anIOR = aSO.GetIOR()
221             if len(anIOR):
222               aSOList.append(aSO)
223             anIters.append(aStudy.NewChildIterator(aSO))
224             aLast.Next()
225           else:
226             anIters.remove(aLast)
227
228         for aSO in aSOList: # for each sobject export shapes stream if exists
229           anIOR = aSO.GetIOR()
230           if not len(anIOR):
231             continue
232           anObj = salome.orb.string_to_object(anIOR)
233           if type(anObj) == SHAPERSTUDY_ORB._objref_SHAPER_Group:
234             if len(aResult):
235               aResult = aResult + '|'
236             # store internal entry, type and list of indices of the group selection (separated by spaces)
237             aResult = aResult + anObj.GetEntry() + "|" + str(anObj.GetSelectionType())
238             aSelList = anObj.GetSelection()
239             aResult = aResult + "|" + str(' '.join(str(anI) for anI in aSelList))
240           elif type(anObj) == SHAPERSTUDY_ORB._objref_SHAPER_Field:
241             if len(aResult):
242               aResult = aResult + '|'
243             # same as for group, but in addition to the second string part - field specifics
244             aResult = aResult + anObj.GetEntry() + "|" + str(anObj.GetSelectionType())
245             aResult = aResult + " " + str(anObj.GetDataType()) # values type
246             aSteps = anObj.GetSteps()
247             aResult = aResult + " " + str(len(aSteps)) # number of steps
248             aComps = anObj.GetComponents()
249             aResult = aResult + " " + str(len(aComps)) # number of components
250             for aComp in aComps: # components strings: but before remove spaces and '|'
251               aCoded = aComp.replace(" ", "__space__").replace("|", "__vertical_bar__")
252               aResult = aResult + " " + aCoded
253             for aStepNum in range(len(aSteps)):
254               aVals = anObj.GetStep(aStepNum + 1).GetValues()
255               if aStepNum == 0:
256                 aResult = aResult + " " + str(len(aVals)) # first the number of values in the step
257               aResult = aResult + " " + str(anObj.GetStep(aStepNum + 1).GetStamp()) # ID of stamp in step
258               for aVal in aVals:
259                 aResult = aResult + " " + str(aVal) # all values of step
260             aSelList = anObj.GetSelection()
261             aResult = aResult + "|" + str(' '.join(str(anI) for anI in aSelList))
262           elif isinstance(anObj, SHAPERSTUDY_ORB._objref_SHAPER_Object):
263             if len(aResult):
264               aResult = aResult + '|'
265             # store internal entry, current and old shapes in BRep format
266             aResult = aResult + anObj.GetEntry() + "|" + anObj.GetShapeStream().decode()
267             aResult = aResult + "|" + anObj.GetOldShapeStream().decode()
268
269         return aResult.encode()
270
271     def Load( self, component, stream, URL, isMultiFile ):
272         """
273         Loads data
274         """
275         global __entry2IOR__
276         __entry2IOR__.clear()
277         aList=stream.decode().split('|')
278         aSubNum = 1
279         anId = ""
280         aNewShapeStream = ""
281         for aSub in aList:
282           if aSubNum == 1:
283             anId = aSub
284             aSubNum = 2
285           elif aSubNum == 2:
286             aNewShapeStream = aSub
287             aSubNum = 3
288           else: # create objects by 3 arguments
289             anObj = None
290             if anId.startswith('group') or (anId.startswith('dead') and anId.count("group") > 0): # group object
291               anObj = SHAPERSTUDY_Object.SHAPERSTUDY_Group()
292               if len(aSub):
293                 anObj.SetSelection([int(anI) for anI in aSub.split(' ')])
294               anObj.SetSelectionType(int(aNewShapeStream))
295             elif anId.startswith('field') or (anId.startswith('dead') and anId.count("field") > 0): # field object
296               anObj = SHAPERSTUDY_Object.SHAPERSTUDY_Field()
297               if len(aSub):
298                 anObj.SetSelection([int(anI) for anI in aSub.split(' ')])
299               aParams = aNewShapeStream.split(" ")
300               anObj.SetSelectionType(int(aParams[0]))
301               aTypeStr = aParams[1]
302               if (aTypeStr == "FDT_Bool"):
303                 anObj.SetValuesType(0)
304               elif (aTypeStr == "FDT_Int"):
305                 anObj.SetValuesType(1)
306               elif (aTypeStr == "FDT_Double"):
307                 anObj.SetValuesType(2)
308               elif (aTypeStr == "FDT_String"):
309                 anObj.SetValuesType(3)
310               aSteps = []
311               aNumSteps = int(aParams[2])
312               for aVal in range(aNumSteps):
313                 aSteps.append(aVal + 1)
314               anObj.SetSteps(aSteps)
315               aCompNum = int(aParams[3])
316               aCompNames = []
317               for aCompNameIndex in range(aCompNum):
318                 aCompName = aParams[4 + aCompNameIndex].replace("__space__", " ").replace("__vertical_bar__", "|")
319                 aCompNames.append(aCompName)
320               anObj.SetComponents(aCompNames)
321               aNumValsInStep = int(aParams[4 + aCompNum])
322               for aStepNum in range(aNumSteps):
323                 aStepStartIndex = 4 + aCompNum + aStepNum * (aNumValsInStep + 1) + 1
324                 aStampId = int(aParams[aStepStartIndex])
325                 aVals = []
326                 for aValIndex in range(aNumValsInStep):
327                   aVals.append(float(aParams[aStepStartIndex + aValIndex + 1]))
328                 anObj.AddFieldStep(aStampId, aStepNum + 1, aVals)
329             else: # shape object by BRep in the stream: set old first then new
330               anObj = SHAPERSTUDY_Object.SHAPERSTUDY_Object()
331               if len(aSub):
332                 anObj.SetShapeByStream(aSub)
333               anObj.SetShapeByStream(aNewShapeStream)
334             if anObj:
335               anObj.SetEntry(anId)
336               anIOR = salome.orb.object_to_string(anObj._this())
337               __entry2IOR__[anId] = anIOR
338             aSubNum = 1
339         return 1
340         
341     def IORToLocalPersistentID(self, sobject, IOR, isMultiFile, isASCII):
342         """
343         Gets persistent ID for the CORBA object.
344         The internal entry of the Object is returned.
345         """
346         anObj = salome.orb.string_to_object(IOR)
347         if anObj and (isinstance(anObj, SHAPERSTUDY_ORB._objref_SHAPER_Object) or \
348                       isinstance(anObj, SHAPERSTUDY_ORB._objref_SHAPER_Field)):
349           return anObj.GetEntry()
350         return ""
351
352     def LocalPersistentIDToIOR(self, sobject, persistentID, isMultiFile, isASCII):
353         "Converts persistent ID of the object to its IOR."
354         global __entry2IOR__
355         if persistentID in __entry2IOR__:
356           aRes = __entry2IOR__[persistentID]
357           if len(aRes): # set SO from the study, the sobject param is temporary, don't store it
358             salome.orb.string_to_object(aRes).SetSO(getStudy().FindObjectID(sobject.GetID()))
359           return aRes
360         return ""
361
362     def DumpPython( self, isPublished, isMultiFile ):
363         """
364         Dump module data to the Python script.
365         """
366         return ("# SHAPER STUDY DUMP".encode(), 1)
367
368
369     def IsFather(theFather, theChild):
370         """
371         Returns true if theChild SObject is a child of theFather SObject
372         """
373         aChild = theChild.GetFather()
374         while aChild.Depth() > theFather.Depth():
375           aChild = aChild.GetFather()
376         return aChild.GetID() == theFather.GetID()
377
378     def BreakLink(self, theEntry):
379         """
380         Breaks links to not-dead shape, make the shape as dead
381         """
382         aStudy = getStudy()
383         aSO = aStudy.FindObjectID(theEntry)
384         if not aSO:
385           return
386         aRes, aSSO = aSO.ReferencedObject()
387         if not aRes:
388           return # only SObjects referenced to the SHAPEr STUDY objects are allowed
389         anIOR = aSSO.GetIOR()
390         if not anIOR:
391           return # must be referenced to the SHAPER STUDY shape
392         anObj = salome.orb.string_to_object(anIOR)
393         if not anObj or not isinstance(anObj, SHAPERSTUDY_ORB._objref_SHAPER_Object):
394           return
395         if anObj.IsDead():
396           return # do nothing for reference to already dead shape
397         aDeadShape = anObj.MakeDead()
398         
399         aMeshSObject = aSO.GetFather()
400         aMeshObject = aMeshSObject.GetObject()
401
402         aBuilder = aStudy.NewBuilder()
403         aBuilder.RemoveReference(aSO) # reset reference to the dead shape
404         aBuilder.Addreference(aSO, aDeadShape.GetSO())
405
406         # check also sub-structure of the mesh to find references to sub-objects that become dead
407         aRoot = aSO.GetFather()
408         anIters = [aStudy.NewChildIterator(aRoot)]
409         aSubList = []
410         while len(anIters):
411           aLast = anIters[len(anIters) - 1]
412           if aLast.More():
413             aSub = aLast.Value()
414             aRes, aSubRef = aSub.ReferencedObject()
415             if aRes and SHAPERSTUDY.IsFather(aSSO, aSubRef):
416               aReferenced = aSubRef.GetObject()
417               if aReferenced and not aReferenced.IsDead():
418                 aSubList.append(aSub)
419             anIters.append(aStudy.NewChildIterator(aSub))
420             aLast.Next()
421           else:
422             anIters.remove(aLast)
423         if len(aSubList):
424           # associate the number of sub-objects of the referenced objects
425           aMapSubEntryToIndex = {}
426           aSSOIter = aStudy.NewChildIterator(aSSO)
427           anIndex = 1
428           while aSSOIter.More():
429             aSub = aSSOIter.Value()
430             if aSub.GetIOR():
431               aMapSubEntryToIndex[aSub.GetID()] = anIndex
432               anIndex = anIndex + 1
433             aSSOIter.Next()
434           for aSubSO in aSubList:
435             aRes, aSubRef = aSubSO.ReferencedObject()
436             if aRes and aSubRef.GetID() in aMapSubEntryToIndex:
437               anIndex = aMapSubEntryToIndex[aSubRef.GetID()]
438               aDeadIter = aStudy.NewChildIterator(aDeadShape.GetSO())
439               while aDeadIter.More(): # iterate dead subs to find object with the same index
440                 aDeadSubSO = aDeadIter.Value()
441                 if aDeadSubSO.GetIOR():
442                   anIndex = anIndex - 1
443                   if anIndex == 0:
444                     # for a submesh there is no ReplaceShape, but the shape is not updated
445                     # anyway, so no need to update it here
446                     #aSubMeshSO = aSubSO.GetFather() # Replace shape object in the parent mesh
447                     #aSubMeshObject = aSubMeshSO.GetObject()
448                     #if aSubMeshObject:
449                     #  aSubMeshObject.ReplaceShape(aDeadSubSO.GetObject())
450                     aBuilder.RemoveReference(aSubSO) # reset reference to the dead shape
451                     aBuilder.Addreference(aSubSO, aDeadSubSO)
452                 aDeadIter.Next()
453
454         # Replace shape object in the parent mesh
455         aMeshObject.ReplaceShape(aDeadShape)
456