]> git.tdb.fi Git - libs/gl.git/blobdiff - blender/io_mspgl/scene.py
Refactor scene data preparation to its own class
[libs/gl.git] / blender / io_mspgl / scene.py
diff --git a/blender/io_mspgl/scene.py b/blender/io_mspgl/scene.py
new file mode 100644 (file)
index 0000000..079647c
--- /dev/null
@@ -0,0 +1,64 @@
+def is_same_object(obj1, obj2):
+       if obj1.data.name!=obj2.data.name:
+               return False
+       if any(m1.name!=m2.name for m1, m2 in zip(obj1.material_slots, obj2.material_slots)):
+               return False
+
+       return True
+
+class Instance:
+       def __init__(self, obj, prototype):
+               self.name = obj.name
+               self.matrix_world = obj.matrix_world
+               self.rotation_mode = obj.rotation_mode
+               self.prototype = prototype.name
+
+class Scene:
+       def __init__(self, scene, obj_filter=None):
+               self.name = scene.name
+               self.scene_type = scene.scene_type
+               self.prototypes = []
+               self.instances = []
+
+               objects = [o for o in scene.objects if o.type=='MESH']
+               objects.sort(key=lambda o:o.name)
+               if obj_filter:
+                       objects = list(filter(obj_filter, objects))
+
+               processed = set()
+               for o in objects:
+                       if o.name in processed:
+                               continue
+
+                       clones = [c for c in objects if is_same_object(o, c)]
+                       self.prototypes.append(o)
+                       for c in clones:
+                               self.instances.append(Instance(c, o))
+                               processed.add(c.name)
+
+def get_all_collections(collection):
+       result = [collection]
+       for c in collection.children:
+               result += get_all_collections(c)
+       return result
+
+def create_scene_from_current(context, *, selected_only=False, visible_only=True):
+       obj_filters = []
+
+       if selected_only:
+               obj_filters.append(lambda o: o.select_get())
+
+       if visible_only:
+               visible_names = set()
+               for c in get_all_collections(context.view_layer.layer_collection):
+                       if not c.hide_viewport and not c.collection.hide_viewport:
+                               visible_names.update(o.name for o in c.collection.objects)
+               obj_filters.append(lambda o: o.name in visible_names)
+
+       obj_filter = None
+       if len(obj_filters)==1:
+               obj_filter = obj_filters[0]
+       if obj_filters:
+               obj_filter = lambda o: all(f(o) for f in obj_filters)
+
+       return Scene(context.scene, obj_filter)