Simple but wrong code to export bone matrix

I use this simple python script to export bones transformation into my JS 3D engine (www.babylonjs.com)

bones = armature.pose.bones
# for eaach bone in bones
SystemMatrix = Matrix.Scale(-1, 4, Vector((0, 0, 1))) * Matrix.Rotation(radians(-90), 4, 'X')
if (bone.parent):
  Export_babylon.write_matrix4(file_handler, "matrix", bone.parent.matrix.inverted() * bone.matrix)
else:
  Export_babylon.write_matrix4(file_handler, "matrix", SystemMatrix * bone.matrix)

I’m using a left handed Y up system but I should forget something about rotation because the result is not correct :frowning:



Original version under Blender:

Ok I found the solution :slight_smile:
For those who have the same question here is the final exportation code:

def export_bone_matrix(armature, bone, label, file_handler):
        SystemMatrix = Matrix.Scale(-1, 4, Vector((0, 0, 1))) * Matrix.Rotation(radians(-90), 4, 'X')


        if (bone.parent):
            Export_babylon.write_matrix4(file_handler, label, (SystemMatrix * armature.matrix_world * bone.parent.matrix).inverted() * (SystemMatrix * armature.matrix_world * bone.matrix))
        else:
            Export_babylon.write_matrix4(file_handler, label, SystemMatrix * armature.matrix_world * bone.matrix)

I wonder if you need to multiply by SystemMatrix and matrix_world twice…

(SystemMatrix * armature.matrix_world * bone.parent.matrix).inverted() * (SystemMatrix * armature.matrix_world * bone.matrix))

Shouldn’t it be enough to do that once? (At least the SytemMatrix…)

SystemMatrix * ((armature.matrix_world * bone.parent.matrix).inverted() * (armature.matrix_world * bone.matrix)))

Alternatively, convert_space could be used i guess. Might be faster as the calculation would be done by native code, the python call could annihilate it though.