reformat: code cleanup

This commit is contained in:
Swann Martinez 2019-05-02 17:58:37 +02:00
parent 824c70eaff
commit c1119976cd
No known key found for this signature in database
GPG Key ID: 414CCAFD8DA720E1
3 changed files with 71 additions and 116 deletions

View File

@ -1,25 +1,22 @@
import binascii import binascii
import collections import collections
import copy
import logging import logging
import os import os
import queue
import sys import sys
import threading import threading
import time import time
from enum import Enum from enum import Enum
from random import randint from random import randint
import copy
import queue from . import draw, helpers, message
from .libs import dump_anything, umsgpack, zmq
# import zmq # import zmq
lock = threading.Lock() lock = threading.Lock()
from .libs import umsgpack
from .libs import zmq
from .libs import dump_anything
from . import helpers
from . import message
from . import draw
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -487,4 +484,3 @@ def serial_worker(product, feed):
elif command == 'LOAD': elif command == 'LOAD':
if value: if value:
helpers.load(key, value) helpers.load(key, value)

View File

@ -1,10 +1,12 @@
import bpy
import sys
import mathutils
from .libs import dump_anything
from uuid import uuid4
import logging import logging
import sys
from uuid import uuid4
import bpy
import mathutils
from . import draw from . import draw
from .libs import dump_anything
CORRESPONDANCE = {'Collection': 'collections', 'Mesh': 'meshes', 'Object': 'objects', 'Material': 'materials', CORRESPONDANCE = {'Collection': 'collections', 'Mesh': 'meshes', 'Object': 'objects', 'Material': 'materials',
'Texture': 'textures', 'Scene': 'scenes', 'Light': 'lights', 'Camera': 'cameras', 'Action': 'actions', 'Armature': 'armatures', 'Grease Pencil': 'grease_pencils'} 'Texture': 'textures', 'Scene': 'scenes', 'Light': 'lights', 'Camera': 'cameras', 'Action': 'actions', 'Armature': 'armatures', 'Grease Pencil': 'grease_pencils'}
@ -15,6 +17,8 @@ SUPPORTED_TYPES = ['Material',
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# UTILITY FUNCTIONS # UTILITY FUNCTIONS
def refresh_window(): def refresh_window():
import bpy import bpy
bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1) bpy.ops.wm.redraw_timer(type='DRAW_WIN_SWAP', iterations=1)
@ -28,23 +32,26 @@ def get_selected_objects(scene):
return selected_objects return selected_objects
def get_all_datablocks(): def get_all_datablocks():
datas = [] datas = []
for datatype in SUPPORTED_TYPES: for datatype in SUPPORTED_TYPES:
for item in getattr(bpy.data, CORRESPONDANCE[datatype]): for item in getattr(bpy.data, CORRESPONDANCE[datatype]):
item.id= bpy.context.scene.session_settings.username item.id = bpy.context.scene.session_settings.username
datas.append("{}/{}".format(datatype, item.name)) datas.append("{}/{}".format(datatype, item.name))
return datas return datas
# LOAD HELPERS # LOAD HELPERS
def load(key, value): def load(key, value):
target = resolve_bpy_path(key) target = resolve_bpy_path(key)
target_type = key.split('/')[0] target_type = key.split('/')[0]
if value == "None": if value == "None":
return return
if target_type == 'Object': if target_type == 'Object':
load_object(target=target, data=value, load_object(target=target, data=value,
create=True) create=True)
@ -94,25 +101,10 @@ def load_client(client=None, data=None):
D = bpy.data D = bpy.data
net_settings = C.scene.session_settings net_settings = C.scene.session_settings
if client and data: if client and data:
if net_settings.enable_draw: if net_settings.enable_draw:
draw.renderer.draw_client(data) draw.renderer.draw_client(data)
draw.renderer.draw_client_selected_objects(data) draw.renderer.draw_client_selected_objects(data)
# localy_selected = get_selected_objects(C.scene)
# Draw client
# Load selected object
# for obj in C.scene.objects:
# if obj.id == client:
# D.objects[obj.name].hide_select = True
# else:
# D.objects[obj.name].hide_select = False
# if client_data['active_objects'] and obj.name in client_data['active_objects']:
# D.objects[obj.name].hide_select = True
# else:
# D.objects[obj.name].hide_select = False
def load_mesh(target=None, data=None, create=False): def load_mesh(target=None, data=None, create=False):
@ -179,7 +171,7 @@ def load_object(target=None, data=None, create=False):
target.matrix_world = mathutils.Matrix(data["matrix_world"]) target.matrix_world = mathutils.Matrix(data["matrix_world"])
target.id = data['id'] target.id = data['id']
client = bpy.context.scene.session_settings.username client = bpy.context.scene.session_settings.username
if target.id == client: if target.id == client:
@ -206,13 +198,13 @@ def load_collection(target=None, data=None, create=False):
for object in target.objects.keys(): for object in target.objects.keys():
if object not in data["objects"]: if object not in data["objects"]:
target.objects.unlink(bpy.data.objects[object]) target.objects.unlink(bpy.data.objects[object])
# Link childrens # Link childrens
for collection in data["children"]: for collection in data["children"]:
if collection not in target.children.keys(): if collection not in target.children.keys():
target.children.link( target.children.link(
bpy.data.collections[collection]) bpy.data.collections[collection])
target.id = data['id'] target.id = data['id']
except Exception as e: except Exception as e:
logger.error("Collection loading error: {}".format(e)) logger.error("Collection loading error: {}".format(e))
@ -288,9 +280,9 @@ def load_material(target=None, data=None, create=False):
for link in data["node_tree"]["links"]: for link in data["node_tree"]["links"]:
current_link = data["node_tree"]["links"][link] current_link = data["node_tree"]["links"][link]
input_socket = target.node_tree.nodes[current_link['to_node'] input_socket = target.node_tree.nodes[current_link['to_node']
['name']].inputs[current_link['to_socket']['name']] ['name']].inputs[current_link['to_socket']['name']]
output_socket = target.node_tree.nodes[current_link['from_node'] output_socket = target.node_tree.nodes[current_link['from_node']
['name']].outputs[current_link['from_socket']['name']] ['name']].outputs[current_link['from_socket']['name']]
target.node_tree.links.new(input_socket, output_socket) target.node_tree.links.new(input_socket, output_socket)
@ -354,7 +346,6 @@ def load_light(target=None, data=None, create=False, type=None):
if target is None and create: if target is None and create:
target = bpy.data.lights.new(data["name"], data["type"]) target = bpy.data.lights.new(data["name"], data["type"])
dump_anything.load(target, data) dump_anything.load(target, data)
target.id = data['id'] target.id = data['id']
@ -374,30 +365,32 @@ def load_default(target=None, data=None, create=False, type=None):
logger.error("default loading error {}".format(e)) logger.error("default loading error {}".format(e))
# DUMP HELPERS # DUMP HELPERS
def dump(key): def dump(key):
target = resolve_bpy_path(key) target = resolve_bpy_path(key)
target_type = key.split('/')[0] target_type = key.split('/')[0]
data = None data = None
if target_type == 'Material': if target_type == 'Material':
data = dump_datablock_attibute(target, ['name', 'node_tree','id'], 7) data = dump_datablock_attibute(target, ['name', 'node_tree', 'id'], 7)
elif target_type == 'Grease Pencil': elif target_type == 'Grease Pencil':
data = dump_datablock_attibute( data = dump_datablock_attibute(
target, ['name', 'layers', 'materials','id'], 9) target, ['name', 'layers', 'materials', 'id'], 9)
elif target_type == 'Camera': elif target_type == 'Camera':
data = dump_datablock(target, 1) data = dump_datablock(target, 1)
elif target_type == 'Light': elif target_type == 'Light':
data = dump_datablock(target, 1) data = dump_datablock(target, 1)
elif target_type == 'Mesh': elif target_type == 'Mesh':
data = dump_datablock_attibute( data = dump_datablock_attibute(
target, ['name', 'polygons', 'edges', 'vertices','id'], 6) target, ['name', 'polygons', 'edges', 'vertices', 'id'], 6)
elif target_type == 'Object': elif target_type == 'Object':
data = dump_datablock(target, 1) data = dump_datablock(target, 1)
elif target_type == 'Collection': elif target_type == 'Collection':
data = dump_datablock(target, 4) data = dump_datablock(target, 4)
elif target_type == 'Scene': elif target_type == 'Scene':
data = dump_datablock_attibute(target,['name','collection','id','camera','grease_pencil'], 4) data = dump_datablock_attibute(
target, ['name', 'collection', 'id', 'camera', 'grease_pencil'], 4)
return data return data

View File

@ -1,21 +1,22 @@
import asyncio
import logging import logging
import os
import queue
import random import random
import string import string
import time
import asyncio
import queue
from operator import itemgetter
import subprocess import subprocess
import time
from operator import itemgetter
import bgl import bgl
import blf import blf
import bpy import bpy
import os
import gpu import gpu
import mathutils import mathutils
from bpy_extras import view3d_utils from bpy_extras import view3d_utils
from gpu_extras.batch import batch_for_shader from gpu_extras.batch import batch_for_shader
from . import client, ui, draw, helpers from . import client, draw, helpers, ui
from .libs import umsgpack from .libs import umsgpack
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -37,7 +38,7 @@ SUPPORTED_TYPES = ['Material',
def client_list_callback(scene, context): def client_list_callback(scene, context):
global client_keys global client_keys
items = [] items = []
if client_keys: if client_keys:
for k in client_keys: for k in client_keys:
@ -98,53 +99,22 @@ def update_selected_object(context):
username = bpy.context.scene.session_settings.username username = bpy.context.scene.session_settings.username
client_key = "Client/{}".format(username) client_key = "Client/{}".format(username)
client_data = client_instance.get(client_key) client_data = client_instance.get(client_key)
selected_objects = helpers.get_selected_objects(context.scene) selected_objects = helpers.get_selected_objects(context.scene)
if len(selected_objects) > 0: if len(selected_objects) > 0:
for obj in selected_objects: for obj in selected_objects:
# if obj not in client_data[0][1]['active_objects']: # if obj not in client_data[0][1]['active_objects']:
client_data[0][1]['active_objects'] = selected_objects client_data[0][1]['active_objects'] = selected_objects
client_instance.set(client_key,client_data[0][1]) client_instance.set(client_key, client_data[0][1])
break break
elif client_data and client_data[0][1]['active_objects']: elif client_data and client_data[0][1]['active_objects']:
client_data[0][1]['active_objects'] = [] client_data[0][1]['active_objects'] = []
client_instance.set(client_key,client_data[0][1]) client_instance.set(client_key, client_data[0][1])
# for update in local_updates:
# client_instance.get('')
# if session.active_object is not context.selected_objects[0] or session.active_object.is_evaluated:
# session.active_object = context.selected_objects[0]
# key = "net/objects/{}".format(client_instance.id.decode())
# data = {}
# data['color'] = [session.client_instance_color.r,
# session.client_instance_color.g, session.client_instance_color.b]
# data['object'] = session.active_object.name
# client_instance.push_update(
# key, 'client_instanceObject', data)
# return True
# elif len(context.selected_objects) == 0 and session.active_object:
# session.active_object = None
# data = {}
# data['color'] = [session.client_instance_color.r,
# session.client_instance_color.g, session.client_instance_color.b]
# data['object'] = None
# key = "net/objects/{}".format(client_instance.id.decode())
# client_instance.push_update(key, 'client_instanceObject', data)
# return True
# return False
def init_datablocks(): def init_datablocks():
@ -152,7 +122,7 @@ def init_datablocks():
for datatype in SUPPORTED_TYPES: for datatype in SUPPORTED_TYPES:
for item in getattr(bpy.data, helpers.CORRESPONDANCE[datatype]): for item in getattr(bpy.data, helpers.CORRESPONDANCE[datatype]):
item.id= bpy.context.scene.session_settings.username item.id = bpy.context.scene.session_settings.username
key = "{}/{}".format(datatype, item.name) key = "{}/{}".format(datatype, item.name)
client_instance.set(key) client_instance.set(key)
@ -160,35 +130,31 @@ def init_datablocks():
def default_tick(): def default_tick():
bpy.ops.session.refresh() bpy.ops.session.refresh()
upload_client_instance_position() upload_client_instance_position()
# global client_instance
# if not client_instance.queue.empty():
# update = client_instance.queue.get()
# helpers.load(update[0],update[1])
return 1 return 1
def sync(): def sync():
global client_instance global client_instance
if client_instance: if client_instance:
for datatype in SUPPORTED_TYPES: for datatype in SUPPORTED_TYPES:
for item in getattr(bpy.data, helpers.CORRESPONDANCE[datatype]): for item in getattr(bpy.data, helpers.CORRESPONDANCE[datatype]):
if item.id == 'None': if item.id == 'None':
item.id= bpy.context.scene.session_settings.username item.id = bpy.context.scene.session_settings.username
key = "{}/{}".format(datatype, item.name) key = "{}/{}".format(datatype, item.name)
client_instance.add(key) client_instance.add(key)
return .2 return .2
def register_ticks(): def register_ticks():
# REGISTER Updaters # REGISTER Updaters
bpy.app.timers.register(sync) bpy.app.timers.register(sync)
bpy.app.timers.register(default_tick) bpy.app.timers.register(default_tick)
pass pass
def unregister_ticks(): def unregister_ticks():
# REGISTER Updaters # REGISTER Updaters
bpy.app.timers.unregister(sync) bpy.app.timers.unregister(sync)
@ -196,6 +162,8 @@ def unregister_ticks():
pass pass
# OPERATORS # OPERATORS
class session_join(bpy.types.Operator): class session_join(bpy.types.Operator):
bl_idname = "session.join" bl_idname = "session.join"
@ -251,17 +219,17 @@ class session_refresh(bpy.types.Operator):
return True return True
def execute(self, context): def execute(self, context):
global client_instance, client_keys,client_state global client_instance, client_keys, client_state
keys = client_instance.list() keys = client_instance.list()
if keys: if keys:
client_keys= keys client_keys = keys
state = client_instance.state() state = client_instance.state()
if state: if state:
client_state = state client_state = state
return {"FINISHED"} return {"FINISHED"}
@ -373,7 +341,6 @@ class session_stop(bpy.types.Operator):
net_settings = context.scene.session_settings net_settings = context.scene.session_settings
if server: if server:
server.kill() server.kill()
time.sleep(0.25) time.sleep(0.25)
@ -417,9 +384,7 @@ class session_rights(bpy.types.Operator):
net_settings = context.scene.session_settings net_settings = context.scene.session_settings
col = layout.column() col = layout.column()
col.prop(net_settings,"clients") col.prop(net_settings, "clients")
def execute(self, context): def execute(self, context):
global server global server
@ -430,11 +395,11 @@ class session_rights(bpy.types.Operator):
if net_settings.is_admin: if net_settings.is_admin:
val = client_instance.get(self.key) val = client_instance.get(self.key)
val[0][1]['id'] = net_settings.clients val[0][1]['id'] = net_settings.clients
client_instance.set(key=self.key, value=val[0][1],override=True)
print("Updating {} rights to {}".format(self.key,net_settings.clients)) client_instance.set(key=self.key, value=val[0][1], override=True)
print("Updating {} rights to {}".format(
self.key, net_settings.clients))
else: else:
print("Not admin") print("Not admin")
@ -474,8 +439,10 @@ class session_settings(bpy.types.PropertyGroup):
name="clients", name="clients",
description="client enum", description="client enum",
items=client_list_callback items=client_list_callback
) )
enable_draw = bpy.props.BoolProperty(name="enable_draw", description='Enable overlay drawing module', default=True) enable_draw = bpy.props.BoolProperty(
name="enable_draw", description='Enable overlay drawing module', default=True)
class session_snapview(bpy.types.Operator): class session_snapview(bpy.types.Operator):
bl_idname = "session.snapview" bl_idname = "session.snapview"
@ -498,7 +465,7 @@ class session_snapview(bpy.types.Operator):
if client: if client:
rv3d.view_location = client[0][1]['location'][0] rv3d.view_location = client[0][1]['location'][0]
rv3d.view_distance = 30.0 rv3d.view_distance = 30.0
return {"FINISHED"} return {"FINISHED"}
return {"CANCELLED"} return {"CANCELLED"}
@ -527,7 +494,7 @@ def ordered(updates):
for item in updates.items(): for item in updates.items():
if item[1].id.bl_rna.name in SUPPORTED_TYPES: if item[1].id.bl_rna.name in SUPPORTED_TYPES:
uplist.append((SUPPORTED_TYPES.index( uplist.append((SUPPORTED_TYPES.index(
item[1].id.bl_rna.name), item[1].id.bl_rna.name, item[1].id.name,item[1].id )) item[1].id.bl_rna.name), item[1].id.bl_rna.name, item[1].id.name, item[1].id))
uplist.sort(key=itemgetter(0)) uplist.sort(key=itemgetter(0))
return uplist return uplist
@ -553,7 +520,6 @@ def depsgraph_update(scene):
username = bpy.context.scene.session_settings.username username = bpy.context.scene.session_settings.username
update_selected_object(bpy.context) update_selected_object(bpy.context)
selected_objects = helpers.get_selected_objects(scene) selected_objects = helpers.get_selected_objects(scene)
if len(selected_objects) > 0: if len(selected_objects) > 0:
for updated_data in updates: for updated_data in updates:
@ -601,8 +567,8 @@ def unregister():
unregister_class(cls) unregister_class(cls)
del bpy.types.Scene.session_settings del bpy.types.Scene.session_settings
del bpy.types.ID.id del bpy.types.ID.id
if __name__ == "__main__": if __name__ == "__main__":
register() register()