quat.lua 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. --- A quaternion and associated utilities.
  2. -- @module quat
  3. local modules = (...):gsub('%.[^%.]+$', '') .. "."
  4. local constants = require(modules .. "constants")
  5. local vec3 = require(modules .. "vec3")
  6. local DOT_THRESHOLD = constants.DOT_THRESHOLD
  7. local DBL_EPSILON = constants.DBL_EPSILON
  8. local acos = math.acos
  9. local cos = math.cos
  10. local sin = math.sin
  11. local min = math.min
  12. local max = math.max
  13. local sqrt = math.sqrt
  14. local quat = {}
  15. local quat_mt = {}
  16. -- Private constructor.
  17. local function new(x, y, z, w)
  18. return setmetatable({
  19. x = x or 0,
  20. y = y or 0,
  21. z = z or 0,
  22. w = w or 1
  23. }, quat_mt)
  24. end
  25. -- Do the check to see if JIT is enabled. If so use the optimized FFI structs.
  26. local status, ffi
  27. if type(jit) == "table" and jit.status() then
  28. status, ffi = pcall(require, "ffi")
  29. if status then
  30. ffi.cdef "typedef struct { double x, y, z, w;} cpml_quat;"
  31. new = ffi.typeof("cpml_quat")
  32. end
  33. end
  34. -- Statically allocate a temporary variable used in some of our functions.
  35. local tmp = new()
  36. local qv, uv, uuv = vec3(), vec3(), vec3()
  37. --- Constants
  38. -- @table quat
  39. -- @field unit Unit quaternion
  40. -- @field zero Empty quaternion
  41. quat.unit = new(0, 0, 0, 1)
  42. quat.zero = new(0, 0, 0, 0)
  43. --- The public constructor.
  44. -- @param x Can be of two types: </br>
  45. -- number x X component
  46. -- table {x, y, z, w} or {x=x, y=y, z=z, w=w}
  47. -- @tparam number y Y component
  48. -- @tparam number z Z component
  49. -- @tparam number w W component
  50. -- @treturn quat out
  51. function quat.new(x, y, z, w)
  52. -- number, number, number, number
  53. if x and y and z and w then
  54. assert(type(x) == "number", "new: Wrong argument type for x (<number> expected)")
  55. assert(type(y) == "number", "new: Wrong argument type for y (<number> expected)")
  56. assert(type(z) == "number", "new: Wrong argument type for z (<number> expected)")
  57. assert(type(w) == "number", "new: Wrong argument type for w (<number> expected)")
  58. return new(x, y, z, w)
  59. -- {x, y, z, w} or {x=x, y=y, z=z, w=w}
  60. elseif type(x) == "table" then
  61. local xx, yy, zz, ww = x.x or x[1], x.y or x[2], x.z or x[3], x.w or x[4]
  62. assert(type(xx) == "number", "new: Wrong argument type for x (<number> expected)")
  63. assert(type(yy) == "number", "new: Wrong argument type for y (<number> expected)")
  64. assert(type(zz) == "number", "new: Wrong argument type for z (<number> expected)")
  65. assert(type(ww) == "number", "new: Wrong argument type for w (<number> expected)")
  66. return new(xx, yy, zz, ww)
  67. end
  68. return new(0, 0, 0, 1)
  69. end
  70. --- Create a quaternion from an angle/axis pair.
  71. -- @tparam number angle Angle (in radians)
  72. -- @tparam vec3 axis
  73. -- @treturn quat out
  74. function quat.from_angle_axis(angle, axis)
  75. local s = sin(angle * 0.5)
  76. local c = cos(angle * 0.5)
  77. return new(axis.x * s, axis.y * s, axis.z * s, c)
  78. end
  79. --- Create a quaternion from a normal/up vector pair.
  80. -- @tparam vec3 normal
  81. -- @tparam vec3 up (optional)
  82. -- @treturn quat out
  83. function quat.from_direction(normal, up)
  84. local u = up or vec3.unit_z
  85. local n = normal:normalize()
  86. local a = u:cross(n)
  87. local d = u:dot(n)
  88. return new(a.x, a.y, a.z, d + 1)
  89. end
  90. --- Clone a quaternion.
  91. -- @tparam quat a Quaternion to clone
  92. -- @treturn quat out
  93. function quat.clone(a)
  94. return new(a.x, a.y, a.z, a.w)
  95. end
  96. --- Add two quaternions.
  97. -- @tparam quat a Left hand operant
  98. -- @tparam quat b Right hand operant
  99. -- @treturn quat out
  100. function quat.add(a, b)
  101. return new(
  102. a.x + b.x,
  103. a.y + b.y,
  104. a.z + b.z,
  105. a.w + b.w
  106. )
  107. end
  108. --- Subtract a quaternion from another.
  109. -- @tparam quat a Left hand operant
  110. -- @tparam quat b Right hand operant
  111. -- @treturn quat out
  112. function quat.sub(a, b)
  113. return new(
  114. a.x - b.x,
  115. a.y - b.y,
  116. a.z - b.z,
  117. a.w - b.w
  118. )
  119. end
  120. --- Multiply two quaternions.
  121. -- @tparam quat a Left hand operant
  122. -- @tparam quat b Right hand operant
  123. -- @treturn quat out
  124. function quat.mul(a, b)
  125. return new(
  126. a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y,
  127. a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z,
  128. a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x,
  129. a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z
  130. )
  131. end
  132. --- Multiply a quaternion and a vec3.
  133. -- @tparam quat a Left hand operant
  134. -- @tparam vec3 b Right hand operant
  135. -- @treturn quat out
  136. function quat.mul_vec3(a, b)
  137. qv.x = a.x
  138. qv.y = a.y
  139. qv.z = a.z
  140. uv = qv:cross(b)
  141. uuv = qv:cross(uv)
  142. return b + ((uv * a.w) + uuv) * 2
  143. end
  144. --- Multiply a quaternion by an exponent.
  145. -- @tparam quat a Left hand operant
  146. -- @tparam number n Right hand operant
  147. -- @treturn quat out
  148. function quat.pow(a, n)
  149. if n == 0 then
  150. return new(0, 0, 0, 1)
  151. end
  152. if n > 0 then
  153. return a * a^(n-1)
  154. end
  155. if n < 0 then
  156. return a:reciprocal()^(-n)
  157. end
  158. end
  159. --- Normalize a quaternion.
  160. -- @tparam quat a Quaternion to normalize
  161. -- @treturn quat out
  162. function quat.normalize(a)
  163. if a:is_zero() then
  164. return new(0, 0, 0, 0)
  165. end
  166. return a:scale(1 / a:len())
  167. end
  168. --- Get the dot product of two quaternions.
  169. -- @tparam quat a Left hand operant
  170. -- @tparam quat b Right hand operant
  171. -- @treturn number dot
  172. function quat.dot(a, b)
  173. return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w
  174. end
  175. --- Return the length of a quaternion.
  176. -- @tparam quat a Quaternion to get length of
  177. -- @treturn number len
  178. function quat.len(a)
  179. return sqrt(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w)
  180. end
  181. --- Return the squared length of a quaternion.
  182. -- @tparam quat a Quaternion to get length of
  183. -- @treturn number len
  184. function quat.len2(a)
  185. return a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w
  186. end
  187. --- Multiply a quaternion by a scalar.
  188. -- @tparam quat a Left hand operant
  189. -- @tparam number s Right hand operant
  190. -- @treturn quat out
  191. function quat.scale(a, s)
  192. return new(
  193. a.x * s,
  194. a.y * s,
  195. a.z * s,
  196. a.w * s
  197. )
  198. end
  199. --- Alias of from_angle_axis.
  200. -- @tparam number angle Angle (in radians)
  201. -- @tparam vec3 axis
  202. -- @treturn quat out
  203. function quat.rotate(angle, axis)
  204. return quat.from_angle_axis(angle, axis)
  205. end
  206. --- Return the conjugate of a quaternion.
  207. -- @tparam quat a Quaternion to conjugate
  208. -- @treturn quat out
  209. function quat.conjugate(a)
  210. return new(-a.x, -a.y, -a.z, a.w)
  211. end
  212. --- Return the inverse of a quaternion.
  213. -- @tparam quat a Quaternion to invert
  214. -- @treturn quat out
  215. function quat.inverse(a)
  216. tmp.x = -a.x
  217. tmp.y = -a.y
  218. tmp.z = -a.z
  219. tmp.w = a.w
  220. return tmp:normalize()
  221. end
  222. --- Return the reciprocal of a quaternion.
  223. -- @tparam quat a Quaternion to reciprocate
  224. -- @treturn quat out
  225. function quat.reciprocal(a)
  226. if a:is_zero() then
  227. error("Cannot reciprocate a zero quaternion")
  228. return false
  229. end
  230. tmp.x = -a.x
  231. tmp.y = -a.y
  232. tmp.z = -a.z
  233. tmp.w = a.w
  234. return tmp:scale(1 / a:len2())
  235. end
  236. --- Lerp between two quaternions.
  237. -- @tparam quat a Left hand operant
  238. -- @tparam quat b Right hand operant
  239. -- @tparam number s Step value
  240. -- @treturn quat out
  241. function quat.lerp(a, b, s)
  242. return (a + (b - a) * s):normalize()
  243. end
  244. --- Slerp between two quaternions.
  245. -- @tparam quat a Left hand operant
  246. -- @tparam quat b Right hand operant
  247. -- @tparam number s Step value
  248. -- @treturn quat out
  249. function quat.slerp(a, b, s)
  250. local dot = a:dot(b)
  251. if dot < 0 then
  252. a = -a
  253. dot = -dot
  254. end
  255. if dot > DOT_THRESHOLD then
  256. return a:lerp(b, s)
  257. end
  258. dot = min(max(dot, -1), 1)
  259. local theta = acos(dot) * s
  260. local c = (b - a * dot):normalize()
  261. return a * cos(theta) + c * sin(theta)
  262. end
  263. --- Unpack a quaternion into individual components.
  264. -- @tparam quat a Quaternion to unpack
  265. -- @treturn number x
  266. -- @treturn number y
  267. -- @treturn number z
  268. -- @treturn number w
  269. function quat.unpack(a)
  270. return a.x, a.y, a.z, a.w
  271. end
  272. --- Return a boolean showing if a table is or is not a quat.
  273. -- @tparam quat a Quaternion to be tested
  274. -- @treturn boolean is_quat
  275. function quat.is_quat(a)
  276. if type(a) == "cdata" then
  277. return ffi.istype("cpml_quat", a)
  278. end
  279. return
  280. type(a) == "table" and
  281. type(a.x) == "number" and
  282. type(a.y) == "number" and
  283. type(a.z) == "number" and
  284. type(a.w) == "number"
  285. end
  286. --- Return a boolean showing if a table is or is not a zero quat.
  287. -- @tparam quat a Quaternion to be tested
  288. -- @treturn boolean is_zero
  289. function quat.is_zero(a)
  290. return
  291. a.x == 0 and
  292. a.y == 0 and
  293. a.z == 0 and
  294. a.w == 0
  295. end
  296. --- Return a boolean showing if a table is or is not a real quat.
  297. -- @tparam quat a Quaternion to be tested
  298. -- @treturn boolean is_real
  299. function quat.is_real(a)
  300. return
  301. a.x == 0 and
  302. a.y == 0 and
  303. a.z == 0
  304. end
  305. --- Return a boolean showing if a table is or is not an imaginary quat.
  306. -- @tparam quat a Quaternion to be tested
  307. -- @treturn boolean is_imaginary
  308. function quat.is_imaginary(a)
  309. return a.w == 0
  310. end
  311. --- Convert a quaternion into an angle/axis pair.
  312. -- @tparam quat a Quaternion to convert
  313. -- @treturn number angle
  314. -- @treturn vec3 axis
  315. function quat.to_angle_axis(a)
  316. if a.w > 1 or a.w < -1 then
  317. a = a:normalize()
  318. end
  319. local x, y, z
  320. local angle = 2 * acos(a.w)
  321. local s = sqrt(1 - a.w * a.w)
  322. if s < DBL_EPSILON then
  323. x = a.x
  324. y = a.y
  325. z = a.z
  326. else
  327. x = a.x / s
  328. y = a.y / s
  329. z = a.z / s
  330. end
  331. return angle, vec3(x, y, z)
  332. end
  333. --- Convert a quaternion into a vec3.
  334. -- @tparam quat a Quaternion to convert
  335. -- @treturn vec3 out
  336. function quat.to_vec3(a)
  337. return vec3(a.x, a.y, a.z)
  338. end
  339. --- Return a formatted string.
  340. -- @tparam quat a Quaternion to be turned into a string
  341. -- @treturn string formatted
  342. function quat.to_string(a)
  343. return string.format("(%+0.3f,%+0.3f,%+0.3f,%+0.3f)", a.x, a.y, a.z, a.w)
  344. end
  345. quat_mt.__index = quat
  346. quat_mt.__tostring = quat.to_string
  347. function quat_mt.__call(_, x, y, z, w)
  348. return quat.new(x, y, z, w)
  349. end
  350. function quat_mt.__unm(a)
  351. return a:scale(-1)
  352. end
  353. function quat_mt.__eq(a,b)
  354. if not quat.is_quat(a) or not quat.is_quat(b) then
  355. return false
  356. end
  357. return a.x == b.x and a.y == b.y and a.z == b.z and a.w == b.w
  358. end
  359. function quat_mt.__add(a, b)
  360. assert(quat.is_quat(a), "__add: Wrong argument type for left hand operant. (<cpml.quat> expected)")
  361. assert(quat.is_quat(b), "__add: Wrong argument type for right hand operant. (<cpml.quat> expected)")
  362. return a:add(b)
  363. end
  364. function quat_mt.__sub(a, b)
  365. assert(quat.is_quat(a), "__sub: Wrong argument type for left hand operant. (<cpml.quat> expected)")
  366. assert(quat.is_quat(b), "__sub: Wrong argument type for right hand operant. (<cpml.quat> expected)")
  367. return a:sub(b)
  368. end
  369. function quat_mt.__mul(a, b)
  370. assert(quat.is_quat(a), "__mul: Wrong argument type for left hand operant. (<cpml.quat> expected)")
  371. assert(quat.is_quat(b) or vec3.is_vec3(b) or type(b) == "number", "__mul: Wrong argument type for right hand operant. (<cpml.quat> or <cpml.vec3> or <number> expected)")
  372. if quat.is_quat(b) then
  373. return a:mul(b)
  374. end
  375. if type(b) == "number" then
  376. return a:scale(b)
  377. end
  378. return a:mul_vec3(b)
  379. end
  380. function quat_mt.__pow(a, n)
  381. assert(quat.is_quat(a), "__pow: Wrong argument type for left hand operant. (<cpml.quat> expected)")
  382. assert(type(n) == "number", "__pow: Wrong argument type for right hand operant. (<number> expected)")
  383. return a:pow(n)
  384. end
  385. if status then
  386. ffi.metatype(new, quat_mt)
  387. end
  388. return setmetatable({}, quat_mt)