Skip to content

Instantly share code, notes, and snippets.

@skrat
Created March 20, 2019 18:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save skrat/feb829e26c655521410ccac085abf651 to your computer and use it in GitHub Desktop.
Save skrat/feb829e26c655521410ccac085abf651 to your computer and use it in GitHub Desktop.
Auto reload file in blender using asyncio sleep
import os
import bpy
import asyncio
GLB = "/tmp/model.glb"
def import_gltf(path):
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()
bpy.ops.import_scene.gltf(filepath=path)
@asyncio.coroutine
def watch_file(path, interval=1):
mtime = None
while True:
if os.path.exists(path):
mtime_now = os.path.getmtime(path)
if mtime != mtime_now:
mtime = mtime_now
import_gltf(path)
yield from asyncio.sleep(interval)
timer = None
class AsyncLoop(bpy.types.Operator):
bl_idname = "asyncio.loop"
bl_label = "Runs the asyncio main loop"
command = bpy.props.EnumProperty(name="Command",
description="Command being issued to the asyncio loop",
default='TOGGLE', items=[
('START', "Start", "Start the loop"),
('STOP', "Stop", "Stop the loop"),
('TOGGLE', "Toggle", "Toggle the loop state")
])
period = bpy.props.FloatProperty(name="Period",
description="Time between two asyncio beats",
default=0.01, subtype="UNSIGNED", unit="TIME")
def execute(self, context):
return self.invoke(context, None)
def invoke(self, context, event):
global timer
wm = context.window_manager
if timer and self.command in ('STOP', 'TOGGLE'):
wm.event_timer_remove(timer)
timer = None
return {'FINISHED'}
elif not timer and self.command in ('START', 'TOGGLE'):
wm.modal_handler_add(self)
timer = wm.event_timer_add(self.period, window=context.window)
return {'RUNNING_MODAL'}
else:
return {'CANCELLED'}
def modal(self, context, event):
global timer
if not timer:
return {'FINISHED'}
elif event.type != 'TIMER':
return {'PASS_THROUGH'}
else:
loop = asyncio.get_event_loop()
loop.stop()
loop.run_forever()
return {'RUNNING_MODAL'}
def register():
bpy.utils.register_class(AsyncLoop)
def unregister():
bpy.utils.unregister_class(AsyncLoop)
register()
asyncio.ensure_future(watch_file("/tmp/model.glb", 0.5))
bpy.ops.asyncio.loop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment