excessive/cpml

cpml.mat4.from_transform() computes the wrong rotation matrix.

leonardus opened this issue · 1 comments

cpml/modules/mat4.lua:

local rx, ry, rz, rw = rot.x, rot.y, rot.z, rot.w

local rm = new {
  1-2*(ry*ry+rz*rz), 2*(rx*ry-rz*rw), 2*(rx*rz+ry*rw), 0,
  2*(rx*ry+rz*rw), 1-2*(rx*rx+rz*rz), 2*(ry*rz-rx*rw), 0,
  2*(rx*rz-ry*rw), 2*(ry*rz+rx*rw), 1-2*(rx*rx+ry*ry), 0,
  0, 0, 0, 1
}

Something about how that rotation matrix is calculated is wrong. Because when I replace it with my own function, that gets the rotation matrix the same way mat4.from_quaternion computes the matrix (using q:to_angle_axis()), I get the correct results that I was expecting:

function dbg_from_transform(trans, rot, scale)
	local sm = cpml.mat4.new{
		scale.x, 0,       0,       0,
		0,       scale.y, 0,       0,
		0,       0,       scale.z, 0,
		0,       0,       0,       1,
	}

	local rm = cpml.mat4.from_angle_axis(rot:to_angle_axis())

	local rsm = rm * sm

	rsm[13] = trans.x
	rsm[14] = trans.y
	rsm[15] = trans.z

	return rsm
end

Specifically, it seems like the issue is that the rotation matrix being generated is transposed.
Here are the matrix results using translation of (0, 0, 0), rotation of (0.4301481, 0.7169136, 0.2867654, 0.4677318), and scale of (1, 1, 1):

Native (cpml.mat4.from_transform()):
[ -0.192, +0.348, +0.917, +0.000, +0.885, +0.465, +0.009, +0.000, -0.424, +0.814, -0.398, +0.000, +0.000, +0.000, +0.000, +1.000 ]

Custom implementation using cpml.mat4.from_angle_axis(rot:to_angle_axis()):
[ -0.192, +0.885, -0.424, +0.000, +0.348, +0.465, +0.814, +0.000, +0.917, +0.009, -0.398, +0.000, +0.000, +0.000, +0.000, +1.000 ]