Scale matrix S
looks like this:
sx 0 0 0
0 sy 0 0
0 0 sz 0
0 0 0 1
Translation matrix T
looks like this:
1 0 0 0
0 1 0 0
0 0 1 0
tx ty tz 1
Z-axis rotation matrix R
looks like this:
cos(a) sin(a) 0 0
-sin(a) cos(a) 0 0
0 0 1 0
0 0 0 1
If you have a transformation matrix M
, it is a result of a number of multiplications of R
, T
and S
matrices. Looking at M
, the order and number of those multiplications is unknown. However, if we assume that M=S*R*T
we can decompose it into separate matrices. Firstly let's calculate S*R*T
:
( sx*cos(a) sx*sin(a) 0 0) (m11 m12 m13 m14)
S*R*T = (-sy*sin(a) sy*cos(a) 0 0) = M = (m21 m22 m23 m24)
( 0 0 sz 0) (m31 m32 m33 m34)
( tx ty tz 1) (m41 m42 m43 m44)
Since we know it's a 2D transformation, getting translation is straightforward:
translation = vector2D(tx, ty) = vector2D(m41, m42)
To calculate rotation and scale, we can use sin(a)^2+cos(a)^2=1
:
(m11 / sx)^2 + (m12 / sx)^2 = 1
(m21 / sy)^2 + (m22 / sy)^2 = 1
m11^2 + m12^2 = sx^2
m21^2 + m22^2 = sy^2
sx = sqrt(m11^2 + m12^2)
sy = sqrt(m21^2 + m22^2)
scale = vector2D(sx, sy)
rotation_angle = atan2(sx*m22, sy*m12)
acos
as it disregards the sign of rotation. It is better to usea=atan2(sx*m22,sy*m12)
ora=atan2(-sy*m11,sx*m21)
. {I useatan2(dx,dy)
, but some systems define it asatan2(dy,dx)
so be careful}. – Beginner