• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

excessive / cpml / 6132372428

09 Sep 2023 05:51PM UTC coverage: 58.701% (+0.6%) from 58.146%
6132372428

push

github

web-flow
Merge pull request #1 from mcclure/euler-quat

quat.to_euler_angles and quat.to_euler_angles_unpack

14 of 14 new or added lines in 1 file covered. (100.0%)

4662 of 7942 relevant lines covered (58.7%)

165.78 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

87.5
/modules/quat.lua
1
--- A quaternion and associated utilities.
2
-- @module quat
3

4
local modules       = (...):gsub('%.[^%.]+$', '') .. "."
12✔
5
local constants     = require(modules .. "constants")
12✔
6
local vec3          = require(modules .. "vec3")
12✔
7
local precond       = require(modules .. "_private_precond")
12✔
8
local private       = require(modules .. "_private_utils")
12✔
9
local DOT_THRESHOLD = constants.DOT_THRESHOLD
12✔
10
local DBL_EPSILON   = constants.DBL_EPSILON
12✔
11
local acos          = math.acos
12✔
12
local cos           = math.cos
12✔
13
local sin           = math.sin
12✔
14
local min           = math.min
12✔
15
local max           = math.max
12✔
16
local sqrt          = math.sqrt
12✔
17
local quat          = {}
12✔
18
local quat_mt       = {}
12✔
19

20
-- Private constructor.
21
local function new(x, y, z, w)
22
        return setmetatable({
220✔
23
                x = x or 0,
110✔
24
                y = y or 0,
110✔
25
                z = z or 0,
110✔
26
                w = w or 1
110✔
27
        }, quat_mt)
220✔
28
end
29

30
-- Do the check to see if JIT is enabled. If so use the optimized FFI structs.
31
local status, ffi
32
if type(jit) == "table" and jit.status() then
12✔
33
        status, ffi = pcall(require, "ffi")
8✔
34
        if status then
8✔
35
                ffi.cdef "typedef struct { double x, y, z, w;} cpml_quat;"
8✔
36
                new = ffi.typeof("cpml_quat")
16✔
37
        end
38
end
39

40
-- Statically allocate a temporary variable used in some of our functions.
41
local tmp = new()
12✔
42
local qv, uv, uuv = vec3(), vec3(), vec3()
28✔
43

44
--- Constants
45
-- @table quat
46
-- @field unit Unit quaternion
47
-- @field zero Empty quaternion
48
quat.unit = new(0, 0, 0, 1)
12✔
49
quat.zero = new(0, 0, 0, 0)
12✔
50

51
--- The public constructor.
52
-- @param x Can be of two types: </br>
53
-- number x X component
54
-- table {x, y, z, w} or {x=x, y=y, z=z, w=w}
55
-- @tparam number y Y component
56
-- @tparam number z Z component
57
-- @tparam number w W component
58
-- @treturn quat out
59
function quat.new(x, y, z, w)
12✔
60
        -- number, number, number, number
61
        if x and y and z and w then
132✔
62
                precond.typeof(x, "number", "new: Wrong argument type for x")
111✔
63
                precond.typeof(y, "number", "new: Wrong argument type for y")
111✔
64
                precond.typeof(z, "number", "new: Wrong argument type for z")
111✔
65
                precond.typeof(w, "number", "new: Wrong argument type for w")
111✔
66

67
                return new(x, y, z, w)
111✔
68

69
        -- {x, y, z, w} or {x=x, y=y, z=z, w=w}
70
        elseif type(x) == "table" then
21✔
71
                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]
6✔
72
                precond.typeof(xx, "number", "new: Wrong argument type for x")
6✔
73
                precond.typeof(yy, "number", "new: Wrong argument type for y")
6✔
74
                precond.typeof(zz, "number", "new: Wrong argument type for z")
6✔
75
                precond.typeof(ww, "number", "new: Wrong argument type for w")
6✔
76

77
                return new(xx, yy, zz, ww)
6✔
78
        end
79

80
        return new(0, 0, 0, 1)
15✔
81
end
82

83
--- Create a quaternion from an angle/axis pair.
84
-- @tparam number angle Angle (in radians)
85
-- @param axis/x -- Can be of two types, a vec3 axis, or the x component of that axis
86
-- @param y axis -- y component of axis (optional, only if x component param used)
87
-- @param z axis -- z component of axis (optional, only if x component param used)
88
-- @treturn quat out
89
function quat.from_angle_axis(angle, axis, a3, a4)
12✔
90
        if axis and a3 and a4 then
15✔
91
                local x, y, z = axis, a3, a4
9✔
92
                local s = sin(angle * 0.5)
9✔
93
                local c = cos(angle * 0.5)
9✔
94
                return new(x * s, y * s, z * s, c)
9✔
95
        else
96
                return quat.from_angle_axis(angle, axis.x, axis.y, axis.z)
6✔
97
        end
98
end
99

100
--- Create a quaternion from a normal/up vector pair.
101
-- @tparam vec3 normal
102
-- @tparam vec3 up (optional)
103
-- @treturn quat out
104
function quat.from_direction(normal, up)
12✔
105
        local u = up or vec3.unit_z
3✔
106
        local n = normal:normalize()
5✔
107
        local a = u:cross(n)
5✔
108
        local d = u:dot(n)
5✔
109
        return new(a.x, a.y, a.z, d + 1)
3✔
110
end
111

112
--- Clone a quaternion.
113
-- @tparam quat a Quaternion to clone
114
-- @treturn quat out
115
function quat.clone(a)
12✔
116
        return new(a.x, a.y, a.z, a.w)
3✔
117
end
118

119
--- Add two quaternions.
120
-- @tparam quat a Left hand operand
121
-- @tparam quat b Right hand operand
122
-- @treturn quat out
123
function quat.add(a, b)
12✔
124
        return new(
16✔
125
                a.x + b.x,
12✔
126
                a.y + b.y,
12✔
127
                a.z + b.z,
12✔
128
                a.w + b.w
12✔
129
        )
8✔
130
end
131

132
--- Subtract a quaternion from another.
133
-- @tparam quat a Left hand operand
134
-- @tparam quat b Right hand operand
135
-- @treturn quat out
136
function quat.sub(a, b)
12✔
137
        return new(
16✔
138
                a.x - b.x,
12✔
139
                a.y - b.y,
12✔
140
                a.z - b.z,
12✔
141
                a.w - b.w
12✔
142
        )
8✔
143
end
144

145
--- Multiply two quaternions.
146
-- @tparam quat a Left hand operand
147
-- @tparam quat b Right hand operand
148
-- @treturn quat quaternion equivalent to "apply b, then a"
149
function quat.mul(a, b)
12✔
150
        return new(
12✔
151
                a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y,
9✔
152
                a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z,
9✔
153
                a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x,
9✔
154
                a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z
9✔
155
        )
6✔
156
end
157

158
--- Multiply a quaternion and a vec3.
159
-- @tparam quat a Left hand operand
160
-- @tparam vec3 b Right hand operand
161
-- @treturn vec3 out
162
function quat.mul_vec3(a, b)
12✔
163
        qv.x = a.x
15✔
164
        qv.y = a.y
15✔
165
        qv.z = a.z
15✔
166
        uv   = qv:cross(b)
35✔
167
        uuv  = qv:cross(uv)
35✔
168
        return b + ((uv * a.w) + uuv) * 2
55✔
169
end
170

171
--- Raise a normalized quaternion to a scalar power.
172
-- @tparam quat a Left hand operand (should be a unit quaternion)
173
-- @tparam number s Right hand operand
174
-- @treturn quat out
175
function quat.pow(a, s)
12✔
176
        -- Do it as a slerp between identity and a (code borrowed from slerp)
177
        if a.w < 0 then
18✔
178
                a   = -a
×
179
        end
180
        local dot = a.w
18✔
181

182
        dot = min(max(dot, -1), 1)
18✔
183

184
        local theta = acos(dot) * s
18✔
185
        local c = new(a.x, a.y, a.z, 0):normalize() * sin(theta)
30✔
186
        c.w = cos(theta)
18✔
187
        return c
18✔
188
end
189

190
--- Normalize a quaternion.
191
-- @tparam quat a Quaternion to normalize
192
-- @treturn quat out
193
function quat.normalize(a)
12✔
194
        if a:is_zero() then
90✔
195
                return new(0, 0, 0, 0)
×
196
        end
197
        return a:scale(1 / a:len())
90✔
198
end
199

200
--- Get the dot product of two quaternions.
201
-- @tparam quat a Left hand operand
202
-- @tparam quat b Right hand operand
203
-- @treturn number dot
204
function quat.dot(a, b)
12✔
205
        return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w
12✔
206
end
207

208
--- Return the length of a quaternion.
209
-- @tparam quat a Quaternion to get length of
210
-- @treturn number len
211
function quat.len(a)
12✔
212
        return sqrt(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w)
57✔
213
end
214

215
--- Return the squared length of a quaternion.
216
-- @tparam quat a Quaternion to get length of
217
-- @treturn number len
218
function quat.len2(a)
12✔
219
        return a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w
9✔
220
end
221

222
--- Multiply a quaternion by a scalar.
223
-- @tparam quat a Left hand operand
224
-- @tparam number s Right hand operand
225
-- @treturn quat out
226
function quat.scale(a, s)
12✔
227
        return new(
124✔
228
                a.x * s,
93✔
229
                a.y * s,
93✔
230
                a.z * s,
93✔
231
                a.w * s
93✔
232
        )
62✔
233
end
234

235
--- Alias of from_angle_axis.
236
-- @tparam number angle Angle (in radians)
237
-- @param axis/x -- Can be of two types, a vec3 axis, or the x component of that axis
238
-- @param y axis -- y component of axis (optional, only if x component param used)
239
-- @param z axis -- z component of axis (optional, only if x component param used)
240
-- @treturn quat out
241
function quat.rotate(angle, axis, a3, a4)
12✔
242
        return quat.from_angle_axis(angle, axis, a3, a4)
×
243
end
244

245
--- Return the conjugate of a quaternion.
246
-- @tparam quat a Quaternion to conjugate
247
-- @treturn quat out
248
function quat.conjugate(a)
12✔
249
        return new(-a.x, -a.y, -a.z, a.w)
3✔
250
end
251

252
--- Return the inverse of a quaternion.
253
-- @tparam quat a Quaternion to invert
254
-- @treturn quat out
255
function quat.inverse(a)
12✔
256
        tmp.x = -a.x
3✔
257
        tmp.y = -a.y
3✔
258
        tmp.z = -a.z
3✔
259
        tmp.w =  a.w
3✔
260
        return tmp:normalize()
3✔
261
end
262

263
--- Return the reciprocal of a quaternion.
264
-- @tparam quat a Quaternion to reciprocate
265
-- @treturn quat out
266
function quat.reciprocal(a)
12✔
267
        if a:is_zero() then
10✔
268
                error("Cannot reciprocate a zero quaternion")
×
269
                return false
×
270
        end
271

272
        tmp.x = -a.x
6✔
273
        tmp.y = -a.y
6✔
274
        tmp.z = -a.z
6✔
275
        tmp.w =  a.w
6✔
276

277
        return tmp:scale(1 / a:len2())
10✔
278
end
279

280
--- Lerp between two quaternions.
281
-- @tparam quat a Left hand operand
282
-- @tparam quat b Right hand operand
283
-- @tparam number s Step value
284
-- @treturn quat out
285
function quat.lerp(a, b, s)
12✔
286
        return (a + (b - a) * s):normalize()
18✔
287
end
288

289
--- Slerp between two quaternions.
290
-- @tparam quat a Left hand operand
291
-- @tparam quat b Right hand operand
292
-- @tparam number s Step value
293
-- @treturn quat out
294
function quat.slerp(a, b, s)
12✔
295
        local dot = a:dot(b)
3✔
296

297
        if dot < 0 then
3✔
298
                a   = -a
×
299
                dot = -dot
×
300
        end
301

302
        if dot > DOT_THRESHOLD then
3✔
303
                return a:lerp(b, s)
3✔
304
        end
305

306
        dot = min(max(dot, -1), 1)
×
307

308
        local theta = acos(dot) * s
×
309
        local c = (b - a * dot):normalize()
×
310
        return a * cos(theta) + c * sin(theta)
×
311
end
312

313
--- Unpack a quaternion into individual components.
314
-- @tparam quat a Quaternion to unpack
315
-- @treturn number x
316
-- @treturn number y
317
-- @treturn number z
318
-- @treturn number w
319
function quat.unpack(a)
12✔
320
        return a.x, a.y, a.z, a.w
3✔
321
end
322

323
--- Return a boolean showing if a table is or is not a quat.
324
-- @tparam quat a Quaternion to be tested
325
-- @treturn boolean is_quat
326
function quat.is_quat(a)
12✔
327
        if type(a) == "cdata" then
225✔
328
                return ffi.istype("cpml_quat", a)
114✔
329
        end
330

331
        return
×
332
                type(a)   == "table"  and
111✔
333
                type(a.x) == "number" and
57✔
334
                type(a.y) == "number" and
57✔
335
                type(a.z) == "number" and
57✔
336
                type(a.w) == "number"
111✔
337
end
338

339
--- Return a boolean showing if a table is or is not a zero quat.
340
-- @tparam quat a Quaternion to be tested
341
-- @treturn boolean is_zero
342
function quat.is_zero(a)
12✔
343
        return
×
344
                a.x == 0 and
63✔
345
                a.y == 0 and
3✔
346
                a.z == 0 and
3✔
347
                a.w == 0
63✔
348
end
349

350
--- Return a boolean showing if a table is or is not a real quat.
351
-- @tparam quat a Quaternion to be tested
352
-- @treturn boolean is_real
353
function quat.is_real(a)
12✔
354
        return
×
355
                a.x == 0 and
3✔
356
                a.y == 0 and
3✔
357
                a.z == 0
3✔
358
end
359

360
--- Return a boolean showing if a table is or is not an imaginary quat.
361
-- @tparam quat a Quaternion to be tested
362
-- @treturn boolean is_imaginary
363
function quat.is_imaginary(a)
12✔
364
        return a.w == 0
3✔
365
end
366

367
--- Return whether any component is NaN
368
-- @tparam quat a Quaternion to be tested
369
-- @treturn boolean if x,y,z, or w is NaN
370
function quat.has_nan(a)
12✔
371
        return private.is_nan(a.x) or
×
372
                private.is_nan(a.y) or
×
373
                private.is_nan(a.z) or
×
374
                private.is_nan(a.w)
×
375
end
376

377
--- Convert a quaternion into an angle plus axis components.
378
-- @tparam quat a Quaternion to convert
379
-- @tparam identityAxis vec3 of axis to use on identity/degenerate quaternions (optional, default returns 0,0,0,1)
380
-- @treturn number angle
381
-- @treturn x axis-x
382
-- @treturn y axis-y
383
-- @treturn z axis-z
384
function quat.to_angle_axis_unpack(a, identityAxis)
12✔
385
        if a.w > 1 or a.w < -1 then
21✔
386
                a = a:normalize()
10✔
387
        end
388

389
        -- If length of xyz components is less than DBL_EPSILON, this is zero or close enough (an identity quaternion)
390
        -- Normally an identity quat would return a nonsense answer, so we return an arbitrary zero rotation early.
391
        -- FIXME: Is it safe to assume there are *no* valid quaternions with nonzero degenerate lengths?
392
        if a.x*a.x + a.y*a.y + a.z*a.z < constants.DBL_EPSILON*constants.DBL_EPSILON then
21✔
393
                if identityAxis then
6✔
394
                        return 0,identityAxis:unpack()
7✔
395
                else
396
                        return 0,0,0,1
3✔
397
                end
398
        end
399

400
        local x, y, z
401
        local angle = 2 * acos(a.w)
15✔
402
        local s     = sqrt(1 - a.w * a.w)
15✔
403

404
        if s < DBL_EPSILON then
15✔
405
                x = a.x
3✔
406
                y = a.y
3✔
407
                z = a.z
3✔
408
        else
409
                x = a.x / s
12✔
410
                y = a.y / s
12✔
411
                z = a.z / s
12✔
412
        end
413

414
        return angle, x, y, z
15✔
415
end
416

417
--- Convert a quaternion into an angle/axis pair.
418
-- @tparam quat a Quaternion to convert
419
-- @tparam identityAxis vec3 of axis to use on identity/degenerate quaternions (optional, default returns 0,vec3(0,0,1))
420
-- @treturn number angle
421
-- @treturn vec3 axis
422
function quat.to_angle_axis(a, identityAxis)
12✔
423
        local angle, x, y, z = a:to_angle_axis_unpack(identityAxis)
15✔
424
        return angle, vec3(x, y, z)
25✔
425
end
426

427
--- Convert a quaternion into euler angle components
428
-- @tparam quat a Quaternion to convert
429
-- @treturn roll
430
-- @treturn pitch
431
-- @treturn yaw
432
function quat.to_euler_angles_unpack(q)
12✔
433
    -- roll (x-axis rotation)
434
    local sinr_cosp = 2 * (q.w * q.x + q.y * q.z)
×
435
    local cosr_cosp = 1 - 2 * (q.x * q.x + q.y * q.y)
×
436
    local roll = math.atan2(sinr_cosp, cosr_cosp)
×
437

438
    -- pitch (y-axis rotation)
439
    local sinp = 2 * (q.w * q.y - q.z * q.x)
×
440
    local pitch
441
    if math.abs(sinp) >= 1 then
×
442
        pitch = math.pi / 2 * ((sinp > 0) and 1 or -1) -- Use 90 degrees if out of range
×
443
    else
444
        pitch = math.asin(sinp)
×
445
    end
446

447
    -- yaw (z-axis rotation)
448
    local siny_cosp = 2 * (q.w * q.z + q.x * q.y)
×
449
    local cosy_cosp = 1 - 2 * (q.y * q.y + q.z * q.z)
×
450
    local yaw = math.atan2(siny_cosp, cosy_cosp)
×
451

452
    return roll, pitch, yaw
×
453
end
454

455
--- Convert a quaternion into euler angles
456
-- @tparam quat a Quaternion to convert
457
-- @treturn result a {roll, pitch, yaw} table
458
function quat.to_euler_angles(a)
12✔
459
        return {quat.to_euler_angles_unpack(a)}
×
460
end
461

462
--- Convert a quaternion into a vec3.
463
-- @tparam quat a Quaternion to convert
464
-- @treturn vec3 out
465
function quat.to_vec3(a)
12✔
466
        return vec3(a.x, a.y, a.z)
3✔
467
end
468

469
--- Return a formatted string.
470
-- @tparam quat a Quaternion to be turned into a string
471
-- @treturn string formatted
472
function quat.to_string(a)
12✔
473
        return string.format("(%+0.3f,%+0.3f,%+0.3f,%+0.3f)", a.x, a.y, a.z, a.w)
3✔
474
end
475

476
quat_mt.__index    = quat
12✔
477
quat_mt.__tostring = quat.to_string
12✔
478

479
function quat_mt.__call(_, x, y, z, w)
12✔
480
        return quat.new(x, y, z, w)
129✔
481
end
482

483
function quat_mt.__unm(a)
12✔
484
        return a:scale(-1)
3✔
485
end
486

487
function quat_mt.__eq(a,b)
12✔
488
        if not quat.is_quat(a) or not quat.is_quat(b) then
49✔
489
                return false
×
490
        end
491
        return a.x == b.x and a.y == b.y and a.z == b.z and a.w == b.w
21✔
492
end
493

494
function quat_mt.__add(a, b)
12✔
495
        precond.assert(quat.is_quat(a), "__add: Wrong argument type '%s' for left hand operand. (<cpml.quat> expected)", type(a))
15✔
496
        precond.assert(quat.is_quat(b), "__add: Wrong argument type '%s' for right hand operand. (<cpml.quat> expected)", type(b))
15✔
497
        return a:add(b)
9✔
498
end
499

500
function quat_mt.__sub(a, b)
12✔
501
        precond.assert(quat.is_quat(a), "__sub: Wrong argument type '%s' for left hand operand. (<cpml.quat> expected)", type(a))
15✔
502
        precond.assert(quat.is_quat(b), "__sub: Wrong argument type '%s' for right hand operand. (<cpml.quat> expected)", type(b))
15✔
503
        return a:sub(b)
9✔
504
end
505

506
function quat_mt.__mul(a, b)
12✔
507
        precond.assert(quat.is_quat(a), "__mul: Wrong argument type '%s' for left hand operand. (<cpml.quat> expected)", type(a))
75✔
508
        assert(quat.is_quat(b) or vec3.is_vec3(b) or type(b) == "number", "__mul: Wrong argument type for right hand operand. (<cpml.quat> or <cpml.vec3> or <number> expected)")
127✔
509

510
        if quat.is_quat(b) then
75✔
511
                return a:mul(b)
6✔
512
        end
513

514
        if type(b) == "number" then
39✔
515
                return a:scale(b)
27✔
516
        end
517

518
        return a:mul_vec3(b)
12✔
519
end
520

521
function quat_mt.__pow(a, n)
12✔
522
        precond.assert(quat.is_quat(a), "__pow: Wrong argument type '%s' for left hand operand. (<cpml.quat> expected)", type(a))
15✔
523
        precond.typeof(n, "number", "__pow: Wrong argument type for right hand operand.")
9✔
524
        return a:pow(n)
9✔
525
end
526

527
if status then
12✔
528
        xpcall(function() -- Allow this to silently fail; assume failure means someone messed with package.loaded
16✔
529
                ffi.metatype(new, quat_mt)
8✔
530
        end, function() end)
16✔
531
end
532

533
return setmetatable({}, quat_mt)
12✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc