Skip to content

Commit 0b399c0

Browse files
committed
Fixed 'Separate and Align Cubes' operator. Close #128:
Before this fix the operator only worked for non-rotated and non-scaled objects without parents. Also the operator could randomly move the children of the object. Now it should work in all cases as expected.
1 parent 028081d commit 0b399c0

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

mcblend/operator_func/__init__.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
import bpy
1313
from bpy.types import Image, Material, Context, Object, Armature, Mesh
14+
from mathutils import Matrix
1415
import numpy as np
1516

1617
from .typed_bpy_access import (
@@ -343,9 +344,20 @@ def separate_mesh_cubes(context: Context):
343344
for obj in context.selected_objects:
344345
if obj.type != 'MESH':
345346
continue
347+
# Remember the original world matrices of children
348+
child_matrices: Dict[str, Matrix] = {}
349+
for child in obj.children:
350+
child_matrices[child.name] = child.matrix_world.copy()
351+
# Apply all transformations
346352
apply_obj_transform_keep_origin(obj)
347353
bpy.context.view_layer.update()
348354
fix_cube_rotation(obj)
355+
356+
# Restore the original world matrices of children
357+
for child in obj.children:
358+
bpy.context.view_layer.update()
359+
child.matrix_world = child_matrices[child.name]
360+
bpy.context.view_layer.update()
349361
return edited_objects
350362

351363
def inflate_objects(

mcblend/operator_func/common.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -911,16 +911,20 @@ def apply_obj_transform_keep_origin(obj: Object):
911911
# This assert should never raise an Exception
912912
assert isinstance(obj.data, Mesh), "The object is not a Mesh"
913913
# Decompose object transformations
914-
_, rot, scl = obj.matrix_local.decompose()
915-
# loc_mat = Matrix.Translation(loc)
914+
loc, rot, scl = obj.matrix_local.decompose()
915+
loc_mat = Matrix.Translation(loc)
916916
rot_mat = rot.to_matrix().to_4x4()
917917
scl_mat = (
918918
Matrix.Scale(scl[0], 4, Vector([1,0,0])) @
919919
Matrix.Scale(scl[1], 4, Vector([0,1,0])) @
920920
Matrix.Scale(scl[2], 4, Vector([0,0,1]))
921921
)
922+
# Edit the matrix_local to only have the location
923+
obj.matrix_local = loc_mat
924+
# Apply the rotation and scale to individual vertices, since now
925+
# the matrix_local is only the location
922926
for vertex in obj.data.vertices:
923-
vertex.co = (rot_mat @ scl_mat) @ vertex.co
927+
vertex.co = rot_mat @ scl_mat @ vertex.co
924928

925929
def fix_cube_rotation(obj: Object):
926930
'''

0 commit comments

Comments
 (0)