I have a rotated and scaled cube (on all axis) with the rotation and scale applied. For example:
As I don't know the original rotation and scale, using Python I'd like to align the cube along the global x,y & z axis. For example, the desired result would be:
For my test I've created a randomly rotated and scaled cube:
import bpy, random
bpy.ops.mesh.primitive_cube_add(size=1)
cube = bpy.context.active_object
cube.rotation_euler = (
random.uniform(-100,100),
random.uniform(-100,100),
random.uniform(-100,100)
)
cube.scale = (
random.uniform(.5,1.5),
random.uniform(.5,1.5),
random.uniform(.5,1.5)
)
# I won't know the rotation or scale before they were applied
bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)
To align the cube, I've managed to get almost there using the following technique:
mesh_data = cube.data
for edge in mesh_data.edges:
#Get the vertex indices from the edge
vertex_index_1, vertex_index_2 = edge.vertices
#Actual edge vetrices
vertex_co_1 = mesh_data.vertices[vertex_index_1].co
vertex_co_2 = mesh_data.vertices[vertex_index_2].co
#Calculate a direction from the vertices
edge_direction = (vertex_co_2 - vertex_co_1)
edge_direction.normalize()
#Get a rotation from the direction
rotation_matrix = edge_direction.to_track_quat('Z', 'Y').to_matrix().to_4x4()
#Transpose
rotation_matrix_transposed = rotation_matrix.transposed()
#Apply
cube.matrix_world = rotation_matrix_transposed
bpy.context.view_layer.update()
break
However, this only aligns one of the faces along one of the axis. Hoping someone can spot the problem!