def SetObject( Name="Object0", Viewport=0, LocRotSca=[], Sub_Name='', ParentName='' ): global ActiveScene,ActiveObject,ObjectSceneID,DLRS ObjectLib=VIEWER.Libs[3] #Verify Data: (use Defaults if neccesary) N = (ObjectLib[Name][0] if (type(Name)==int and Name>-1 and Name<(len(ObjectLib)+1) #get the name of the specified object ) else (Name if type(Name)==str else "Object"+str(len(ObjectLib)))) #N must be a string VP = (Viewport if (Viewport>0 and Viewport<25) else 1) #must be 1 to 24 LRS= (DLRS if len(LocRotSca)!=9 else LocRotSca) #TODO: advanced LRS verification SD = ["",(N if (Sub_Name=='' or type(Sub_Name)!=str) else Sub_Name),[],[]] P = (__GetOID(ParentName) if ParentName!=('__REMOVE__' or '') else ParentName) OID=__GetOID(N) if len(VIEWER.Libs[3])>0 else '' #try to get an active object index if OID=='': #if this is a new object: VIEWER.Libs[3].append([N,VP,LRS,SD,(P if len(VIEWER.Libs[3])>0 else '')]) #ignore parent index if this is the first object VIEWER.Libs[2][ActiveScene][1]+=[len(VIEWER.Libs[3])-1] ObjectSceneID+=[ActiveScene] ActiveObject=len(VIEWER.Libs[3])-1 __LOG('---FORMAT---: created Object: %s'%Name) else: #set the active object to the specicified object and change it's data ActiveObject,ActiveScene = OID,ObjectSceneID[OID]; AO=ObjectLib[OID] VIEWER.Libs[3][OID]=[ AO[0], #reset the object's data: ((VP if Viewport!=0 else AO[1]) if AO[1]!=VP else AO[1]), ((LRS if LRS!=DLRS else AO[2]) if AO[2]!=LRS else AO[2]), [AO[3][0],(AO[3][1] if Sub_Name=='' else SD[1]),AO[3][2],AO[3][3]], #reset sub data name (not data) ((P if ObjectLib[OID][4]!=P else ObjectLib[OID][4]) if P!='__REMOVE__' else '')] __LOG('---FORMAT---: re-set Object: %s'%VIEWER.Libs[3][OID][0]) SetObject.func_defaults=( "Object"+str(len(VIEWER.Libs[3])), 0, [], '', '' )
def SetFacepoint( Vert='', Normal='', Color='', UV='' ): global ActiveObject #verify we havn't switched objects to an invalid type before trying to add facepoints: if VIEWER.Libs[3][ActiveObject][3][0]=="_Mesh": #we can only set the facepoints of an active mesh object if len(VIEWER.Libs[3][ActiveObject][3][3])>0: #we can't append facepoints to an object with no primitives. Colors,UVs = VIEWER.Libs[3][ActiveObject][3][3][2],VIEWER.Libs[3][ActiveObject][3][3][3] VID = __Index(Vert,VIEWER.Libs[3][ActiveObject][3][3][0],'Vert') NID = __Index(Normal,VIEWER.Libs[3][ActiveObject][3][3][1],'Nornal') CIDs = ( (__Index(Color[0],Colors[0],'Color0') ,(__Index(Color[1],Colors[1],'Color1') if len(Color)==2 else '') ) if type(Color)==tuple else (__Index(Color,Colors[0]),'') ) UVIDs = ( (__Index(UV[0],UVs[0],'UV0') ,(__Index(UV[1],UVs[1],'UV1') if len(UV)>=2 else '') ,(__Index(UV[2],UVs[2],'UV2') if len(UV)>=3 else '') ,(__Index(UV[3],UVs[3],'UV3') if len(UV)>=4 else '') ,(__Index(UV[4],UVs[4],'UV4') if len(UV)>=5 else '') ,(__Index(UV[5],UVs[5],'UV5') if len(UV)>=6 else '') ,(__Index(UV[6],UVs[6],'UV6') if len(UV)>=7 else '') ,(__Index(UV[7],UVs[7],'UV7') if len(UV)==8 else '') ) if type(UV)==tuple else (__Index(UV,UVs[0]),'','','','','','','') ) VIEWER.Libs[3][ActiveObject][3][3][5][-1][1]+=[[VID,NID,CIDs,UVIDs]] __LOG('---FORMAT---: set Facepoint: [%s, %s, %s, %s]'%(str(VID),str(NID),str(CIDs),str(UVIDs))) else: print 'unable to append to a non-existant primitive' else: print 'Unable to append Facepoint to Object of type: "'+VIEWER.Libs[3][OID][3][0].split('_')[1]+'"' print 'Make sure the active object is a Mesh-type Object before trying to append Facepoints'
def SetMatColors( Ambient = None, Diffuse = None, Specular = None, Emmisive = None, Shine = None ): global ActiveMaterial r = 1.0/255 if len(VIEWER.Libs[4])>0: try: AR,AG,AB,AA = Ambient if type(AR) == int: AR,AG,AB,AA = AR*r,AG*r,AB*r,AA*r except: AR,AG,AB,AA = VIEWER.Libs[4][ActiveMaterial][2][0] try: DR,DG,DB,DA = Diffuse if type(DR) == int: DR,DG,DB,DA = DR*r,DG*r,DB*r,DA*r except: DR,DG,DB,DA = VIEWER.Libs[4][ActiveMaterial][2][1] try: SR,SG,SB,SA = Specular if type(SR) == int: SR,SG,SB,SA = SR*r,SG*r,SB*r,SA*r except: SR,SG,SB,SA = VIEWER.Libs[4][ActiveMaterial][2][2] try: ER,EG,EB,EA = Emmisive if type(ER) == int: ER,EG,EB,EA = ER*r,EG*r,EB*r,EA*r except: ER,EG,EB,EA = VIEWER.Libs[4][ActiveMaterial][2][3] if Shine==None: Shine=VIEWER.Libs[4][ActiveMaterial][2][4] VIEWER.Libs[4][ActiveMaterial][2] = [[AR,AG,AB,AA],[DR,DG,DB,DA],[SR,SG,SB,SA],[ER,EG,EB,EA],Shine] __LOG('---FORMAT---: set Material colors to: %s'%str(VIEWER.Libs[4][ActiveMaterial][2]))
def __Index(value,List,Type=''): #returns either a valid index or '' if type(value)==tuple: value=list(value) if type(value)==list: #[X,Y(,Z)] or [I/R(,A/G(,B(,A)))] try: return List.index(value) except: List+=[value] __LOG('---FORMAT---: set %s: %s'%(Type,str(value))) return List.index(value) #vector or color elif type(value)==int: return value #index (doesn't validate against len(list)) elif type(value)==str: return '' #no vector (validate any string to '')
def Skip(length, label=''): #TODO: length must be a positive int global __f,__o,__c if __o[__c]==len(__f[__c])-1: #are we at the end? if __TOGGLE_LOGGING: __LOG('%s: wrote %i pad bytes%s'%(__POS(),length,label)) __f[__c]+=__arr('B',[0]*length); __o[__c]+=length else: if __TOGGLE_LOGGING: __LOG('%s: skipped %i bytes%s'%(__POS(),length,label)) v = __f[__c][__o[__c]:__o[__c]+length]; __o[__c]+=length return v
def SetColors( List0=[], List1=[] ): global ActiveObject if len(VIEWER.Libs[3])>0: if VIEWER.Libs[3][ActiveObject][3][0]=="": VIEWER.Libs[3][ActiveObject][3][0]="_Mesh" VIEWER.Libs[3][ActiveObject][3][3]=[[],[],[List0,List1],[[],[],[],[],[],[],[],[]],[],[]] __LOG('---FORMAT---: set Color Lists with [%i,%i] colors'%(len(List0),len(List1))) elif VIEWER.Libs[3][ActiveObject][3][0]=="_Mesh": VIEWER.Libs[3][ActiveObject][3][3][2]=[List0,List1] __LOG('---FORMAT---: set Color Lists with [%i,%i] colors'%(len(List0),len(List1))) else: print 'Unable to append Color Lists to Object of type: "'+VIEWER.Libs[3][OID][3][0].split('_')[1]+'"\nignoring current data' else: print 'please define an object'
def SetNormals( List=[] ): global ActiveObject if len(VIEWER.Libs[3])>0: if VIEWER.Libs[3][ActiveObject][3][0]=="": VIEWER.Libs[3][ActiveObject][3][0]="_Mesh" VIEWER.Libs[3][ActiveObject][3][3]=[[],List,[[],[]],[[],[],[],[],[],[],[],[]],[],[]] __LOG('---FORMAT---: set Normal List with %i normals'%len(List)) elif VIEWER.Libs[3][ActiveObject][3][0]=="_Mesh": VIEWER.Libs[3][ActiveObject][3][3][1]=List __LOG('---FORMAT---: set Normal List with %i normals'%len(List)) else: print 'Unable to append Normal List to Object of type: "'+VIEWER.Libs[3][OID][3][0].split('_')[1]+'"\nignoring current data' else: print 'please define an object'
def Matrix(Rows,Cols,Term,List='',flatten=False,label=''): if List == '': if __TOGGLE_LOGGING: __LOG('%s: reading %ix%i matrix%s'%(__POS(),Rows,Cols,label)) return list([[__Term(Term,'',label=' -- [%i][%i]'%(r,c)) for c in range(Cols)] for r in range(Rows)] if not flatten else [ __Term(Term,'',label=' -- [%i]'%i) for i in range(Cols*Rows)]) if type(List)==list: if len(List)==Rows: #2D list for col in List: for Value in col: __Term(Term,Value) elif len(List)==(Cols*Rows): #1D list for Value in List: __Term(Term,Value) else: pass
def SetImage(Name="Image0",Width=0,Height=0,Data=[]): global ActiveTexture,ActiveImage resolved = 0 IID = __GetIID(Name) if IID!='': ActiveImage = IID __LOG('---FORMAT---: set Active Image to: %s'%VIEWER.Libs[7][IID][0]) else: #NOTE: Pallet not supported yet (last index) if type(Data) == list: VIEWER.Libs[7] += [[Name,Width,Height,Data,[]]] else: VIEWER.Libs[7] += [[Name,1,1,[[255,255,255,255]],[]]] ActiveImage = len(VIEWER.Libs[7])-1 __LOG('---FORMAT---: created Image: %s'%Name) if type(Data) == str: #image directory it = Data.split('.')[-1] #get the file type current,offset = COMMON.__c,COMMON.__o try: import sys __LOG('---FORMAT---: loading image data from %s'%Data) COMMON.ImportFile(Data,1) W,H,img,plt = sys.modules[COMMON._ImgScripts[it]].ImportImage(it) VIEWER.Libs[7][ActiveImage][1] = W VIEWER.Libs[7][ActiveImage][2] = H VIEWER.Libs[7][ActiveImage][3] = img VIEWER.Libs[7][ActiveImage][4] = plt del W; del H; del img; del plt #cleanup #resolved = 1 except: __LOG('---FORMAT---: encountered an error trying to read from the image.') import sys,traceback typ,val,tb=sys.exc_info()#;tb=traceback.extract_tb(i[2])[0] print traceback.print_exception( typ,val,tb#, #limit=2, #file=sys.stdout ) print COMMON.__c,COMMON.__o = current,offset if ActiveTexture!=None and not resolved: VIEWER.Libs[6][ActiveTexture][4] = Name __LOG('---FORMAT---: added Image to Texture: %s'%VIEWER.Libs[6][ActiveTexture][0]) SetImage.func_defaults=( "Image"+str(len(VIEWER.Libs[7])), )
def SetUVs( List0=[], List1=[], List2=[], List3=[], List4=[], List5=[], List6=[], List7=[] ): global ActiveObject if len(VIEWER.Libs[3])>0: if VIEWER.Libs[3][ActiveObject][3][0]=="": VIEWER.Libs[3][ActiveObject][3][0]="_Mesh" VIEWER.Libs[3][ActiveObject][3][3]=[[],[],[[],[]],[List0,List1,List2,List3,List4,List5,List6,List7],[],[]] __LOG('---FORMAT---: set UV Lists with [%i,%i,%i,%i,%i,%i,%i,%i] UVs'%( len(List0),len(List1),len(List2),len(List3),len(List4),len(List5),len(List6),len(List7))) elif VIEWER.Libs[3][ActiveObject][3][0]=="_Mesh": VIEWER.Libs[3][ActiveObject][3][3][0]=[List0,List1,List2,List3,List4,List5,List6,List7] __LOG('---FORMAT---: set UV Lists with [%i,%i,%i,%i,%i,%i,%i,%i] UVs'%( len(List0),len(List1),len(List2),len(List3),len(List4),len(List5),len(List6),len(List7))) else: print 'Unable to append UV Lists to Object of type: "'+VIEWER.Libs[3][OID][3][0].split('_')[1]+'"\nignoring current data' else: print 'please define an object'
def Decompress(Data,Method): global __Scripts,__f,__d,__o,__n,__c; position=len(__n)-1 existant=0 for Mod,D in __Scripts[3][0]: if D[1]==Method: #all we need is the method existant=1 if type(Data)==str: fD,l = sys.modules[Mod].Decompress(Data) return fD,l else: p=__POS() #get file position CDATA=__f[__c][__o[__c]:__o[__c]+Data] fD,l = sys.modules[Mod].Decompress(''.join([chr(c) for c in CDATA])) #__o[__c]+=l if __TOGGLE_LOGGING: __LOG('%s: decompressed %i bytes using %s decompression.'%(p,l,Method)) return fD,l if not existant: print 'ERROR: Compression method "%s" not found'%Method if __TOGGLE_LOGGING: __LOG('\nERROR: Compression method "%s" not found'%Method) __LOG("Check your scripts to make sure you have the required method\n") __LOG("Or check the console to make sure the script isn't flawed.\n") raise ImportError #cancel the import/export operation
def ExportFile(Name): #creates a file data space to be filled global __f,__d,__o,__n,__c D=(__d[__n[0]] if len(__n) else '') #the first file is specified by the Tkinter saveas dialog, #and will always have a directory __c=Name.split('/')[-1] __f[__c] = [] __d[__c] = '%s%s'%(D,Name.replace(__c,'')) __o[__c] = 0 __n+=[__c] #keep the index for switching files by index __LOG("\n-- created export file: '%s' --\n"%Name)
def TempFile(Name): #creates a file data space to be filled global __f,__d,__o,__n,__c D=(__d[__n[0]] if len(__n) else '') #the first file is specified by the Tkinter saveas dialog, #and will always have a directory __c=Name __f[__c] = [] __d[__c] = '' __o[__c] = 0 __n+=[__c] #keep the index for switching files by index __LOG("\n-- created temporary file: '%s' --\n"%Name)
def Set(): global ActiveObject,N,VP,LRS,BM,PA,PR,BoneLib #manage the bone data: BID= __GetBID(N) if len(BoneLib)>0 else '' #try to get an active object index if BID=='': VIEWER.Libs[3][ActiveObject][3][3]+=[[N,VP,LRS,BM,PA,PR]] #add a new bone __LOG('---FORMAT---: created Bone: %s'%Name) else: VIEWER.Libs[3][ActiveObject][3][3][BID]=[BoneLib[BID][0], #edit the specified bone ((VP if Viewport!=0 else BoneLib[BID][1]) if BoneLib[BID][1]!=VP else BoneLib[BID][1]), ((LRS if LRS!=DLRS else BoneLib[BID][2]) if BoneLib[BID][2]!=LRS else BoneLib[BID][2]), ((BM if BM!=DM44 else BoneLib[BID][3]) if BoneLib[BID][3]!=BM else BoneLib[BID][3]), ((PA if ParentName!='' else BoneLib[BID][4]) if BoneLib[BID][4]!=PA else BoneLib[BID][4]), ((PR if ParentName!='' else BoneLib[BID][5]) if BoneLib[BID][5]!=PR else BoneLib[BID][5])] #^- need to check for previous bone looping (in case of user error) __LOG('---FORMAT---: re-set Bone: %s'%BoneLib[BID][0])
def SetScene( Name="Scene0" ): global SceneCount,ActiveScene if SceneCount==0: #change the default scene name VIEWER.Libs[2][0][0]=(Name if type(Name)==str else "Scene"+str(SceneCount)) SceneCount+=1 else: #user defined scenes already exist SceneIndex = None #TODO: usa a while loop for Index,Scene in enumerate(VIEWER.Libs[2]): #check for specified scene name/index if Scene[0]==Name or Index==Name: SceneIndex=Index if SceneIndex == None: #create a new scene VIEWER.Libs[2]+=[Name if type(Name)==str else "Scene"+str(SceneCount)] ActiveScene=len(VIEWER.Libs[2]) #set the active scene index to the newly added scene SceneCount+=1 else: ActiveScene=SceneIndex #set the active scene index to the specified scene __LOG('---FORMAT---: created Scene: %s'%Name) SetScene.func_defaults=( "Scene"+str(SceneCount), )
def SetMaterial(Name="Material0"): global ActiveObject, ActiveMaterial #check if our material exists or create a new material MID = __GetMID(Name) if MID!='': #if so, update the material #Textures = VIEWER.Libs[4][MID][3] #preserve the textures ActiveMaterial = MID __LOG('---FORMAT---: set Active Material to: %s'%VIEWER.Libs[4][MID][0]) else: VIEWER.Libs[4] += [[Name, '', [[1.0,1.0,1.0,1.0],[1.0,1.0,1.0,1.0],[0.5,0.5,0.5,1.0],[0.0,0.0,0.0,0.0],25.0], [], [], []]] ActiveMaterial = len(VIEWER.Libs[4])-1 __LOG('---FORMAT---: created Material: %s'%Name) if VIEWER.Libs[3][ActiveObject][3][2] != ActiveMaterial: VIEWER.Libs[3][ActiveObject][3][2] = ActiveMaterial SetMaterial.func_defaults=( "Material"+str(len(VIEWER.Libs[4])), )
def String(value=None,encoding=__default_encoding,label=''): global __f,__o,__c; p=__POS() if value==None: #read string to 0x00 STRING=[] while IWLD(True) or __o[__c]<=(len(__f[__c])-1): #EOF? (lazy... need better EOF checking) i=__f[__c][__o[__c]] __o[__c]+=1 #maintain the offset if i==0: break else: STRING+=[chr(i)] if __TOGGLE_LOGGING: __LOG("%s: read %s encoded string '%s' to chr(0)%s"%(p,encoding,''.join(STRING),label)) return ''.join(STRING) if encoding==None else ''.join(STRING).decode(encoding) elif type(value)==int: if value==0: #read entire file STRING=[chr(i) for i in __f[__c][0:len(__f[__c])]] if __TOGGLE_LOGGING: __LOG("%s: read file as string%s"%(p,label)) return ''.join(STRING) if encoding==None else ''.join(STRING).decode(encoding) elif __o[__c]+value<=(len(__f[__c])-1): #read length, after EOF test STRING=''.join([chr(i) for i in __f[__c][__o[__c]:__o[__c]+value]]) __o[__c]+=value if __TOGGLE_LOGGING: __LOG("%s: read %s encoded string '%s' of length %i%s"%(p,encoding,STRING,value,label)) return STRING if encoding==None else STRING.decode(encoding) elif type(value)==str: #write string ov=value if encoding!=None: value=value.encode(encoding) __f[__c]+=__arr('B',[ord(c) for c in value]) __o[__c]+=len(value) if __TOGGLE_LOGGING: __LOG(("%s: wrote%s string '%s'%s"%(p,('' if encoding==None else ' %s%s'%(encoding,' encoded')),ov,label)).replace('\n','\\n')) elif type(value)==list: if len(value)==0: #readlines lines=(''.join([chr(i) for i in __f[__c][0:len(__f[__c])]])).split('\n') if __TOGGLE_LOGGING: __LOG("%s: read '%i' lines"%(p,len(lines))) return lines else: #write strings (lines if '\n' added) for Lval in value: String(Lval,encoding) elif type(value)==tuple: if len(value)==0: pass #TODO: readline (figuring out our position is the problem) else: #write strings (lines if '\n' added) for Lval in value: String(Lval)
def __BIT(big,bit_format,byte_size,value,label=''): global __f,__o,__c,FileError if not FileError: p=__POS() #get file position if type(value)==str: #credit to Gribouillis for various speedups: if (__o[__c]+byte_size)<=len(__f[__c]): #check for EOF (better than recieving an indexing error) DATA= __f[__c][__o[__c]:__o[__c]+byte_size]; val = 0 for v in (DATA if big else list(reversed(DATA))): val=(val<<8)|v #multi-int -> single-int (flipped if little endian) if bit_format == 1: val=(val-(1<<(byte_size<<3)) if val>(1<<(byte_size<<3))/2 else val) #signed int if bit_format == 2: #float (IEEE754) if val==0: return 0.0 #speedy check (before performing any calculations) #credit to pyTony for simplifying the formula of 'e' and fixing the return values e=((byte_size*8)-1)//(byte_size+1)+(byte_size>2)*byte_size//2; m,b=[((byte_size*8)-(1+e)), ~(~0 << e-1)] S,E,M=[(val>>((byte_size*8)-1))&1,(val>>m)&~(~0 << e),val&~(~0 << m)] #<- added brackets (faster processing) if E == int(''.join(['1']*e),2): val=(float('NaN') if M!=0 else (float('+inf') if S else float('-inf'))) else: val=((pow(-1,S)*(2**(E-b-m)*((1<<m)+M))) if E else pow(-1,S)*(2**(1-b-m)*M)) #I personally don't entirely understand this, but it works more than perfectly. XD if bit_format == 3: pass #float (IBM) if bit_format == 4: pass #float (Borland) __o[__c]+=byte_size #modify the file offset if __TOGGLE_LOGGING: __LOG('%s: read 0x%s as %s%s'%(p,''.join([__hx__[v] for v in DATA]),str(val),label)) return val else: #EOF (End Of File) if __TOGGLE_LOGGING: __LOG("\nERROR: End of File reached") raise EOFError #this will cancel the import operation elif type(value)==int or type(value)==long: #write int if bit_format==1: value=(value+pow(256,byte_size) if value<0 else value) #signed int Bytes=[(value>>(i*8))&255 for i in range(byte_size)] # single-int -> multi-int (could be faster) __f[__c]+=__arr('B',list(reversed(Bytes)) if big else Bytes) __o[__c]+=byte_size if __TOGGLE_LOGGING: __LOG("%s: wrote %i as 0x%s%s" % (p,value,''.join([__hx__[v] for v in Bytes]),label)) elif type(value)==float: #write float if value==0: Bytes=[0]*byte_size #speedy check (before performing any calculations) else: #credit to jdaster64 for this e=((byte_size*8)-1)//(byte_size+1)+(byte_size>2)*byte_size//2; m,E=[((byte_size*8)-(1+e)), ~(~0 << e-1)]; S=0 #pyTony's formula if value<0: S=1; value*=-1 #set the sign while value<1.0 or value>=2.0: value,E=(value*2.0,E-1) if value<1.0 else (value/2.0,E+1) v=(S<<(e+m))|(E<<m)|int(round((value-1)*(1<<m))) Bytes=[(v>>(i*8))&255 for i in range(byte_size)] __f[__c]+=__arr('B',list(reversed(Bytes)) if big else Bytes) __o[__c]+=byte_size if __TOGGLE_LOGGING: __LOG("%s: wrote %s as 0x%s%s" % (p,str(value),'',label)) elif type(value)==list: return list(__BIT(big,bit_format,byte_size,Lval) for Lval in value) elif type(value)==tuple: return tuple(__BIT(big,bit_format,byte_size,Tval) for Tval in value) elif type(value)==bool: return __BIT(big,bit_format,byte_size,int(value)) #Flag else: pass #skip the bad file
def __Hex(big,value,label=''): global __f,__a p=__POS() if type(value)==int: #read (bytes) DATA=__f[__c][__o[__c]:__o[__c]+value] __o[__c]+=value val = __HDF(DATA if big else list(reversed(DATA))) __LOG("%s: read 0x%s as '%s'%s" % (p,__HDF(DATA),val,label)) return val elif type(value)==str: #write value=((value.replace('0x','')).replace(' ','')).upper() #'0x08f0'/'08 F0' -> '08F0' if str(len(value)/2.).split('.')[1]=='5': value='%s%s'%('0',value) #'30F' -> '030F' Bytes = [__hx__[value[l*2:(l+1)*2]] for l in range(len(value)/2)] #if not big: Bytes=list(reversed(Bytes)) __f[__c]+=__arr('B',Bytes if big else list(reversed(Bytes))); __o[__c]+=len(Bytes) __LOG("%s: wrote '%s' as 0x%s%s" % (p,value,Bytes,label)) elif type(value)==list: return list(__Hex(big,Lval) for Lval in value) elif type(value)==tuple: return tuple(__Hex(big,Tval) for Tval in value) elif type(value)==bool: return __Hex(big,int(value))
def ImportFile(Name,RaiseError=0): #creates a file data space and fills it with the file data global __f,__d,__o,__n,__c,FileError D=(__d[__n[0]] if len(__n) else '') #the first file is specified by the Tkinter open dialog, #and will always have a directory try: FileError=0 #try to open the file F=open('%s%s'%(D,Name),'rb') #continue if successful l=len(F.read()); F.seek(0,0) __c=Name.split('/')[-1] __f.update({__c:__arr('B',[])}) __d.update({__c:'%s%s'%(D,Name.replace(__c,''))}) __o.update({__c:0}) __n+=[__c] #keep the index for switching files by index PrP,sec=0,(1.0/(l-1))*100 for i in range(l): #fill the data space __f[__c]+=__arr('B',[ord(F.read(1))]); P=int(sec*i) if P!=PrP: sys.stdout.write(' \rimporting %s %i%s'%(__c,P,'%')); PrP=P sys.stdout.write(' \rimporting %s %s\n'%(__c,'100%')) F.close() except IOError: print "ERROR: '%s' file not found!"%Name if __TOGGLE_LOGGING: __LOG("\nERROR: ImportFile('%s') file not found!"%Name) __LOG("Please check the directory to make sure the file exists.\n") if RaiseError: raise IOError #cancel the import/export operation else: FileError=1 #skip the file and continue the import/export operation
def Compress(Data,Method): global __Scripts,__f,__d,__o,__n,__c; position=len(__n)-1 existant=0 for Mod,D in __Scripts[3][0]: if D[1]==Method: #all we need is the method existant=1 if type(Data)==str: return sys.modules[Mod].Compress(Data) if not existant: print 'ERROR: Compression method "%s" not found'%Method if __TOGGLE_LOGGING: __LOG('\nERROR: Compression method "%s" not found'%Method) __LOG("Check your scripts to make sure you have the required method\n") __LOG("Or check the console to make sure the script isn't flawed.\n") raise ImportError #cancel the import/export operation
def SetTexture(Name="Texture0"): global ActiveMaterial,ActiveTexture TID = __GetTID(Name) if TID!='': ActiveTexture = TID __LOG('---FORMAT---: set Active Texture to: %s'%VIEWER.Libs[6][TID][0]) else: VIEWER.Libs[6] += [[Name,[],[],[],'',[]]] #TexName,TexParams,EnvParams,TReserved2,ImageName,TReserved3 ActiveTexture = len(VIEWER.Libs[6])-1 __LOG('---FORMAT---: created Texture: %s'%Name) if ActiveMaterial!=None: if ActiveTexture not in VIEWER.Libs[4][ActiveMaterial][3]: VIEWER.Libs[4][ActiveMaterial][3] += [ActiveTexture] __LOG('---FORMAT---: added Texture to Material: %s'%VIEWER.Libs[4][ActiveMaterial][0]) SetTexture.func_defaults=( "Texture"+str(len(VIEWER.Libs[6])), )
def ImportFile(Name,RaiseError=0): #creates a file data space and fills it with the file data global __f,__d,__o,__n,__c,FileError D=(__d[__n[0]] if len(__n) else '') #the initial file is specified by the Tkinter open dialog, #and will always have a directory. #further files are specified by the scripts which specify a directory local to this file's directory. try: FileError=0 #try to open the file F=open(Name if Name.count(':') else '%s%s'%(D,Name),'rb') #continue if successful l=len(F.read()); F.seek(0,0) __c=Name.split('/')[-1] __f[__c] = __arr('B',[255]*l) #much faster __d[__c] = '%s%s'%(D,Name.replace(__c,'')) __o[__c] = 0 __n+=[__c] #keep the index for switching files by index PrP,sec=0,(1.0/(l-1))*100 for i in range(l): #fill the data space __f[__c][i]=ord(F.read(1)); P=int(sec*i) if P!=PrP: sys.stdout.write(' \rimporting %s %i%s'%(__c,P,'%')); PrP=P sys.stdout.write(' \rimporting %s %s\n'%(__c,'100%')) F.close() __LOG("\n-- imported file: '%s' --\n"%__c) except IOError: print "ERROR: '%s' file not found!"%Name __LOG("\nERROR: ImportFile('%s') file not found!"%Name) __LOG("Please check the directory to make sure the file exists.\n") if RaiseError: raise IOError #cancel the import/export operation else: FileError=1 #skip the file and continue the import/export operation
def StructArr(Template,Value=''): #needs a performance boost (redo everything) global __f,__o,__c if type(Template)==tuple: Template=list(Template) if type(Template)!=list: Template=[Template] if type(Value)==tuple: Value=list(Value) #Tuples aren't really supported... yet >_> def RS(t): L=[] for Tm in t: #read single structure if type(Tm)==list: RS(Tm) else: R=__Term(Tm,''); L.append(0 if R==None else R) #returns 0 instead of None return L def WS(t,v): #write single structure for I,Tm in enumerate(t): if type(Tm)==list: WS(Tm,v[I]) #Template[I] == [] else: __Term(Tm,v[I]) if Value == '': #read until 0 struct if __TOGGLE_LOGGING: __LOG("%s: read structures of %s reaching a 0 struct."%(__POS(),str(Template))) Structs=[]; cont=1 while IWLD(cont): Struct = RS(Template) if type(Struct)==list: cont=(0 if sum(Struct)==0 else 1) else: cont=(0 if int(Struct)==0 else 1) if cont: Structs.append(Struct) return Structs if type(Value) == int: if __o[__c]==len(__f[__c])-1: #are we at the end? WS(Template,[Value]) #write the int value if so if __TOGGLE_LOGGING: __LOG("%s: wrote 1 structure of %s"%(__POS(),str(Template))) else: if __TOGGLE_LOGGING: __LOG('%s: read %i structures of %s'%(__POS(),Value,str(Template))) return [RS(Template) for v in range(Value)] #read count if type(Value) == list: if __o[__c]==len(__f[__c])-1: #are we at the end? for S in Value: #write structs if type(S)!=(list or tuple): S=[S] WS(Template,S) if __TOGGLE_LOGGING: __LOG("%s: wrote %i structures of %s"%(__POS(),len(Value),str(Template))) else: #read until StopStruct if __TOGGLE_LOGGING: __LOG("%s: read structures of %s stopping at %s"%(__POS(),str(Template),str(Value))) Structs=[]; cont=1 while IWLD(cont): Struct = RS(Template) if Struct==[(Struct[I] if V=='*' else V) for I,V in enumerate(Value)]: cont=0 else: Structs.append(Struct) return Structs if type(Value) == float: WS(Template,[Value]) #write the float value if __TOGGLE_LOGGING: __LOG("%s: wrote 1 structure of %s"%(__POS(),str(Template)))
def pString(value=None, start='', stop=chr(0), recursive=True, code=None, label=''): global __o__,__f,__c,__o; p=__POS() pos=__o[__c] #get the current offset in the file maxfilelen = len(__f[__c])-1 if value==None: #read string to stop character or 0x00 STRING='' # set the stop character chr(0) if '' or None if stop == None or stop == '': stop=0 else: stop=ord(stop) _start=0 if start!='': _start = ord(start) read = (start==None) r=0 #recursion depth try: while True or pos<=maxfilelen: if read: c=__f[__c][pos]; pos+=1 #maintain the internal offset if recursive: if c==_start: r+=1 if c==stop: if r>0: r-=1 else: break elif c==stop: break else: STRING='%s%s'%(STRING,chr(c)) #return what's read else: #once read is True, it can't be set False c=__f[__c][pos]; pos+=1 #maintain the internal offset if start=='': if c not in [0,10,32]: read = True; STRING='%s%s'%(STRING,chr(c)) elif c==_start: read = True if pos>maxfilelen: #EOF test if STRING=='': return None else: break except: import sys,traceback typ,val,tb=sys.exc_info()#;tb=traceback.extract_tb(i[2])[0] print traceback.print_exception( typ,val,tb#, #limit=2, #file=sys.stdout ) print raw_input('press enter to exit.') if start==None: startchr = '' elif start=='': STRING = STRING.lstrip() startchr = 'from whitespace ' else: startchr = "from '%s' "%start.replace('\n','\\n') if code!=None: STRING = STRING.decode(code) strcode = '%s encoded '%code else: strcode = '' if __o__!=None: __o__[__c]=pos; mode='' else: mode='pre' __LOG("%s: %sread %sstring '%s' %sto '%s'%s"%(p,mode,strcode,STRING,startchr,chr(stop).replace('\n','\\n'),label)) return STRING elif type(value)==int: if value==0: #read entire file STRING=[chr(i) for i in __f[__c]] __LOG("%s: read file as string"%p) #__LOG(''.join(STRING)) return ''.join(STRING) elif pos+value<=maxfilelen: #read length, EOF? STRING=''.join(chr(c) for c in __f[__c][pos:pos+value]) if code!=None: STRING = STRING.decode(code) strcode = '%s encoded '%code else: strcode = '' if __o__!=None: __o__[__c]+=value; mode='' else: mode='pre' __LOG("%s: %sread %sstring '%s' of length %i%s"%(p,mode,strcode,STRING,value,label)) return STRING elif type(value)==str: #write string if code!=None: value = value.encode(code) strcode = '%s encoded '%code else: strcode = '' __f[__c]+=__arr('B',[ord(c) for c in value]) if __o__!=None: __o__[__c]+=len(value) __LOG("%s: wrote %sstring '%s'%s"%(p,strcode,value,label)) elif type(value)==list: if len(value)==0: #readlines lines=String(0).split('\n') __LOG("%s: read '%i' lines"%(p,len(lines))) return lines else: #write strings (lines if '\n' added) __LOG("%s: wrote list of strings:"%p) for Lval in value: String(Lval,code)
def Jump(offset, location=0, position=0, label=''): #TODO: make sure we aren't jumping past the end of the file global __f,__o,__c; l=__POS(); p=__o[__c]; __o[__c]=offset+location+((len(__f[__c]) if position>1 else __o[__c]) if position else 0) __LOG('%s: jumping to: %s from %s%s'%(l,__POS(),(('end of file' if position>1 else 'current position') if position else 'start of file'),label)) return p #return the current position before jumping.
def Keyboard(key, x, y): global TOGGLE_FULLSCREEN,TOGGLE_LIGHTING,TOGGLE_GRID,TOGGLE_WIREFRAME,TOGGLE_BONES,TOGGLE_3D,TOGGLE_ORTHO global _mode,DIR global __MODEL_DATA,__BONE_DATA #//--// need a GUI handler for these if key == chr(9): #import model typenames,modules,modnames,ihandlers,decmpr = [],[],[],[],[]; iftypes,isupport = [],[] for M,D,I in COMMON.__Scripts[0][0]: #get model import scripts if D[1] != ('',['']): #script has model info (not sure if it's safe to remove this yet) iftypes+=[(D[1][0],tuple(["*.%s"%T for T in D[1][1]]))] for T in D[1][1]: try: isupport.index("*.%s"%T) #is this file type already supported? except: isupport+=["*.%s"%T] #add the current file type to the supported types list modnames+=[D[1][0]] #displayed in the GUI or Tk fiter typenames+=[T] #filetype modules+=[M] #current script ihandlers+=[I] #included image handlers #----- Tkinter dialog (will be replaced) _in=askopenfilename(title='Import Model', filetypes=[('Supported', " ".join(isupport))]+iftypes) #----- if _in=='': pass #action cancelled else: COMMON.__functions=[0,0,0,0] #prevent unwanted initialization #this block will change once I use my own dialog #Tkinter doesn't return the filter ID #----- it = _in.split('.')[-1] if typenames.count(it)>1: print '\nThis filetype is used by multiple scripts:\n' scr = [] for idx,ft in enumerate(typenames): if ft==it: scr+=[[modnames[idx],modules[idx]]] for I,NM in enumerate(scr): print ' %i - %s'%(I,NM[0]) print sid=input('Please enter the script ID here: ') i=__import__(scr[sid][1]) else: ti=typenames.index(it) i=__import__(modules[ti]) COMMON.__ReloadScripts() #check for valid changes to the scripts #----- try: #can we get our hands on the file? COMMON.ImportFile(_in,1) #set the file data global Libs; __Libs=Libs #remember last session in case of a script error Libs=[[],[],[],[],[["Def_Scene",[]]],[]] #reset the data for importing print 'Converting from import format...' try: #does the script contain any unfound errors? __LOG('-- importing %s --\n'%_in.split('/')[-1]) i.ImportModel(it,None) print 'Verifying data...' glNewList(__MODEL_DATA, GL_COMPILE); __M(); glEndList() glNewList(__BONE_DATA, GL_COMPILE); __B(); glEndList() print 'Updating Viewer\n' glutSetWindowTitle("Universal Model Converter v3.0a (dev5) - %s" % _in.split('/')[-1]) #export UMC session data l=open('session.ses','w') l.write(str([1,Libs])) l.close() COMMON.__ClearFiles() #clear the file data to be used for writing except: Libs=__Libs print "Error! Check 'session-info.log' for more details.\n" import traceback typ,val,tb=sys.exc_info()#;tb=traceback.extract_tb(i[2])[0] traceback.print_exception( typ,val,tb#, #limit=2, #file=sys.stdout ) print __Libs=[] #save memory usage except: pass #an error should already be thrown __WLOG(0) #write log COMMON.__CleanScripts() #remove pyc files if key == chr(5): #export model COMMON.__ClearFiles() #clear the file data again... just in case etypenames,emodules,emodnames,ehandlers = [],[],[],[]; eftypes = [] for M,D,I in COMMON.__Scripts[0][1]: if D[1] != ('',['']): #has model info eftypes+=[(D[1][0],tuple(["*.%s"%T for T in D[1][1]]))] for T in D[1][1]: emodnames+=[D[1][0]] etypenames+=[T] emodules+=[M] ehandlers+=[I] #Tkinter dialog (will be replaced) #----- _en=asksaveasfilename(title='Export Model', filetypes=eftypes, defaultextension='.ses') #----- if _en=='': pass else: COMMON.__functions=[0,0,0,0] #prevent unwanted initialization #this block will change once I use my own dialog #Tkinter doesn't return the filter ID #----- et = _en.split('.')[-1] if etypenames.count(et)>1: print '\nThis filetype is used by multiple scripts:\n' scr = [] for idx,ft in enumerate(etypenames): if ft==et: scr+=[[emodnames[idx],emodules[idx]]] for I,NM in enumerate(scr): print ' %i - %s'%(I,NM[0]) print sid=input('Please enter the script ID here: ') e=__import__(scr[sid][1]) else: e=__import__(emodules[etypenames.index(et)]) COMMON.__ReloadScripts() #check for valid changes to the scripts #----- ''' try: COMMON.ExportFile(_en) #add the file to the data space print 'converting to export format...' e.ExportModel(et,None) COMMON.__WriteFiles() print 'Done!' except: print "Error! Check 'session-info.log' for details.\n" ''' COMMON.ExportFile(_en) #add the file to the data space print 'converting to export format...' e.ExportModel(et,None) COMMON.__WriteFiles() print 'Refreshing Viewer\n' #''' __WLOG(_mode) #write log COMMON.__CleanScripts() #remove pyc files
def SwitchFile(Name=0,RaiseError=0): global __f,__n,__c,FileError if type(Name)==str: try: FileError=0 __f[Name] __c=Name if __TOGGLE_LOGGING: __LOG("\n-- Switching file: %s --"%Name) except: print "ERROR: SwitchFile('%s') file does not exist!"%Name if __TOGGLE_LOGGING: __LOG("\nERROR: SwitchFile('%s') file does not exist!"%Name) __LOG("Please make sure you've imported the file first with NewFile('%s')"%Name) __LOG("Or check to make sure you've included the file's extension.\n") if RaiseError: raise IndexError #cancel the import/export operation else: FileError=1 #skip the file and continue the import/export operation elif type(Name)==int: try: FileError=0 __c=__n[Name] if __TOGGLE_LOGGING: __LOG("\n-- Switching file: %s --"%__n[Name]) except: print "ERROR: SwitchFile('%i') invalid file index!"%Name if __TOGGLE_LOGGING: __LOG("\nERROR: SwitchFile('%i') invalid file index!"%Name) __LOG("Please make sure you've imported the file first with NewFile(*Directory*)") __LOG("Or check to make sure the index is valid. (0 is the first file)\n") if RaiseError: raise IndexError #cancel the import/export operation else: FileError=1 #skip the file and continue the import/export operation