module Z80Lib3D::Quaternion

Z80Lib3D::Quaternion

Quaternion related helper methods.

Public Instance Methods

normalize_quaternion(q) click to toggle source

Returns a normalized quaternion.

# File lib/z80lib3d/quaternion.rb, line 27
def normalize_quaternion(q)
  n = quaternion_norm(q)
  s, x, y, z = q
  [s/n, x/n, y/n, z/n]
end
quaternion2matrix(q) click to toggle source

Returns a transformation matrix from a quaternion.

# File lib/z80lib3d/quaternion.rb, line 44
def quaternion2matrix(q)
  sq, xq, yq, zq = normalize_quaternion(q)

  xq2 = xq*xq
  yq2 = yq*yq
  zq2 = zq*zq

  xqyq = xq*yq
  sqzq = sq*zq
  xqzq = xq*zq
  sqyq = sq*yq
  yqzq = yq*zq
  sqxq = sq*xq

  qxx = 1.0 - 2.0*(yq2 + zq2)
  qyy = 1.0 - 2.0*(xq2 + zq2)
  qzz = 1.0 - 2.0*(xq2 + yq2)

  qxy = (xqyq - sqzq)*2.0
  qxz = (xqzq + sqyq)*2.0
  qyx = (xqyq + sqzq)*2.0
  qyz = (yqzq - sqxq)*2.0
  qzx = (xqzq - sqyq)*2.0
  qzy = (yqzq + sqxq)*2.0

  [qxx, qxy, qxz,
   qyx, qyy, qyz,
   qzx, qzy, qzz]
end
quaternion_cross_product(a, b) click to toggle source

Returns a quaternion as a cross product of quaternions a and b.

# File lib/z80lib3d/quaternion.rb, line 34
def quaternion_cross_product(a, b)
  sa, xa, ya, za = a
  sb, xb, yb, zb = b
  [sa*sb - xa*xb - ya*yb - za*zb,
   sa*xb + sb*xa + ya*zb - yb*za,
   sa*yb + sb*ya + za*xb - zb*xa,
   sa*zb + sb*za + xa*yb - xb*ya]
end
quaternion_norm(q) click to toggle source

Returns a quaternion norm.

# File lib/z80lib3d/quaternion.rb, line 22
def quaternion_norm(q)
  sqrt(quaternion_norm_q(q))
end
quaternion_norm_q(q) click to toggle source

Returns a quaternion square norm.

# File lib/z80lib3d/quaternion.rb, line 16
def quaternion_norm_q(q)
  s, x, y, z = q
  s*s + x*x + y*y + z*z
end
rotor_quaternion(rad, av) click to toggle source

Returns a rotor quaternion from radians and a unit vector.

# File lib/z80lib3d/quaternion.rb, line 9
def rotor_quaternion(rad, av)
  sn = sin(rad/2)
  x, y, z = av
  [cos(rad/2),sn*x,sn*y,sn*z]
end