Search code examples
pythonblenderbpy

Blender bpy: Retrieve object rotation as quaternion without modifying scene


I am writing a blender exporter for my scene format.

When exporting, I need the rotation as quaternion.

The easiest way I found is to use the rotation_quaternion. But this member only guarantees to store the rotation, when the rotation_mode is set to 'QUATERNION'.

My temporary solution current looks like:

prevRotationMode = object.rotation_mode
object.rotation_mode = 'QUATERNION'
rotationAsQuaternion = object.rotation_quaternion
object.rotation_mode = prevRotationMode

This solution works, but I am affraid this may introduce numerical errors when my exporter would be called often, as the rotation angles would be converted between quaternion representations and the original representation.

My second idea was to copy the object, and change the rotation-mode in the copy of the object and deleting it afterwards. But this still wouldn't be a clean solution, as the scene would be modified by the exporter script.

Is there an elegant way to get the rotation as quaternions without modifying the scene?


Solution

  • The mathutils module gives you some useful functions, some of which are already directly available from various properties.

    rot_output = object.rotation_euler.to_quaternion()
    

    That will allow you to get the quaternions without altering the file data.

    I wouldn't be concerned about numerical errors, these use the same conversion steps that are used internally when you change rotation modes and you can change them back and forth all day without seeing any visual difference, changing the axis order of the euler rotation does make a difference though.