From 594b82f814021e4eea9403d70a2a3f9ab7b88fa9 Mon Sep 17 00:00:00 2001 From: Swann Martinez Date: Fri, 23 Aug 2019 12:28:57 +0200 Subject: [PATCH] refactor: pep8 compliant --- __init__.py | 7 +-- delayable.py | 27 ++++++---- environment.py | 40 +++++++-------- operators.py | 51 ++++++++++--------- presence.py | 53 +++++++++----------- ui.py | 130 +++++++++++++++++++++++++------------------------ 6 files changed, 162 insertions(+), 146 deletions(-) diff --git a/__init__.py b/__init__.py index 6ada564..4be3a28 100644 --- a/__init__.py +++ b/__init__.py @@ -10,14 +10,15 @@ bl_info = { import logging +import os import random import sys -import os + import bpy -from . import environment -from . import utils from bpy.app.handlers import persistent +from . import environment, utils + DEPENDENCIES = { "zmq", "umsgpack", diff --git a/delayable.py b/delayable.py index 721b18d..547155f 100644 --- a/delayable.py +++ b/delayable.py @@ -1,12 +1,15 @@ import bpy -from .libs.replication.constants import * -from .libs import debug + from . import operators, utils from .bl_types.bl_user import BlUser +from .libs import debug +from .libs.replication.constants import FETCHED + class Delayable(): """Delayable task interface """ + def register(self): raise NotImplementedError @@ -16,11 +19,13 @@ class Delayable(): def unregister(self): raise NotImplementedError + class Timer(Delayable): """Timer binder interface for blender Run a bpy.app.Timer in the background looping at the given rate """ + def __init__(self, duration=1): self._timeout = duration @@ -42,8 +47,9 @@ class Timer(Delayable): except: print("timer already unregistered") + class ApplyTimer(Timer): - def __init__(self, timout=1,target_type=None): + def __init__(self, timout=1, target_type=None): self._type = target_type super().__init__(timout) @@ -59,24 +65,26 @@ class ApplyTimer(Timer): return self._timeout + class Draw(Delayable): def __init__(self): self._handler = None def register(self): self._handler = bpy.types.SpaceView3D.draw_handler_add( - self.execute,(), 'WINDOW', 'POST_VIEW') - + self.execute, (), 'WINDOW', 'POST_VIEW') + def execute(self): raise NotImplementedError() - + def unregister(self): try: bpy.types.SpaceView3D.draw_handler_remove( - self._handler, "WINDOW") + self._handler, "WINDOW") except: print("draw already unregistered") - + + class ClientUpdate(Draw): def __init__(self, client_uuid=None): assert(client_uuid) @@ -84,9 +92,8 @@ class ClientUpdate(Draw): super().__init__() def execute(self): - if hasattr(operators,"client") and self._client_uuid: + if hasattr(operators, "client") and self._client_uuid: client = operators.client.get(self._client_uuid) if client: client.pointer.update_location() - diff --git a/environment.py b/environment.py index be43f68..acdbb5f 100644 --- a/environment.py +++ b/environment.py @@ -39,27 +39,28 @@ DEFAULT_CONFIG = { } ORDERED_TYPES = [ - 'Image', - 'Texture', - 'Curve', - 'Material', - 'Light', - 'SunLight', - 'SpotLight', - 'AreaLight', - 'PointLight', - 'Camera', - 'Mesh', - 'Armature', - 'GreasePencil', - 'Object', - 'Action', - 'Collection', - 'Scene', + 'Image', + 'Texture', + 'Curve', + 'Material', + 'Light', + 'SunLight', + 'SpotLight', + 'AreaLight', + 'PointLight', + 'Camera', + 'Mesh', + 'Armature', + 'GreasePencil', + 'Object', + 'Action', + 'Collection', + 'Scene', ] rtypes = [] + def load_config(): import yaml @@ -71,6 +72,7 @@ def load_config(): return DEFAULT_CONFIG + def get_replicated_types(): config = load_config() rtpyes = config["replicated_types"] @@ -82,9 +84,10 @@ def get_replicated_types(): return tlist + def genererate_replicated_types(): rtypes.clear() - + cfg = load_config() replicated_types = cfg['replicated_types'] for t in ORDERED_TYPES: @@ -133,7 +136,6 @@ def setup(dependencies, python_path): PYTHON_PATH = Path(python_path) SUBPROCESS_DIR = PYTHON_PATH.parent - if not module_can_be_imported("pip"): install_pip() diff --git a/operators.py b/operators.py index 93c5c6c..6a20076 100644 --- a/operators.py +++ b/operators.py @@ -26,6 +26,7 @@ client = None delayables = [] ui_context = None + def add_datablock(datablock): global client child = [] @@ -35,16 +36,19 @@ def add_datablock(datablock): if hasattr(datablock, "materials"): for mat in datablock.materials: child.append(add_datablock(mat)) - if hasattr(datablock, "collection") and hasattr(datablock.collection, "children"): - for coll in datablock.collection.children: - child.append(add_datablock(coll)) + if hasattr(datablock, "collection") \ + and hasattr(datablock.collection, "children"): + for coll in datablock.collection.children: + child.append(add_datablock(coll)) if hasattr(datablock, "children"): for coll in datablock.children: child.append(add_datablock(coll)) if hasattr(datablock, "objects"): for obj in datablock.objects: child.append(add_datablock(obj)) - if hasattr(datablock,'uuid') and datablock.uuid and client.exist(datablock.uuid): + if hasattr(datablock, 'uuid') \ + and datablock.uuid \ + and client.exist(datablock.uuid): return datablock.uuid else: new_uuid = client.add(datablock, childs=child) @@ -62,7 +66,6 @@ def init_supported_datablocks(supported_types_id): add_datablock(item) - # OPERATORS class SessionStartOperator(bpy.types.Operator): bl_idname = "session.start" @@ -94,11 +97,17 @@ class SessionStartOperator(bpy.types.Operator): _type = getattr(bl_types, type) supported_bl_types.append(_type.bl_id) - bpy_factory.register_type(_type.bl_class, _type.bl_rep_class, timer=_type.bl_delay_refresh,automatic=True) - + bpy_factory.register_type( + _type.bl_class, + _type.bl_rep_class, + timer=_type.bl_delay_refresh, + automatic=True) + if _type.bl_delay_apply > 0: - delayables.append(delayable.ApplyTimer(timout=_type.bl_delay_apply,target_type=_type.bl_rep_class)) - + delayables.append(delayable.ApplyTimer( + timout=_type.bl_delay_apply, + target_type=_type.bl_rep_class)) + client = Client(factory=bpy_factory) if self.host: @@ -120,21 +129,22 @@ class SessionStartOperator(bpy.types.Operator): usr = presence.User( username=settings.username, color=(settings.client_color.r, - settings.client_color.g, - settings.client_color.b, - 1), + settings.client_color.g, + settings.client_color.b, + 1), ) - + settings.user_uuid = client.add(usr) - delayables.append(delayable.ClientUpdate(client_uuid=settings.user_uuid)) - - # Push all added values + delayables.append(delayable.ClientUpdate( + client_uuid=settings.user_uuid)) + + # Push all added values client.push() # Launch drawing module if settings.enable_presence: presence.renderer.run() - + for d in delayables: d.register() @@ -160,7 +170,7 @@ class SessionStopOperator(bpy.types.Operator): for d in delayables: d.unregister() - + presence.renderer.stop() return {"FINISHED"} @@ -216,8 +226,7 @@ class SessionPropertyRightOperator(bpy.types.Operator): global client if client: - client.right(self.key,settings.clients) - + client.right(self.key, settings.clients) return {"FINISHED"} @@ -247,8 +256,6 @@ class SessionSnapUserOperator(bpy.types.Operator): return {"CANCELLED"} - pass - class SessionApply(bpy.types.Operator): bl_idname = "session.apply" diff --git a/presence.py b/presence.py index 8ae496f..f212e61 100644 --- a/presence.py +++ b/presence.py @@ -13,10 +13,11 @@ from gpu_extras.batch import batch_for_shader # from .libs import debug # from .bl_types.bl_user import BlUser -# from .delayable import Draw +# from .delayable import Draw global renderer - + + def view3d_find(): for area in bpy.data.window_managers[0].windows[0].screen.areas: if area.type == 'VIEW_3D': @@ -74,7 +75,7 @@ def get_client_cam_points(): v6 = list(rv3d.view_location) v7 = get_target_far(region, rv3d, (width/2, height/2), -.8) - coords = [v1,v2,v3,v4,v5,v6,v7] + coords = [v1, v2, v3, v4, v5, v6, v7] return coords @@ -86,11 +87,12 @@ def get_client_2d(coords): else: return (0, 0) + class User(): - def __init__(self, username=None, color=(0,0,0,1)): + def __init__(self, username=None, color=(0, 0, 0, 1)): self.name = username self.color = color - self.location = [[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0]] + self.location = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] self.active_object = "" def update_location(self): @@ -100,10 +102,8 @@ class User(): current_coords = get_client_cam_points() if current_coords: self.location = list(current_coords) - - - def update_client_selected_object(self,context): + def update_client_selected_object(self, context): session = bpy.context.window_manager.session username = bpy.context.window_manager.session.username # client_data = client.get(client_key) @@ -121,8 +121,6 @@ class User(): elif client_data and client_data[0][1]['active_objects']: client_data[0][1]['active_objects'] = [] client.set(client_key, client_data[0][1]) - - class DrawFactory(object): @@ -136,12 +134,12 @@ class DrawFactory(object): self.coords = None self.active_object = None - def run(self): self.register_handlers() - + def stop(self): self.unregister_handlers() + def register_handlers(self): self.draw3d_handle = bpy.types.SpaceView3D.draw_handler_add( self.draw3d_callback, (), 'WINDOW', 'POST_VIEW') @@ -184,43 +182,39 @@ class DrawFactory(object): (0, 4), (1, 5), (2, 6), (3, 7) ) - if select_ob in bpy.data.objects.keys(): ob = bpy.data.objects[select_ob] else: return - bbox_corners = [ob.matrix_world @ mathutils.Vector(corner) for corner in ob.bound_box] + bbox_corners = [ob.matrix_world @ mathutils.Vector( + corner) for corner in ob.bound_box] coords = [(point.x, point.y, point.z) - for point in bbox_corners] - + for point in bbox_corners] shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR') - color = client['color'] - batch = batch_for_shader( shader, 'LINES', {"pos": coords}, indices=indices) + drawable_key = "{}/{}".format(client['id'], select_ob) - self.d3d_items["{}/{}".format(client['id'], - select_ob)] = (shader, batch, color) - else: - pass - - def draw_client_camera(self,client_uuid, client_location, client_color): + self.d3d_items[drawable_key] = (shader, batch, color) + + def draw_client_camera(self, client_uuid, client_location, client_color): if client_location: local_username = bpy.context.window_manager.session.username try: indices = ( - (1, 3), (2, 1), (3, 0), (2, 0),(4,5),(1, 6), (2, 6), (3, 6), (0, 6) + (1, 3), (2, 1), (3, 0), + (2, 0), (4, 5), (1, 6), + (2, 6), (3, 6), (0, 6) ) shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR') position = [tuple(coord) for coord in client_location] color = client_color - batch = batch_for_shader( shader, 'LINES', {"pos": position}, indices=indices) @@ -237,7 +231,7 @@ class DrawFactory(object): shader.bind() shader.uniform_float("color", color) batch.draw(shader) - except Exception as e: + except Exception: print("3D Exception") def draw2d_callback(self): @@ -251,9 +245,10 @@ class DrawFactory(object): blf.color(0, color[0], color[1], color[2], color[3]) blf.draw(0, font) - except Exception as e: + except Exception: print("2D EXCEPTION") + def register(): global renderer renderer = DrawFactory() @@ -263,4 +258,4 @@ def unregister(): global renderer renderer.unregister_handlers() - del renderer \ No newline at end of file + del renderer diff --git a/ui.py b/ui.py index 17319c8..cd7ebe5 100644 --- a/ui.py +++ b/ui.py @@ -1,15 +1,16 @@ import bpy from . import operators -from .libs.replication.constants import * +from .libs.replication.constants import FETCHED, ERROR from .bl_types.bl_user import BlUser -PROP_STATES = [ 'KEYTYPE_BREAKDOWN_VEC', - 'KEYTYPE_BREAKDOWN_VEC', - 'KEYTYPE_KEYFRAME_VEC', - 'KEYTYPE_KEYFRAME_VEC', - 'KEYTYPE_JITTER_VEC', - 'KEYTYPE_KEYFRAME_VEC'] +PROP_STATES = ['KEYTYPE_BREAKDOWN_VEC', + 'KEYTYPE_BREAKDOWN_VEC', + 'KEYTYPE_KEYFRAME_VEC', + 'KEYTYPE_KEYFRAME_VEC', + 'KEYTYPE_JITTER_VEC', + 'KEYTYPE_KEYFRAME_VEC'] + class SESSION_PT_settings(bpy.types.Panel): """Settings panel""" @@ -22,40 +23,37 @@ class SESSION_PT_settings(bpy.types.Panel): def draw_header(self, context): self.layout.label(text="", icon='TOOL_SETTINGS') - def draw(self, context): layout = self.layout layout.use_property_split = True - row = layout.row() - if hasattr(context.window_manager, 'session'): - settings = context.window_manager.session - window_manager = context.window_manager + if hasattr(context.window_manager, 'session'): # STATE INITIAL - if not operators.client or (operators.client and operators.client.state == 0): + if not operators.client \ + or (operators.client and operators.client.state == 0): pass # REPLICATION SETTINGS # row = layout.row() # box = row.box() # row = box.row() # row.label(text="REPLICATION", icon='TRIA_RIGHT') - # row = box.row() - + # row = box.row() + # for item in window_manager.session.supported_datablock: # row.label(text=item.type_name,icon=ICONS[item.type_name]) - # row.prop(item, "is_replicated", text="") + # row.prop(item, "is_replicated", text="") # row = box.row() else: - # STATE ACTIVE - if operators.client.state == 2: - + # STATE ACTIVE + if operators.client.state == 2: + row = layout.row() row.operator("session.stop", icon='QUIT', text="Exit") row = layout.row() # STATE SYNCING - else: + else: status = "connecting..." row.label(text=status) row = layout.row() @@ -69,15 +67,17 @@ class SESSION_PT_settings_network(bpy.types.Panel): bl_region_type = 'UI' bl_category = "Multiuser" bl_parent_id = 'MULTIUSER_SETTINGS_PT_panel' + @classmethod def poll(cls, context): - return not operators.client or (operators.client and operators.client.state == 0) - + return not operators.client \ + or (operators.client and operators.client.state == 0) + def draw(self, context): layout = self.layout settings = context.window_manager.session - scene = context.window_manager + row = layout.row() # USER SETTINGS row.label(text="draw overlay:") @@ -86,7 +86,7 @@ class SESSION_PT_settings_network(bpy.types.Panel): row.label(text="clear blend:") row.prop(settings, "start_empty", text="") row = layout.row() - + row = layout.row() row.prop(settings, "session_mode", expand=True) row = layout.row() @@ -106,7 +106,6 @@ class SESSION_PT_settings_network(bpy.types.Panel): row.label(text="port:") row.prop(settings, "port", text="") row = box.row() - row = box.row() row.operator("session.start", text="CONNECT").host = False @@ -119,21 +118,23 @@ class SESSION_PT_settings_user(bpy.types.Panel): bl_region_type = 'UI' bl_category = "Multiuser" bl_parent_id = 'MULTIUSER_SETTINGS_PT_panel' + @classmethod def poll(cls, context): - return not operators.client or (operators.client and operators.client.state == 0) - + return not operators.client \ + or (operators.client and operators.client.state == 0) + def draw(self, context): layout = self.layout settings = context.window_manager.session - scene = context.window_manager + row = layout.row() # USER SETTINGS row.prop(settings, "username", text="id") - + row = layout.row() - row.prop(settings, "client_color", text="color") + row.prop(settings, "client_color", text="color") row = layout.row() @@ -144,44 +145,45 @@ class SESSION_PT_user(bpy.types.Panel): bl_region_type = 'UI' bl_category = "Multiuser" bl_parent_id = 'MULTIUSER_SETTINGS_PT_panel' + @classmethod def poll(cls, context): - return operators.client and operators.client.state == 2 - + return operators.client and operators.client.state == 2 def draw(self, context): layout = self.layout settings = context.window_manager.session - scene = context.window_manager + # Create a simple row. col = layout.column(align=True) - + client_keys = operators.client.list(filter=BlUser) if client_keys and len(client_keys) > 0: for key in client_keys: - area_msg = col.row(align = True) + area_msg = col.row(align=True) item_box = area_msg.box() client = operators.client.get(key).buffer - pointer = operators.client.get(key).pointer + info = "" - - detail_item_row = item_box.row(align = True) + + detail_item_row = item_box.row(align=True) username = client['name'] + is_local_user = username == settings.username - is_local_user = username == settings.username - - if is_local_user: + if is_local_user: info = "(self)" - + detail_item_row.label( text="{} {}".format(username, info)) - + if not is_local_user: detail_item_row.operator( - "session.snapview", text="", icon='VIEW_CAMERA').target_client = key + "session.snapview", + text="", + icon='VIEW_CAMERA').target_client = key row = layout.row() else: row.label(text="Empty") @@ -189,14 +191,14 @@ class SESSION_PT_user(bpy.types.Panel): row = layout.row() -def draw_property(context,parent,property_uuid, level=0): +def draw_property(context, parent, property_uuid, level=0): settings = context.window_manager.session item = operators.client.get(property_uuid) - + if item.str_type == 'BlUser' or item.state == ERROR: return - area_msg = parent.row(align = True) + area_msg = parent.row(align=True) if level > 0: for i in range(level): area_msg.label(text="") @@ -204,21 +206,25 @@ def draw_property(context,parent,property_uuid, level=0): name = item.buffer['name'] - detail_item_box = line.row(align = True) + detail_item_box = line.row(align=True) if item.state == FETCHED: - detail_item_box.operator("session.apply",text="", icon=PROP_STATES[item.state]).target = item.uuid + detail_item_box.operator( + "session.apply", + text="", + icon=PROP_STATES[item.state]).target = item.uuid else: detail_item_box.label(text="", icon=PROP_STATES[item.state]) - detail_item_box.label(text="",icon=item.icon) + detail_item_box.label(text="", icon=item.icon) detail_item_box.label(text="{} ".format(name)) - + right_icon = "DECORATE_UNLOCKED" if item.owner != settings.username: - right_icon="DECORATE_LOCKED" - - ro = detail_item_box.operator("session.right", text="", icon=right_icon, emboss=settings.is_admin) + right_icon = "DECORATE_LOCKED" + + ro = detail_item_box.operator( + "session.right", text="", icon=right_icon, emboss=settings.is_admin) ro.key = property_uuid detail_item_box.operator( @@ -234,21 +240,19 @@ class SESSION_PT_outliner(bpy.types.Panel): @classmethod def poll(cls, context): - return operators.client and operators.client.state == 2 + return operators.client and operators.client.state == 2 def draw_header(self, context): self.layout.label(text="", icon='OUTLINER_OB_GROUP_INSTANCE') - + def draw(self, context): layout = self.layout - - - if hasattr(context.window_manager,'session'): + + if hasattr(context.window_manager, 'session'): settings = context.window_manager.session - scene = context.window_manager row = layout.row() - row.prop(settings,'outliner_filter', text="") + row.prop(settings, 'outliner_filter', text="") row = layout.row(align=True) # Property area @@ -258,8 +262,8 @@ class SESSION_PT_outliner(bpy.types.Panel): if client_keys and len(client_keys) > 0: col = layout.column(align=True) for key in client_keys: - draw_property(context,col,key) - + draw_property(context, col, key) + else: col.label(text="Empty")