Guest User

RPython Blender2.5 bridge

a guest
Jul 27th, 2010
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 19.90 KB | None | 0 0
  1. '''
  2. PyPy Pipe v0.3
  3. Brett Hartshorn 2010 - License BSD
  4.  
  5. Run "./blender -P pypypipe.py"
  6.  
  7. Use CPython as a host for external libs, tested with PyGTK, PyODE, and Pygame
  8. return types limited: bool, tuple, object   # TODO add more
  9. no keyword arguments can be used from RPython, unless you define a custom wrapper.
  10. only simple lambda callbacks are working (these operate in CPython space)
  11. TODO: callback from CPython to RPython
  12.  
  13. Getting Started:
  14.     make sure this file is named pypypipe.py
  15.     copy this file to your pypy trunk folder, or add the path to pypy below PATH2PYPY
  16.     make sure you have pygame, pygtk, and pyode
  17.  
  18. Hacking:
  19.     Dynamic attribute access is not possible, but function calls are ok.
  20.     This is wrapper incomplete, any class with unique init args, or functions with unique
  21.     args must be hand wrapped.  Even the return type may need to be defined.
  22.     See below:
  23.         gen_func_response
  24.         genRPC
  25.         INIT_GROUPS
  26.  
  27.  
  28. pypy hacking notes:
  29.     s = s[1:len(s)-1]       # pypy.rpython.error.TyperError: slice stop must be proved non-negative
  30.     s = s.replace('<','').replace('>','')   # pypy.rpython.error.TyperError: replace only works for char args
  31.     long(string, 16) not allowed
  32.     globals() not allowed
  33.     function return types can not be mixed (required generated return functions per incompatible types)
  34.  
  35. '''
  36. ## Set your PyPy root ##
  37. PATH2PYPY = 'pypy'
  38.  
  39. def pypy_entry_point_test_bpy():
  40.     ops = bpy_ops_wrapped()
  41.     #debug( ops )
  42.     mesh = ops.mesh()
  43.     mesh.primitive_plane_add()
  44.     debug('bpy ops test complete')
  45.  
  46. def pypy_entry_point():
  47.     ## init module level proxies ##
  48.     gtk = gtk_wrapped()
  49.     #pygame = pygame_wrapped()
  50.     #pygame.display = pygame_display_wrapped()
  51.     #pygame.draw = pygame_draw_wrapped()
  52.     #ode = ode_wrapped()
  53.  
  54.     #world = ode.World()
  55.     #world.setERP( 0.8 )
  56.     #world.setCFM( 0.1 )
  57.     #world.setGravity( ( 0, -0.6*10000, 0 ) )
  58.     #body = ode.Body( world )
  59.     #body.addForce( (1,0,0) )       # not having dynamic attribute access is a good thing!?
  60.  
  61.     w = gtk.Window()
  62.     w.set_size_request( 320,200 )
  63.     w.set_title('PyPyGTK v0.1b')
  64.     root = gtk.VBox(); w.add( root )
  65.     root.set_border_width(50)
  66.     lab = gtk.Label()
  67.     lab.set_text( 'hello world' )
  68.     root.pack_start( lab )
  69.     b = gtk.Button( 'click me' )
  70.     b.connect('clicked', "lambda b,l: l.set_text('clicked test')", lab )        # note lambdas are passed as strings
  71.     root.pack_start( b )
  72.     root2 = b.get_parent()
  73.     root2.pack_start( gtk.Label('return instance from CPython works') )
  74.     b = gtk.Button('exit demo')
  75.     b.connect('clicked', 'lambda b: gtk.main_quit()' )
  76.     root2.pack_start( b )
  77.     frame = gtk.Frame('PyODE body position')
  78.     root2.pack_start( frame )
  79.     bodylab = gtk.Label('body pos')
  80.     frame.add( bodylab )
  81.     w.show_all()
  82.  
  83.     w2 = gtk.Window( gtk.WINDOW_POPUP )
  84.     w2.move( 20,240 )
  85.     w2.set_size_request( 320,100 )
  86.     r2 = gtk.VBox(); w2.add( r2 )
  87.     lab2 = gtk.Label('enum values work (this is a popup window)' )
  88.     r2.pack_start( lab2 )
  89.     b2 = gtk.Button('close')
  90.     b2.connect('clicked', "lambda b,w: w.destroy()", w2)
  91.     r2.pack_start( b2 )
  92.     w2.show_all()
  93.  
  94.     #pygame.init()
  95.     #surf = pygame.display.set_mode( (320,240) )
  96.     i = 0
  97.     while True:     # does not block gtk because we have a glib timeout in the other process
  98.         #x = math.sin( radians(i) ) * 100
  99.         #y = math.cos( radians(i) ) * 100
  100.         #pygame.draw.aaline( surf, (255,255,255,255), (160,120), (int(160+x),int(120+y)) )
  101.         #pygame.display.flip()
  102.  
  103.         #world.quickStep( 0.001 )
  104.         #pos = body.getPosition()
  105.         #bodylab.set_text( str(pos) )
  106.  
  107.         i += 1
  108.         if i == 360: raise SystemExit
  109.  
  110.  
  111.  
  112. def pypy_entry_point_test_simple():
  113.     os = os_wrapper()
  114.     print( os.system )
  115.  
  116.  
  117.  
  118.  
  119.  
  120.  
  121.  
  122. ## Reserved Characters, can not be passed from rpython to Cpython by function call in a string
  123. ## you can change them if you need ##
  124. INSTANCE_SEP = '|'
  125. FUNCTION_SEP = '$'
  126. FUNC_ARG_SEP = '^'
  127. ARGUMENT_SEP = '~'
  128. MODULE_SEP = '!'
  129. DO_NOT_CREATE = b'DO_NOT_CREATE'
  130.  
  131. import os, sys, time, inspect, types, select, subprocess, math, pickle
  132. if '.' not in sys.path: sys.path.append( '.' )      # blender253 pickle bug
  133. sys.path.append(PATH2PYPY)      # assumes you have pypy dist in a subfolder, you may need to rename this pypy-trunk
  134. #import pypy.tool.error
  135.  
  136. bpy = glib = gtk = ode = pygame = None
  137. try:
  138.     import glib, gtk
  139.     import pygame, ode
  140. except:
  141.     try:
  142.         import bpy
  143.         ops = bpy.ops
  144.     except: pass
  145.  
  146. DEBUG = False
  147.  
  148. def debug( string ):
  149.     stderr.write( '\t[debug][%s]\n' %string )
  150.     stderr.flush()
  151.  
  152. degToRad = math.pi / 180.0
  153. def radians(x):
  154.     """radians(x) -> converts angle x from degrees to radians
  155.     """
  156.     return x * degToRad
  157.  
  158. def loop():
  159.     #time.sleep(0.01)
  160.     rlist,wlist,xlist = select.select( [read], [write], [], 0.01 )     
  161.     if rlist and wlist: # must wait for both read and write, because read can be selected by itself, but we must also respond
  162.         a = read.readline().decode().strip()
  163.         if a: print( a )
  164.         if a and a.startswith('>'):
  165.             print('ok')
  166.             cname = header = a.split('>')[-1].strip()
  167.             mod = globals()
  168.             if MODULE_SEP in header:
  169.                 mname, cname = header.split( MODULE_SEP )   # should raise syntax error if ! was in arg string
  170.                 mod = mod[ mname ]
  171.  
  172.                 if FUNC_ARG_SEP in cname:
  173.                     cname, args = cname.split( FUNC_ARG_SEP )
  174.                     nargs = string2args( args )
  175.                     cls = getattr( mod, cname )
  176.                     # workaround for functions that return objects
  177.                     if DO_NOT_CREATE in nargs:
  178.                         if DEBUG: print( 'not creating instance' )
  179.                         ID = nargs[-1]; o = INSTANCES[ int(ID) ]
  180.                     else: o = cls( *nargs )
  181.                 else:
  182.                     cls = getattr( mod, cname )
  183.                     try: o = cls()
  184.                     except: o = cls
  185.  
  186.             else: ## module ##
  187.                 #if cname not in mod:   ## this is not useful because it needs to be wrapped beforehand
  188.                 #   print '------importing-------'
  189.                 #   o = __import__( cname, mod )
  190.                 #else:
  191.                 if DEBUG: print( '-----getting module------' )
  192.                 if '.' in cname:
  193.                     x,y = cname.split('.')
  194.                     o = getattr(mod[ x ], y )
  195.                 else: o = mod[ cname ]
  196.  
  197.             ID = id( o )        # cpython object
  198.             INSTANCES[ ID ] = o
  199.             if DEBUG:
  200.                 print( '$cpython instance', o )
  201.                 print( '$instance ID', ID )
  202.             #write.write( b'%s\n' %ID )
  203.             write.write( bytes( str(ID), 'utf-8' ) + b'\n' )
  204.             write.flush()
  205.  
  206.         elif a and a.startswith('@'):
  207.             ID, b = a.split( FUNCTION_SEP )
  208.             ID = int(ID[1:])        # strip the @
  209.             o = INSTANCES[ID]
  210.             if DEBUG: print( '$got instance', o)
  211.             fname,args = b.split(FUNC_ARG_SEP)
  212.             func = getattr( o, fname )
  213.             nargs = string2args( args )
  214.             if DEBUG: print( 'calling', func)
  215.             res = func( *nargs )        # call the function
  216.             ## check the output of the function ##
  217.             r = ''
  218.             if gtk and isinstance(res,gtk.Object):
  219.                 sID = id(res)
  220.                 if sID not in INSTANCES: INSTANCES[ sID ] = res
  221.                 r += '<gtk.%s%s%s>' %(res.__class__.__name__, INSTANCE_SEP, sID)
  222.             elif pygame and isinstance( res, pygame.Surface ):
  223.                 sID = id(res)
  224.                 if sID not in INSTANCES: INSTANCES[ sID ] = res
  225.                 r += '<pygame.%s%s%s>' %(res.__class__.__name__, INSTANCE_SEP, sID)
  226.             elif ode and isinstance( res, (ode.World,ode.Body) ):
  227.                 sID = id(res)
  228.                 if sID not in INSTANCES: INSTANCES[ sID ] = res
  229.                 r += '<ode.%s%s%s>' %(res.__class__.__name__, INSTANCE_SEP, sID)
  230.  
  231.  
  232.             else: r = str( res )
  233.             #sres = sres.replace(' instance at ', INSTANCE_SEP)
  234.             #if type(res) in (tuple,list):
  235.             if DEBUG: print( 'piping back ->', r )
  236.             #write.write( '%s\n' %r )
  237.             write.write( bytes( r, 'utf-8' ) + b'\n' )
  238.             write.flush()
  239.  
  240.     return True
  241.  
  242.  
  243. def pipe( string ): # the types of *args can not change in pypy, convert to strings first
  244.     rl,wl,xl = rpoll.select( [], [1], [], 0 )
  245.     if wl:
  246.         stdout.write( '%s\n' %string )
  247.         stdout.flush()
  248.  
  249. def string2args( string ):
  250.     nargs = []
  251.     for arg in string.split(ARGUMENT_SEP):
  252.         if arg.strip():
  253.             if arg.startswith('@'): nargs.append( INSTANCES[int(arg[1:])] )
  254.             else: nargs.append( eval(arg) )
  255.     return nargs
  256.  
  257. GeneratedResponses = {}
  258. GeneratedClasses = {}
  259. GeneratedRPC = {}
  260.  
  261. def gen_func_response( rtype=object ):
  262.     if rtype is bool:
  263.         def get_function_response(dummy):
  264.             if DEBUG: debug( 'waiting for function response' )
  265.             rl,wl,xl = rpoll.select( [0], [], [], 60 )  # wait 10 seconds, subprocess only needs to wait for reading
  266.             if rl:
  267.                 if DEBUG: debug( 'readline ready' )
  268.                 s = string = stdin.readline().strip('\n').strip(' ')
  269.                 if DEBUG: debug( '^got function response: %s' %string )
  270.                 if s == 'True': return True
  271.                 elif s == 'False': return False
  272.             else:
  273.                 debug( '^^ lost contact with parent process ^^' )
  274.                 raise SystemExit
  275.     elif rtype is tuple:
  276.         def get_function_response(dummy):
  277.             if DEBUG: debug( 'waiting for function response' )
  278.             rl,wl,xl = rpoll.select( [0], [], [], 60 )  # wait 10 seconds, subprocess only needs to wait for reading
  279.             if rl:
  280.                 if DEBUG: debug( 'readline ready' )
  281.                 s = string = stdin.readline().strip('\n').strip(' ')
  282.                 if DEBUG: debug( '^got function response: %s' %string )
  283.                 s = s.replace('(',' ').replace(')',' ').strip(' ')
  284.                 return [ float(x) for x in s.split(',') ]
  285.             else:
  286.                 debug( '^^ lost contact with parent process ^^' )
  287.                 raise SystemExit
  288.  
  289.     elif rtype is object:
  290.         def get_function_response(dummy):
  291.             if DEBUG: debug( 'waiting for function response' )
  292.             rl,wl,xl = rpoll.select( [0], [], [], 60 )  # wait 10 seconds, subprocess only needs to wait for reading
  293.             if rl:
  294.                 if DEBUG: debug( 'readline ready' )
  295.                 s = string = stdin.readline().strip('\n').strip(' ')
  296.                 if DEBUG: debug( '^got function response: %s' %string )
  297.                 if s.startswith('<') and s.endswith('>'):
  298.                     s = s.replace('<',' ').replace('>',' ').strip(' ')
  299.                     if INSTANCE_SEP in s:
  300.                         a,b = s.split( INSTANCE_SEP )       # pypy only splits on a single char
  301.                         ID = int( b )
  302.                         if ID in Cache.instances:
  303.                             if DEBUG: debug( 'proxy already exists' )
  304.                             return Cache.instances[ID]
  305.                         else:
  306.                             if DEBUG: debug( 'creating new rproxy' )
  307.                             cls = GeneratedClasses[ a ]
  308.                             return cls( DO_NOT_CREATE, str(ID) )
  309.             else:
  310.                 debug( '^^ lost contact with parent process ^^' )
  311.                 raise SystemExit
  312.  
  313.     return get_function_response
  314.  
  315. class RCache(object):
  316.     def __init__(self):
  317.         self.instances = {}
  318. Cache = RCache()
  319.  
  320.  
  321. class Proxy(object):        ## pypy only allows __init__ and __del__
  322.     pass
  323. def geninit():      # generating init for each class is too slow
  324.     def __init__(self, *args):
  325.         if self._modulename_: header = '%s%s%s' %(str(self._modulename_), MODULE_SEP, str(self._classname_))
  326.         else: header = self._classname_
  327.         if args:
  328.             a = ''
  329.             for arg in list(args):
  330.                 if isinstance(arg,Proxy): a += '@%s%s' %(arg._ID, ARGUMENT_SEP)
  331.                 elif isinstance( arg, str ):        # type(arg) is str # not allowed in pypy
  332.                     a += '"%s"%s' %(arg, ARGUMENT_SEP)
  333.                 else: a += '%s%s' %(arg, ARGUMENT_SEP)
  334.             pipe( '>create>%s%s%s' %(header, FUNC_ARG_SEP, a) )
  335.         else: pipe( '>create>%s' %str(header) )
  336.         self._ID = 0
  337.         rl,wl,xl = rpoll.select( [0], [], [], 10.0 )    # wait 10 seconds, subprocess only needs to wait for reading
  338.         if rl:
  339.             ID = stdin.readline().strip('\n').strip(' ')
  340.             self._ID = int(ID)
  341.             Cache.instances[ self._ID ] = self
  342.         else:
  343.             pipe( '^^ lost contact with parent process ^^' )
  344.             raise SystemExit
  345.     return __init__
  346. Proxy.__init__ = geninit()
  347.  
  348.  
  349. INSTANCES = {}
  350.  
  351. CALL_GROUPS = { 'tag lambda *args': [], 'pygame.draw.line': [] }
  352. if gtk:
  353.     CALL_GROUPS[ 'tag lambda *args' ].append( gtk.Object.connect )
  354. if pygame:
  355.     CALL_GROUPS[ 'pygame.draw.line' ].append( pygame.draw.line )
  356.     CALL_GROUPS[ 'pygame.draw.line' ].append( pygame.draw.aaline )
  357.  
  358. RETURN_GROUPS = { tuple : [] }
  359. if ode:
  360.     RETURN_GROUPS[ tuple ].append(ode.Body.getPosition)
  361.  
  362.  
  363. class WrapFunction(object):
  364.     def __init__(self, fname, func ):
  365.         self._func_name = fname
  366.         self._call_group = None
  367.         self._return_group = None
  368.         for group in CALL_GROUPS:
  369.             if func in CALL_GROUPS[group]:
  370.                 self._call_group = group
  371.                 break
  372.         for group in RETURN_GROUPS:
  373.             if func in RETURN_GROUPS[group]:
  374.                 self._return_group = group
  375.                 break
  376.  
  377.     def unpack( self ):     ## interesting pypy needs generated functions so that *args can work properly
  378.         fname = self._func_name
  379.         index = len( GeneratedResponses )
  380.         gupdate = {}
  381.         genres_name = '_generated_RPC_closure%s'%index
  382.         if self._return_group:
  383.             gupdate[ genres_name ] = genres_func = gen_func_response( self._return_group )
  384.         else:
  385.             gupdate[ genres_name ] = genres_func = gen_func_response()      # defaults to object
  386.  
  387.         GeneratedResponses[ genres_name ] = genres_func
  388.         genres_func.func_name = genres_name
  389.  
  390.         rpc_name = '_generated_RPC%s'%index
  391.  
  392.         if self._call_group == 'tag lambda *args':
  393.             def rpc( self, name, tag, callback, *args ):
  394.                 if DEBUG: debug( '-rpc %s %s' %(self, name) )
  395.                 a = '"%s"%s' %(tag, ARGUMENT_SEP)
  396.                 a += '%s%s' %(callback, ARGUMENT_SEP)
  397.                 for arg in list(args):
  398.                     if isinstance(arg,Proxy): a += '@%s%s' %(arg._ID, ARGUMENT_SEP)
  399.                     elif isinstance( arg, str ):        # type(arg) is str # not allowed in pypy
  400.                         a += '"%s"%s' %(arg, ARGUMENT_SEP)
  401.                     else: a += '%s%s' %(arg, ARGUMENT_SEP)
  402.                 pipe( '@%s%s%s%s%s' %(self._ID, FUNCTION_SEP, name, FUNC_ARG_SEP, a) )
  403.             wrap = eval( 'lambda self,tag,cb,*args: %s(%s(self,"%s",tag,cb,*args))' %(genres_name, rpc_name, fname) )
  404.  
  405.         elif self._call_group == 'pygame.draw.line':
  406.             def rpc( self, name, surf, color, start, end, width=1 ):
  407.                 if DEBUG: debug( '-rpc %s %s' %(self, name) )
  408.                 a = '@%s%s' %(surf._ID,ARGUMENT_SEP)
  409.                 a += '%s%s' %(color,ARGUMENT_SEP)
  410.                 a += '%s%s' %(start,ARGUMENT_SEP)
  411.                 a += '%s%s' %(end,ARGUMENT_SEP)
  412.                 a += '%s%s' %(width,ARGUMENT_SEP)
  413.                 pipe( '@%s%s%s%s%s' %(self._ID, FUNCTION_SEP, name, FUNC_ARG_SEP, a) )
  414.             wrap = eval( 'lambda self,surf,color,start,end,width=1: %s(%s(self,"%s",surf,color,start,end,width))' %(genres_name, rpc_name, fname) )
  415.  
  416.         else:
  417.             def rpc( self, name, *args ):
  418.                 if DEBUG: debug( '-rpc %s %s' %(self, name) )
  419.                 a = ''
  420.                 for arg in list(args):
  421.                     if isinstance(arg,Proxy): a += '@%s%s' %(arg._ID, ARGUMENT_SEP)
  422.                     elif isinstance( arg, str ):        # type(arg) is str # not allowed in pypy
  423.                         a += '"%s"%s' %(arg, ARGUMENT_SEP)
  424.                     else: a += '%s%s' %(arg, ARGUMENT_SEP)
  425.                 pipe( '@%s%s%s%s%s' %(self._ID, FUNCTION_SEP, name, FUNC_ARG_SEP, a) )
  426.             wrap = eval( 'lambda self,*args: %s(%s(self,"%s",*args))' %(genres_name, rpc_name, fname) )
  427.  
  428.         rpc.func_name = rpc_name
  429.         GeneratedRPC[ rpc_name ] = rpc
  430.         gupdate[ rpc_name ] = rpc
  431.         globals().update( gupdate )
  432.         return wrap
  433.  
  434.  
  435. ## these are considered constants ##
  436. WrappableAttributesTypes = (
  437.     bool,
  438.     int,
  439.     #long,
  440.     float,
  441.     str,
  442.     #unicode,
  443. )
  444. INIT_GROUPS = { int:[], object:[] }
  445. if gtk:
  446.     INIT_GROUPS[ int ].append( gtk.Window )
  447. if ode:
  448.     INIT_GROUPS[ object ].append( ode.Body )
  449.  
  450. INIT_GROUPS_gen = {}
  451. for tag in INIT_GROUPS: INIT_GROUPS_gen[ tag ] = geninit()
  452. del tag
  453.  
  454. class WrapClass(object):
  455.     def __init__( self, cls, classname, modulename, items={} ):
  456.         if modulename: modulename = str(modulename)
  457.         self._classname = str(classname)
  458.         self._modulename = modulename
  459.         self._items = items
  460.         self._init_type = None
  461.         for group in INIT_GROUPS:
  462.             if cls in INIT_GROUPS[group]:
  463.                 self._init_type = group
  464.  
  465.     def unpack( self ):
  466.         classitems = {}
  467.         for key in self._items:
  468.             #debug( key )
  469.             v = self._items[key]
  470.             if isinstance( v, (WrapClass,WrapFunction) ): v = v.unpack()
  471.             classitems[ key ] = v
  472.  
  473.         if self._init_type in INIT_GROUPS_gen:
  474.             classitems['__init__'] = INIT_GROUPS_gen[ self._init_type ] # classes that have the same init vars
  475.  
  476.         self._classname = str(self._classname)
  477.         classitems['_classname_'] = self._classname
  478.         if self._modulename:
  479.             self._modulename = str(self._modulename)
  480.             classitems['_modulename_'] = self._modulename
  481.  
  482.         metaclass = types.ClassType(self._classname, bases=(Proxy,), dict=classitems)
  483.         if self._modulename: key = '%s.%s' %(self._modulename, self._classname)
  484.         else: key = self._classname
  485.         GeneratedClasses[ key ] = metaclass
  486.         return metaclass
  487.  
  488. def wrap_class( cls, classes=False ):
  489.     print( 'wrapping', cls )
  490.     if cls.__class__.__name__ == 'bpy_ops':
  491.         name = 'ops'
  492.         mname = None
  493.     elif cls.__class__.__name__ == 'bpy_ops_submodule':
  494.         name = cls.module       # name of submod "mesh" etc..
  495.         mname = 'ops'
  496.     else:
  497.         name = cls.__name__
  498.         if inspect.ismodule( cls ): mname = None
  499.         else: mname = cls.__module__
  500.     if mname: mname = str(mname)
  501.     name = str(name)
  502.     funcs = {}
  503.     fnames = ''
  504.     d = { '_classname_':str(name), '_modulename_':mname }
  505.  
  506.     for n in dir(cls):
  507.         if n.startswith('_'): continue
  508.         a = getattr( cls, n )
  509.         if inspect.isroutine( a ) or ( isinstance(a,object) and a.__class__.__name__ == 'bpy_ops_submodule_op' ):
  510.             #print( '\tFUNCTION: ', n )
  511.             d[n] = WrapFunction(n,a)
  512.         elif inspect.isclass( a ) and classes:
  513.             #if classes: print '\tCLASS: ', n
  514.             if a.__module__ == 'gtk._gtk': continue
  515.             else: d[ n ] = wrap_class( a )
  516.         elif isinstance(a,object) and a.__class__.__name__ == 'bpy_ops_submodule':
  517.             d[ n ] = wrap_class( a )
  518.         elif type(a) in WrappableAttributesTypes:
  519.             d[ n ] = a
  520.         elif type(a) in (list,tuple):
  521.             safe = True
  522.             for item in a:
  523.                 if type(item) not in WrappableAttributesTypes:
  524.                     safe = False; break
  525.             if safe:
  526.                 d[ n ] = a
  527.         else:
  528.             ## check for gtk enum
  529.             items = dir(a)
  530.             enum = True
  531.             for test in 'conjugate denominator imag numerator real'.split():
  532.                 if test not in items: enum = False; break
  533.             if enum:
  534.                 d[ n ] = a.real
  535.  
  536.     #mclass = types.ClassType(name, bases=(Proxy,), dict=d)
  537.     #if mname: key = '%s.%s' %(mname,name)
  538.     #else: key = name
  539.     #GeneratedClasses[ key ] = mclass
  540.     #globals()[ name ] = mclass
  541.     #return mclass
  542.     wrapped = WrapClass( cls, name, mname, items=d )
  543.     #globals()[ 'wrapped_%s' %time.time() ] = wrapped
  544.     return wrapped
  545.  
  546. if '--pypy' in sys.argv:
  547.     from pypy.rlib import streamio
  548.     from pypy.rlib import rpoll
  549.     from pypy.translator.interactive import Translation
  550.  
  551.     stdin = streamio.fdopen_as_stream(0, 'r', 0)        # fd, mode, buffering
  552.     stdout = streamio.fdopen_as_stream(1, 'w', 0)
  553.     stderr = streamio.fdopen_as_stream(2, 'w', 0)
  554.  
  555.     dump = pickle.load( open('/tmp/genwrapper.pickle','rb') )
  556.     D = globals()
  557.     for key in dump:
  558.         debug( key )
  559.         metaclass = dump[key].unpack()
  560.         debug( metaclass )
  561.         D[ key ] = metaclass
  562.     for k in globals().keys():
  563.         if not k.startswith('_'):
  564.             debug('global %s' %k )
  565.  
  566.     if '--bpy' in sys.argv: t = Translation( pypy_entry_point_test_bpy )
  567.     elif '--gtk' in sys.argv: t = Translation( pypy_entry_point )
  568.     else: t = Translation( pypy_entry_point_simple )
  569.     t.annotate(); t.rtype()
  570.     f = t.compile_c()
  571.     f()
  572.     print( 'subprocess exit' )
  573.  
  574.  
  575. elif __name__ == '__main__':
  576.     import pypypipe     # blender253 pickle bug
  577.     pypypipe.dump()
  578.     test = ''
  579.     if bpy: test = '--bpy'
  580.     elif gtk: test = '--gtk'
  581.     process = subprocess.Popen( 'python pypypipe.py --pypy %s' %test, stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=0, shell=True )
  582.     write = process.stdin
  583.     read = process.stdout
  584.     print( 'read pipe', read )
  585.     print( 'read write', write )
  586.     if glib:
  587.         glib.timeout_add( 33, loop )
  588.         gtk.main()
  589.     elif bpy:
  590.         bpy.ops.screen.animation_play('EXEC_DEFAULT')
  591.         def draw_callback( area, region ): loop()
  592.         for area in bpy.context.window.screen.areas:
  593.             print(area.type)
  594.             if area.type == 'VIEW_3D':
  595.                 for reg in area.regions:
  596.                     print( '\tregion: ', reg.type )
  597.                     if reg.type == 'WINDOW':
  598.                         print( 'adding callback' )
  599.                         reg.callback_add(draw_callback, (area,reg), 'POST_PIXEL')   # sneaky! unlisted function!!!
  600.  
  601.  
  602.     print( 'toplevel exit' )
  603.  
  604. #else:      # import pypypipe  (blender253 pickle bug)
  605. def dump():
  606.     ## save wrap ##
  607.     D = {}
  608.     if gtk:
  609.         w = wrap_class( gtk, classes=True )
  610.         D['gtk_wrapped'] = w
  611.         #D['pygame_wrapped'] = wrap_class( pygame, classes=True )
  612.         #D['pygame_display_wrapped'] = wrap_class( pygame.display, classes=True )
  613.         #D['pygame_draw_wrapped'] = wrap_class( pygame.draw, classes=True )
  614.         D['ode_wrapped'] = wrap_class( ode, classes=True )
  615.     elif bpy:
  616.         D['bpy_ops_wrapped'] = wrap_class( bpy.ops, classes=True )
  617.  
  618.     else:
  619.         D['os_wrapped'] = wrap_class( os, classes=True )
  620.  
  621.     f = open('/tmp/genwrapper.pickle','wb')
  622.     pickle.dump( D, f, protocol=2)      #,fix_imports=False )
  623.     f.close()
  624.     print( 'genwrapper.pickle dumped' )
Advertisement
Add Comment
Please, Sign In to add comment