source: main/branches/3D/openPLM/document3D/STP_converter_JSS.py @ 592

Revision 592, 16.9 KB checked in by agalech, 9 years ago (diff)

add document3d app

Line 
1##Copyright 2008-2011 Thomas Paviot (tpaviot@gmail.com)
2##
3##This file is part of pythonOCC.
4##
5##pythonOCC is free software: you can redistribute it and/or modify
6##it under the terms of the GNU Lesser General Public License as published by
7##the Free Software Foundation, either version 3 of the License, or
8##(at your option) any later version.
9##
10##pythonOCC is distributed in the hope that it will be useful,
11##but WITHOUT ANY WARRANTY; without even the implied warranty of
12##MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13##GNU Lesser General Public License for more details.
14##
15##You should have received a copy of the GNU Lesser General Public License
16##along with pythonOCC.  If not, see <http://www.gnu.org/licenses/>.
17
18
19
20import os.path
21from OCC.TDataStd import *
22from OCC.Utils.Topology import Topo
23from OCC.TopAbs import *
24
25from OCC import XCAFApp, TDocStd, XCAFDoc ,TCollection, Quantity, TopLoc, gp, TPrsStd, XCAFPrs
26from OCC.STEPCAFControl import *
27from OCC.STEPControl import *
28
29from django.core.files.base import File
30
31#from openPLM.document3D.aficher import *
32import StringIO
33#from OCC.Utils.DataExchange.STEP import *
34
35#from OCC.TopoDS import *
36from OCC.BRep import *
37
38
39from OCC.IFSelect import *
40
41
42from OCC.TDF import *
43
44from OCC.TopoDS import *
45
46
47##Puede haver dos root?
48## y si el shapeTOPO no es ABS 1 o 2
49
50
51
52class NEW_STEP_Import(object):
53
54    def __init__(self, filename, layer_name='layer-00'):
55        self.filename = filename
56        self._shapes = [] #an empty string
57        self._arbre_nom= []
58        self._vertices= []
59        self._faces= []
60       
61    def get_shapes(self):
62        return self._shapes 
63    def get_shapes_(self,i):
64        return self._arbre_nom[i] 
65       
66    def read_file(self):     
67        STEPReader = STEPCAFControl_Reader()
68        STEPReader.ReadFile(self.filename) 
69        #STEPReader.ReadFile("/home/linux/openPLM/branches/3D/openPLM/docs/stp/pppp.stp")
70        h_doc = TDocStd.Handle_TDocStd_Document()
71        app = XCAFApp.GetApplication().GetObject()
72        app.NewDocument(TCollection.TCollection_ExtendedString("MDTV-CAF"),h_doc)
73        STEPReader.Transfer(h_doc)
74        doc = h_doc.GetObject()
75        h_shape_tool = XCAFDoc.XCAFDoc_DocumentTool_ShapeTool(doc.Main())
76        l_Labels_root = TDF_LabelSequence()
77        l_LabelShapes = TDF_LabelSequence()
78        l_ComponentShapes = TDF_LabelSequence()
79        l_SubComponent=TDF_LabelSequence()
80        shape_tool = h_shape_tool.GetObject()
81        shape_tool.GetShapes(l_LabelShapes)
82        shape_tool.GetFreeShapes(l_Labels_root)
83       
84        ### Presentation Shapes###
85        print "Shapes in fichier:" 
86        for i in range(l_LabelShapes.Length()):
87            print '\t',Nom_Label_Shape(l_LabelShapes.Value(i+1))
88        ###              ###
89        ### Presentation Components###
90        print "Components:"
91        shape_tool.GetComponents(l_Labels_root.Value(1),l_ComponentShapes) 
92        for i in range(l_ComponentShapes.Length()):
93            print '\t',Nom_Label_Shape(l_ComponentShapes.Value(i+1))
94        ###              ###
95       
96        for i in range(l_Labels_root.Length()):
97            self._shapes.append([])
98            parcours_recursif(l_Labels_root.Value(i+1),self._shapes[i],shape_tool)
99
100           
101           
102        """
103        for i in range(l_Labels_root.Length()):  #pour chaque root         
104            l_ComponentShapes = TDF_LabelSequence()
105            shape_tool.GetComponents(l_Labels_root.Value(i+1),l_ComponentShapes)
106            #print "Root[",Nom_Label_Shape(l_Labels_root.Value(i+1)),"]"
107            if(l_ComponentShapes.Length()>0):
108                for f in range(l_ComponentShapes.Length()): #pour chaque component
109                    #print '\tComposant[',Nom_Label_Shape(l_ComponentShapes.Value(f+1)),']'
110                    compShape=shape_tool.GetShape(l_ComponentShapes.Value(f+1))
111                   
112                    self._arbre_nom.append(Nom_Label_Shape(l_ComponentShapes.Value(f+1)))
113                    if len(self._shapes) <= f:
114                        #self._shapes.append([])
115                        self._shapes[f].append(compShape)
116
117                   
118                   
119                    #t = Topo(compShape)   
120                    #Podemos conseguir piezas mas pequenas pero no sus nombres
121                    #for aux in t.solids(): #entramos q solid para tener mass precision pero no conseguimos los nombres de las partes
122                        #self._shapes[f].append(aux)
123                        #print "no entra aqui"
124                       
125                    #tengo que enviar el compshape
126                     
127            else:
128
129                    compShape=shape_tool.GetShape(l_Labels_root.Value(i+1))
130                    self._shapes.append([])
131                    self._shapes[0].append(compShape)
132
133        """
134        return True             
135                       
136           
137def parcours_recursif(label,shape,shape_tool):
138    l_ComponentShapes = TDF_LabelSequence()           
139    shape_tool.GetComponents(label,l_ComponentShapes)
140    if(l_ComponentShapes.Length()>0):
141       
142        for f in range(l_ComponentShapes.Length()):
143            shape.append([])     
144            parcours_recursif(l_ComponentShapes.Value(f+1),shape[f],shape_tool)     
145    else:
146
147        compShape=shape_tool.GetShape(label)
148        shape.append(compShape)
149   
150           
151def Nom_Label_Shape(lab):
152
153            entry = TCollection.TCollection_AsciiString()
154            TDF_Tool.Entry(lab,entry)
155            N = Handle_TDataStd_Name()
156            lab.FindAttribute(TDataStd_Name_GetID(),N)
157            n=N.GetObject()
158            return n.Get().PrintToString()
159       
160       
161                   
162class NEW_STEPOCAF_Import(object):
163    '''
164    Imports STEP file that support layers & colors
165    '''
166    def __init__(self, filename, layer_name='layer-00'):
167        self.filename = filename
168        self._shapes = [] #an empty string
169        self._components =[]
170   
171    def get_shapes(self):
172        return self._shapes
173        #return self._components
174   
175    def read_file(self):
176   
177        # Create the TDocStd document
178
179       
180       
181           
182        # Create Reader
183       
184   
185        STEPReader = STEPCAFControl_Reader()
186        #STEPReader.SetColorMode(True)
187        #STEPReader.SetLayerMode(True)
188        #STEPReader.SetNameMode(True)
189        #STEPReader.SetMatMode(True)
190        #status = STEPReader.ReadFile(str(self.filename)) 
191        #status = STEPReader.ReadNames("/home/linux/openPLM/trunk/openPLM/docs/stp/d14c00b285ebb58966e0a962400ccb60-j8g.stp")
192       
193       
194        STEPReader.ReadFile("/home/linux/openPLM/trunk/openPLM/docs/stp/d14c00b285ebb58966e0a962400ccb60-tmi.stp")
195       
196       
197        h_doc = TDocStd.Handle_TDocStd_Document()
198
199       
200
201        # Create the application
202       
203        app = XCAFApp.GetApplication().GetObject()
204        app.NewDocument(TCollection.TCollection_ExtendedString("MDTV-CAF"),h_doc)
205       
206       
207        # Transfer
208
209        STEPReader.Transfer(h_doc)
210
211        # Get root assembly
212        doc = h_doc.GetObject()
213       
214       
215       
216        h_shape_tool = XCAFDoc.XCAFDoc_DocumentTool_ShapeTool(doc.Main())
217        l_Colors = XCAFDoc.XCAFDoc_DocumentTool_ColorTool(doc.Main())
218        l_Layers = XCAFDoc.XCAFDoc_DocumentTool_LayerTool(doc.Main())
219        l_materials = XCAFDoc.XCAFDoc_DocumentTool_MaterialTool(doc.Main())
220                    #ShapeSequence = new TopTools_HSequenceOfShape();
221        #STEPReader.Transfer(doc.GetHandle())
222
223        Labels = TDF_LabelSequence()
224        ColorLabels = TDF_LabelSequence()
225        LayersLabel = TDF_LabelSequence()
226        l_LabelShapes = TDF_LabelSequence()
227       
228        shape_tool = h_shape_tool.GetObject()
229        shape_tool.GetFreeShapes(Labels)
230        shape_tool.GetShapes(l_LabelShapes);
231
232       
233        print 'Number of root :%i'%Labels.Length()
234        print 'Number of shapes :%i'%l_LabelShapes.Length() 
235       
236
237       
238        for i in range(l_LabelShapes.Length()):
239            lab=TDF_Label()
240            lab=l_LabelShapes.Value(i+1)
241            entry = TCollection.TCollection_AsciiString()
242            TDF_Tool.Entry(lab,entry)
243
244            N = Handle_TDataStd_Name()
245            lab.FindAttribute(TDataStd_Name_GetID(),N)
246
247            n=N.GetObject()
248            a=n.Get()
249           
250            nuevoShape = shape_tool.GetShape(l_LabelShapes.Value(i+1))       
251            sub_shapes_labels = TDF_LabelSequence()
252            sub_component_labels = TDF_LabelSequence()
253            shape_tool.GetSubShapes(l_LabelShapes.Value(i+1),sub_shapes_labels)
254            shape_tool.GetComponents(l_LabelShapes.Value(i+1),sub_component_labels)
255
256     
257            nuevoshape=shape_tool.GetShape(l_LabelShapes.Value(i+1))
258            #print "Tipo del atributo" ,  nuevoshape.ShapeType()
259            if (nuevoshape.ShapeType() == TopAbs_COMPOUND or nuevoshape.ShapeType() == 2) and i==1: #or i==4 or i==5):
260                print 'Name of atributo del shape ',a.PrintToString()
261                print 'Number of subshapes  in the assemly :%i'%sub_shapes_labels.Length()
262                print 'Number of components in the assemly :%i'%sub_component_labels.Length() 
263               
264               
265                for y in range(sub_component_labels.Length()):
266                    Shape_componente=shape_tool.GetShape(sub_component_labels.Value(y+1))
267                    lab=sub_component_labels.Value(y+1)
268                    entry = TCollection.TCollection_AsciiString()
269                    TDF_Tool.Entry(lab,entry)
270
271                    N = Handle_TDataStd_Name()
272                    lab.FindAttribute(TDataStd_Name_GetID(),N)
273
274                    n=N.GetObject()
275                    a=n.Get()
276                   
277                    print 'Name of component ',a.PrintToString() 
278                   
279                #for t in t.compounds():
280                    #print "Tipo del atributo" ,  shape_tool.GetShape(sub_component_labels.Value(i+1)).ShapeType()
281                    if (Shape_componente.ShapeType()==TopAbs_COMPOUND or Shape_componente.ShapeType()==TopAbs_SOLID):                     
282                        componente = Component_Step(a.PrintToString(),Shape_componente)
283                        self._components.append(componente)  #######AQUI####
284                        t = Topo(Shape_componente)
285 
286
287                        for t in t.solids():
288                            self._shapes.append(t)
289
290       
291        for i in range(Labels.Length()):
292       
293       
294
295            lab=Labels.Value(i+1)
296            entry = TCollection.TCollection_AsciiString()
297            TDF_Tool.Entry(lab,entry)
298
299            N = Handle_TDataStd_Name()
300            lab.FindAttribute(TDataStd_Name_GetID(),N)
301
302            n=N.GetObject()
303            a=n.Get()
304            print 'Name of root ',a.PrintToString()
305           
306
307
308            #print "Is Assembly?",shape_tool.IsAssembly(Labels.Value(i+1))
309           
310            sub_shapes = shape_tool.GetSubShapes(Labels.Value(i+1),sub_shapes_labels)
311            sub_component = shape_tool.GetComponents(Labels.Value(i+1),sub_component_labels)
312
313            #print 'Number of subshapes  in the assemly :%i'%sub_shapes_labels.Length()
314            #print 'Number of components in the assemly :%i'%sub_component_labels.Length()
315
316         
317         
318         
319        l_Colors.GetObject().GetColors(ColorLabels)
320        #print 'Number of colors=%i'%ColorLabels.Length()
321       
322        #if(CL_Len>0):
323        #       ColorTool->GetColor(ColorLabels.Value(1),DefaultColor);
324       
325        #for i in range(sub_component_labels.Length()):
326        """
327        for i in range(Labels.Length()):
328
329            #print i
330            #aShape = shape_tool.GetShape(sub_omponent_labels.Value(i+1))
331            aShape = shape_tool.GetShape(Labels.Value(i+1))
332            #aShape = shape_tool.GetShapes(Labels.Value(i+1))
333            m = l_Layers.GetObject().GetLayers(aShape)
334            #print c
335            #print "Lenght of popo :%i"%m.GetObject().Length()
336            #v = m.GetObject().Value(0)#Value()
337            #print v,v.Length()
338                    #for i in v.Length():
339                    #    print chr(v.Value(i+1))
340            #layer_labels = TDF_LabelSequence()
341            #popo = Handle_TColStd_HSequenceOfExtendedString()
342           
343            #print 'Number of layers :%i'%layer_labels.Length()
344            #print aShape,aShape.ShapeType()
345            if aShape.ShapeType() == TopAbs_COMPOUND:
346                t = Topo(aShape)
347
348                #for t in t.compounds():
349                for t in t.solids():
350                   
351                    self._shapes.append(t)
352     
353     
354        """
355        sub_sub_shapes_labels = TDF_LabelSequence()
356        sub_sub_component_labels = TDF_LabelSequence()
357        sub1 = TDF_LabelSequence()
358        sub2 = TDF_LabelSequence()
359       
360        #print "Llega hasta aqui"
361        """
362        for i in range(sub_component_labels.Length()):
363       
364            lab=sub_component_labels.Value(i+1)
365            entry = TCollection.TCollection_AsciiString()
366            TDF_Tool.Entry(lab,entry)
367
368            N = Handle_TDataStd_Name()
369            lab.FindAttribute(TDataStd_Name_GetID(),N)
370
371            n=N.GetObject()
372            a=n.Get()
373            componente = Component_Step(a.PrintToString(),shape_tool.GetShape(sub_component_labels.Value(i+1)))
374            print 'Name of component ',a.PrintToString() 
375           
376           
377            shape_tool.GetSubShapes(sub_component_labels.Value(i+1),sub_sub_shapes_labels)
378            shape_tool.GetComponents(sub_component_labels.Value(i+1),sub_sub_component_labels)
379
380            #print 'Number of subshapes  in the assemly :%i'%sub_sub_shapes_labels.Length()
381            #print 'Number of components in the assemly :%i'%sub_sub_component_labels.Length()
382     
383            self._components.append(componente)
384        """
385             
386           
387        return True
388       
389       
390       
391class STEP_NEW_Importer(object):
392    def __init__(self,filename=None):       
393        self._shapes = []
394        self._nbs = 0
395        self.set_filename(filename)
396
397    def get_nbr_shapes(self):
398        """ Return the number of shapes from the importer
399        """
400        return self._nbs
401       
402    def set_filename(self, filename):
403        if not os.path.isfile(filename):
404            print "STEPImporter initialization Error: file %s not found."%filename
405            self._filename = None
406        else:
407            self._filename = filename
408       
409    def read_file(self):
410        """
411        Read the STEP file and stores the result in a _shapes list
412        """
413        "entro acocococococo"
414        if not self._filename:
415            print "ReadFile Error: first set the filename."
416            return False
417        aReader = STEPControl_Reader()
418        status = aReader.ReadFile(self._filename)
419        if status==IFSelect_RetDone:
420            failsonly = False
421            aReader.PrintCheckLoad(failsonly, IFSelect_ItemsByEntity)
422            nbr = aReader.NbRootsForTransfer()
423            print "%i root(s)"%nbr
424            aReader.PrintCheckTransfer(failsonly, IFSelect_ItemsByEntity)
425            for n in range(1,nbr+1):
426                ok = aReader.TransferRoot(n)
427                self._nbs = aReader.NbShapes()
428                print "El numero de nbs es" , self._nbs
429                if self._nbs == 0:
430                    print "At least one shape in STEP cannot be transfered"
431                elif (nbr==1 and self._nbs==1):
432                    aResShape = aReader.Shape(1)
433                    if aResShape.IsNull():
434                        print "At least one shape in STEP cannot be transferred"
435                    self._shapes.append(aResShape)
436                else:                   
437                    for i in range(1,self._nbs+1):
438                        aShape = aReader.Shape(i)
439                        if aShape.IsNull():
440                            print "At least one shape in STEP cannot be transferred"
441                        else:
442                            self._shapes.append(aShape)
443                            #B.Add(compound,aShape)
444            return True
445        else:
446            print "Error: can't read file %s"%self._filename
447            return False
448        return False
449
450    def get_compound(self):
451        """ Create and returns a compound from the _shapes list
452        """
453        # Create a compound
454        compound = TopoDS_Compound()
455        B = BRep_Builder()
456        B.MakeCompound(compound)
457        # Populate the compound
458        for shape in self._shapes:
459            B.Add(compound,shape)
460        return compound
461   
462    def get_shapes(self):
463        return self._shapes       
464       
465class Component_Step():
466
467    def __init__(self,name_composant,aShape):
468        self._shapes = []
469        self._name_composant = name_composant
470       
471        #print "el tipo es :", aShape.ShapeType()
472        if aShape.ShapeType() == TopAbs_COMPOUND or aShape.ShapeType() == 2:
473                t = Topo(aShape)
474 
475                #for t in t.compounds():
476                for t in t.solids():
477                    #print "entra el guacamayo"
478                    self._shapes.append(t)
479
480
481
Note: See TracBrowser for help on using the repository browser.