Page MenuHome

Python: obj.parent = new_parent_obj, clears obj.matrix_parent_inverse for no reason.
Closed, ArchivedPublic

Description

I want to change object parent form Cube to Suzane, so that it won't move (matrix_basis, and matrix_world should be the same).
We search for new obj.matrix_parent_inverse2, in code below. It should work (proof on bottom), but last line clears new obj.matrix_parent_inverse

def set_new_parent_bug(obj, new_parent):
     new_m_p_inv = new_parent.matrix_world.inverted() * obj.parent.matrix_world * obj.matrix_parent_inverse
     obj.matrix_parent_inverse = new_m_p_inv
     obj.parent = new_parent # this clears m_parent_inv !! BUG?

In blend file I have script with broken function set_new_parent_bug(), and workaround function set_new_parent() that backups obj.matrix_parent_inverse, so that after changing parent and it being cleared to Identity Matrix, we can still use backup for calculation of new matrix_parent_inverse (for new parent)


But affects both blender 2.8 and 2.79
In short using obj.parent = xxx, should not clear obj.matrix_parent_inverse

And below proof that the math is valid (we search for new matrix_parent_inverse so that objects stays in place).
mat_world should be same with old parent and new parent

old_m_w == new_m_w
old_parent_m_w @ obj.m_p_inv1 @ obj.m_basis  ==  new_parent_m_w @ **obj.m_p_inv2** @ obj.m_basis
new_parent_m_w.inv() @ old_parent_m_w @ obj.m_p_inv1 @ obj.m_basis  ==  new_parent_m_w.inv() @ new_parent_m_w @ **obj.m_p_inv2** @ obj.m_basis
new_parent_m_w.inv() @ old_parent_m_w @ obj.m_p_inv1   ==   **obj.m_p_inv2**

Event Timeline

Brecht Van Lommel (brecht) changed the task status from Unknown Status to Unknown Status.Mar 11 2019, 2:40 PM
Brecht Van Lommel (brecht) claimed this task.

You can manually set matrix_parent_inverse to the old value if you need to, but I don't think preserving is the most commonly useful behavior.

Even if we did want to change it, it would break backward compatibility and I don't think it's worth it.

Might be misunderstanding, but if you only want to change parent without moving, why not just do something like:

obj.parent = new_parent
obj.matrix_parent_inverse = new_parent.matrix_world.inverted()

@Philipp Oeser (lichtwerk), this will work only if for old parent:
obj.matrix_parent_inverse would be same as obj.parent.matrix_world.inverted() (which is true only at time of parenting, as long as we don't move parent).
then obj.matrix_parent_inverse * obj.parent.matrix_world == Identity Matrix. And obj.m_w == basically obj.matrix_basis
But as soon as we move obj.parent, then above equation wont give you identity matrix, and obj.matrix_world will change (child will follow change of parent obj transform).
To test you can open blend file attached to task, and before running the script offset first parent object (cube). You will see, that with your method child object won't stay in one place.