-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcpml.lua
3134 lines (2677 loc) · 83.4 KB
/
cpml.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local private = {}
local floor = math.floor
local ceil = math.ceil
function private.round(value, precision)
if precision then return utils.round(value / precision) * precision end
return value >= 0 and floor(value+0.5) or ceil(value-0.5)
end
-- Maths
local sqrt = math.sqrt
local cos = math.cos
local sin = math.sin
local tan = math.tan
local rad = math.rad
local acos = math.acos
local atan2 = math.atan2
local min = math.min
local max = math.max
local abs = math.abs
local ceil = math.ceil
local floor = math.floor
local log = math.log
local log2 = log(2)
local frexp = math.frexp or function(x)
if x == 0 then return 0, 0 end
local e = floor(log(abs(x)) / log2 + 1)
return x / 2 ^ e, e
end
local constants = {}
-- same as C's FLT_EPSILON
constants.FLT_EPSILON = 1.19209290e-07
-- same as C's DBL_EPSILON
constants.DBL_EPSILON = 2.2204460492503131e-16
-- used for quaternion.slerp
constants.DOT_THRESHOLD = 0.9995
local DOT_THRESHOLD = constants.DOT_THRESHOLD
local DBL_EPSILON = constants.DBL_EPSILON
vec3 = {}
vec3_mt = {}
vec2 = {}
vec2_mt = {}
utils = {}
quat = {}
quat_mt = {}
mat4 = {}
mat4_mt = {}
intersect = {}
-- setmetatable(vec3, vec3_mt)
-- setmetatable(vec2, vec2_mt)
-- setmetatable(quat, quat_mt)
-- setmetatable(mat4, mat4_mt)
-- Order:
-- vec3
-- vec2
-- utils
-- quat
-- mat4
-- intersect
--
-- BLOCK vec3
--
do
-- Private constructor.
local function new(x, y, z)
return setmetatable({
x = x or 0,
y = y or 0,
z = z or 0
}, vec3_mt)
end
-- Do the check to see if JIT is enabled. If so use the optimized FFI structs.
local status, ffi
if type(jit) == "table" and jit.status() then
status, ffi = pcall(require, "ffi")
if status then
ffi.cdef "typedef struct { double x, y, z;} cpml_vec3;"
new = ffi.typeof("cpml_vec3")
end
end
--- Constants
-- @table vec3
-- @field unit_x X axis of rotation
-- @field unit_y Y axis of rotation
-- @field unit_z Z axis of rotation
-- @field zero Empty vector
vec3.unit_x = new(1, 0, 0)
vec3.unit_y = new(0, 1, 0)
vec3.unit_z = new(0, 0, 1)
vec3.zero = new(0, 0, 0)
--- The public constructor.
-- @param x Can be of three types: </br>
-- number X component
-- table {x, y, z} or {x=x, y=y, z=z}
-- scalar To fill the vector eg. {x, x, x}
-- @tparam number y Y component
-- @tparam number z Z component
-- @treturn vec3 out
function vec3.new(x, y, z)
-- number, number, number
if x and y and z then
assert(type(x) == "number", "new: Wrong argument type for x (<number> expected)")
assert(type(y) == "number", "new: Wrong argument type for y (<number> expected)")
assert(type(z) == "number", "new: Wrong argument type for z (<number> expected)")
return new(x, y, z)
-- {x, y, z} or {x=x, y=y, z=z}
elseif type(x) == "table" or type(x) == "cdata" then -- table in vanilla lua, cdata in luajit
local xx, yy, zz = x.x or x[1], x.y or x[2], x.z or x[3]
assert(type(xx) == "number", "new: Wrong argument type for x (<number> expected)")
assert(type(yy) == "number", "new: Wrong argument type for y (<number> expected)")
assert(type(zz) == "number", "new: Wrong argument type for z (<number> expected)")
return new(xx, yy, zz)
-- number
elseif type(x) == "number" then
return new(x, x, x)
else
return new()
end
end
--- Clone a vector.
-- @tparam vec3 a Vector to be cloned
-- @treturn vec3 out
function vec3.clone(a)
return new(a.x, a.y, a.z)
end
--- Add two vectors.
-- @tparam vec3 a Left hand operand
-- @tparam vec3 b Right hand operand
-- @treturn vec3 out
function vec3.add(a, b)
return new(
a.x + b.x,
a.y + b.y,
a.z + b.z
)
end
--- Subtract one vector from another.
-- @tparam vec3 a Left hand operand
-- @tparam vec3 b Right hand operand
-- @treturn vec3 out
function vec3.sub(a, b)
return new(
a.x - b.x,
a.y - b.y,
a.z - b.z
)
end
--- Multiply a vector by another vectorr.
-- @tparam vec3 a Left hand operand
-- @tparam vec3 b Right hand operand
-- @treturn vec3 out
function vec3.mul(a, b)
return new(
a.x * b.x,
a.y * b.y,
a.z * b.z
)
end
--- Divide a vector by a scalar.
-- @tparam vec3 a Left hand operand
-- @tparam vec3 b Right hand operand
-- @treturn vec3 out
function vec3.div(a, b)
return new(
a.x / b.x,
a.y / b.y,
a.z / b.z
)
end
--- Get the normal of a vector.
-- @tparam vec3 a Vector to normalize
-- @treturn vec3 out
function vec3.normalize(a)
if a:is_zero() then
return new()
end
return a:scale(1 / a:len())
end
--- Trim a vector to a given length
-- @tparam vec3 a Vector to be trimmed
-- @tparam number len Length to trim the vector to
-- @treturn vec3 out
function vec3.trim(a, len)
return a:normalize():scale(math.min(a:len(), len))
end
--- Get the cross product of two vectors.
-- @tparam vec3 a Left hand operand
-- @tparam vec3 b Right hand operand
-- @treturn vec3 out
function vec3.cross(a, b)
return new(
a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x
)
end
--- Get the dot product of two vectors.
-- @tparam vec3 a Left hand operand
-- @tparam vec3 b Right hand operand
-- @treturn number dot
function vec3.dot(a, b)
return a.x * b.x + a.y * b.y + a.z * b.z
end
--- Get the length of a vector.
-- @tparam vec3 a Vector to get the length of
-- @treturn number len
function vec3.len(a)
return sqrt(a.x * a.x + a.y * a.y + a.z * a.z)
end
--- Get the squared length of a vector.
-- @tparam vec3 a Vector to get the squared length of
-- @treturn number len
function vec3.len2(a)
return a.x * a.x + a.y * a.y + a.z * a.z
end
--- Get the distance between two vectors.
-- @tparam vec3 a Left hand operand
-- @tparam vec3 b Right hand operand
-- @treturn number dist
function vec3.dist(a, b)
local dx = a.x - b.x
local dy = a.y - b.y
local dz = a.z - b.z
return sqrt(dx * dx + dy * dy + dz * dz)
end
--- Get the squared distance between two vectors.
-- @tparam vec3 a Left hand operand
-- @tparam vec3 b Right hand operand
-- @treturn number dist
function vec3.dist2(a, b)
local dx = a.x - b.x
local dy = a.y - b.y
local dz = a.z - b.z
return dx * dx + dy * dy + dz * dz
end
--- Scale a vector by a scalar.
-- @tparam vec3 a Left hand operand
-- @tparam number b Right hand operand
-- @treturn vec3 out
function vec3.scale(a, b)
return new(
a.x * b,
a.y * b,
a.z * b
)
end
--- Rotate vector about an axis.
-- @tparam vec3 a Vector to rotate
-- @tparam number phi Angle to rotate vector by (in radians)
-- @tparam vec3 axis Axis to rotate by
-- @treturn vec3 out
function vec3.rotate(a, phi, axis)
if not vec3.is_vec3(axis) then
return a
end
local u = axis:normalize()
local c = cos(phi)
local s = sin(phi)
-- Calculate generalized rotation matrix
local m1 = new((c + u.x * u.x * (1 - c)), (u.x * u.y * (1 - c) - u.z * s), (u.x * u.z * (1 - c) + u.y * s))
local m2 = new((u.y * u.x * (1 - c) + u.z * s), (c + u.y * u.y * (1 - c)), (u.y * u.z * (1 - c) - u.x * s))
local m3 = new((u.z * u.x * (1 - c) - u.y * s), (u.z * u.y * (1 - c) + u.x * s), (c + u.z * u.z * (1 - c)) )
return new(
a:dot(m1),
a:dot(m2),
a:dot(m3)
)
end
--- Get the perpendicular vector of a vector.
-- @tparam vec3 a Vector to get perpendicular axes from
-- @treturn vec3 out
function vec3.perpendicular(a)
return new(-a.y, a.x, 0)
end
--- Lerp between two vectors.
-- @tparam vec3 a Left hand operand
-- @tparam vec3 b Right hand operand
-- @tparam number s Step value
-- @treturn vec3 out
function vec3.lerp(a, b, s)
return a + (b - a) * s
end
-- Round all components to nearest int (or other precision).
-- @tparam vec3 a Vector to round.
-- @tparam precision Digits after the decimal (round numebr if unspecified)
-- @treturn vec3 Rounded vector
function vec3.round(a, precision)
return vec3.new(private.round(a.x, precision), private.round(a.y, precision), private.round(a.z, precision))
end
--- Unpack a vector into individual components.
-- @tparam vec3 a Vector to unpack
-- @treturn number x
-- @treturn number y
-- @treturn number z
function vec3.unpack(a)
return a.x, a.y, a.z
end
--- Return the component-wise minimum of two vectors.
-- @tparam vec3 a Left hand operand
-- @tparam vec3 b Right hand operand
-- @treturn vec3 A vector where each component is the lesser value for that component between the two given vectors.
function vec3.component_min(a, b)
return new(math.min(a.x, b.x), math.min(a.y, b.y), math.min(a.z, b.z))
end
--- Return the component-wise maximum of two vectors.
-- @tparam vec3 a Left hand operand
-- @tparam vec3 b Right hand operand
-- @treturn vec3 A vector where each component is the lesser value for that component between the two given vectors.
function vec3.component_max(a, b)
return new(math.max(a.x, b.x), math.max(a.y, b.y), math.max(a.z, b.z))
end
-- Negate x axis only of vector.
-- @tparam vec2 a Vector to x-flip.
-- @treturn vec2 x-flipped vector
function vec3.flip_x(a)
return vec3.new(-a.x, a.y, a.z)
end
-- Negate y axis only of vector.
-- @tparam vec2 a Vector to y-flip.
-- @treturn vec2 y-flipped vector
function vec3.flip_y(a)
return vec3.new(a.x, -a.y, a.z)
end
-- Negate z axis only of vector.
-- @tparam vec2 a Vector to z-flip.
-- @treturn vec2 z-flipped vector
function vec3.flip_z(a)
return vec3.new(a.x, a.y, -a.z)
end
--- Return a boolean showing if a table is or is not a vec3.
-- @tparam vec3 a Vector to be tested
-- @treturn boolean is_vec3
function vec3.is_vec3(a)
if type(a) == "cdata" then
return ffi.istype("cpml_vec3", a)
end
return
type(a) == "table" and
type(a.x) == "number" and
type(a.y) == "number" and
type(a.z) == "number"
end
--- Return a boolean showing if a table is or is not a zero vec3.
-- @tparam vec3 a Vector to be tested
-- @treturn boolean is_zero
function vec3.is_zero(a)
return a.x == 0 and a.y == 0 and a.z == 0
end
--- Return a formatted string.
-- @tparam vec3 a Vector to be turned into a string
-- @treturn string formatted
function vec3.to_string(a)
return string.format("(%+0.3f,%+0.3f,%+0.3f)", a.x, a.y, a.z)
end
vec3_mt.__index = vec3
vec3_mt.__tostring = vec3.to_string
function vec3_mt.__call(_, x, y, z)
return vec3.new(x, y, z)
end
function vec3_mt.__unm(a)
return new(-a.x, -a.y, -a.z)
end
function vec3_mt.__eq(a, b)
if not vec3.is_vec3(a) or not vec3.is_vec3(b) then
return false
end
return a.x == b.x and a.y == b.y and a.z == b.z
end
function vec3_mt.__add(a, b)
assert(vec3.is_vec3(a), "__add: Wrong argument type for left hand operand. (<cpml.vec3> expected)")
assert(vec3.is_vec3(b), "__add: Wrong argument type for right hand operand. (<cpml.vec3> expected)")
return a:add(b)
end
function vec3_mt.__sub(a, b)
assert(vec3.is_vec3(a), "__sub: Wrong argument type for left hand operand. (<cpml.vec3> expected)")
assert(vec3.is_vec3(b), "__sub: Wrong argument type for right hand operand. (<cpml.vec3> expected)")
return a:sub(b)
end
function vec3_mt.__mul(a, b)
assert(vec3.is_vec3(a), "__mul: Wrong argument type for left hand operand. (<cpml.vec3> expected)")
assert(vec3.is_vec3(b) or type(b) == "number", "__mul: Wrong argument type for right hand operand. (<cpml.vec3> or <number> expected)")
if vec3.is_vec3(b) then
return a:mul(b)
end
return a:scale(b)
end
function vec3_mt.__div(a, b)
assert(vec3.is_vec3(a), "__div: Wrong argument type for left hand operand. (<cpml.vec3> expected)")
assert(vec3.is_vec3(b) or type(b) == "number", "__div: Wrong argument type for right hand operand. (<cpml.vec3> or <number> expected)")
if vec3.is_vec3(b) then
return a:div(b)
end
return a:scale(1 / b)
end
if status then
xpcall(function() -- Allow this to silently fail; assume failure means someone messed with package.loaded
ffi.metatype(new, vec3_mt)
end, function() end)
end
vec3 = setmetatable({}, vec3_mt)
end
--
-- BLOCK vec2
--
do
-- Private constructor.
local function new(x, y)
return setmetatable({
x = x or 0,
y = y or 0
}, vec2_mt)
end
-- Do the check to see if JIT is enabled. If so use the optimized FFI structs.
local status, ffi
if type(jit) == "table" and jit.status() then
status, ffi = pcall(require, "ffi")
if status then
ffi.cdef "typedef struct { double x, y;} cpml_vec2;"
new = ffi.typeof("cpml_vec2")
end
end
--- Constants
-- @table vec2
-- @field unit_x X axis of rotation
-- @field unit_y Y axis of rotation
-- @field zero Empty vector
vec2.unit_x = new(1, 0)
vec2.unit_y = new(0, 1)
vec2.zero = new(0, 0)
--- The public constructor.
-- @param x Can be of three types: </br>
-- number X component
-- table {x, y} or {x = x, y = y}
-- scalar to fill the vector eg. {x, x}
-- @tparam number y Y component
-- @treturn vec2 out
function vec2.new(x, y)
-- number, number
if x and y then
assert(type(x) == "number", "new: Wrong argument type for x (<number> expected)")
assert(type(y) == "number", "new: Wrong argument type for y (<number> expected)")
return new(x, y)
-- {x, y} or {x=x, y=y}
elseif type(x) == "table" or type(x) == "cdata" then -- table in vanilla lua, cdata in luajit
local xx, yy = x.x or x[1], x.y or x[2]
assert(type(xx) == "number", "new: Wrong argument type for x (<number> expected)")
assert(type(yy) == "number", "new: Wrong argument type for y (<number> expected)")
return new(xx, yy)
-- number
elseif type(x) == "number" then
return new(x, x)
else
return new()
end
end
--- Convert point from polar to cartesian.
-- @tparam number radius Radius of the point
-- @tparam number theta Angle of the point (in radians)
-- @treturn vec2 out
function vec2.from_cartesian(radius, theta)
return new(radius * cos(theta), radius * sin(theta))
end
--- Clone a vector.
-- @tparam vec2 a Vector to be cloned
-- @treturn vec2 out
function vec2.clone(a)
return new(a.x, a.y)
end
--- Add two vectors.
-- @tparam vec2 a Left hand operand
-- @tparam vec2 b Right hand operand
-- @treturn vec2 out
function vec2.add(a, b)
return new(
a.x + b.x,
a.y + b.y
)
end
--- Subtract one vector from another.
-- @tparam vec2 a Left hand operand
-- @tparam vec2 b Right hand operand
-- @treturn vec2 out
function vec2.sub(a, b)
return new(
a.x - b.x,
a.y - b.y
)
end
--- Multiply a vector by another vector.
-- @tparam vec2 a Left hand operand
-- @tparam vec2 b Right hand operand
-- @treturn vec2 out
function vec2.mul(a, b)
return new(
a.x * b.x,
a.y * b.y
)
end
--- Divide a vector by another vector.
-- @tparam vec2 a Left hand operand
-- @tparam vec2 b Right hand operand
-- @treturn vec2 out
function vec2.div(a, b)
return new(
a.x / b.x,
a.y / b.y
)
end
--- Get the normal of a vector.
-- @tparam vec2 a Vector to normalize
-- @treturn vec2 out
function vec2.normalize(a)
if a:is_zero() then
return new()
end
return a:scale(1 / a:len())
end
--- Trim a vector to a given length.
-- @tparam vec2 a Vector to be trimmed
-- @tparam number len Length to trim the vector to
-- @treturn vec2 out
function vec2.trim(a, len)
return a:normalize():scale(math.min(a:len(), len))
end
--- Get the cross product of two vectors.
-- @tparam vec2 a Left hand operand
-- @tparam vec2 b Right hand operand
-- @treturn number magnitude
function vec2.cross(a, b)
return a.x * b.y - a.y * b.x
end
--- Get the dot product of two vectors.
-- @tparam vec2 a Left hand operand
-- @tparam vec2 b Right hand operand
-- @treturn number dot
function vec2.dot(a, b)
return a.x * b.x + a.y * b.y
end
--- Get the length of a vector.
-- @tparam vec2 a Vector to get the length of
-- @treturn number len
function vec2.len(a)
return sqrt(a.x * a.x + a.y * a.y)
end
--- Get the squared length of a vector.
-- @tparam vec2 a Vector to get the squared length of
-- @treturn number len
function vec2.len2(a)
return a.x * a.x + a.y * a.y
end
--- Get the distance between two vectors.
-- @tparam vec2 a Left hand operand
-- @tparam vec2 b Right hand operand
-- @treturn number dist
function vec2.dist(a, b)
local dx = a.x - b.x
local dy = a.y - b.y
return sqrt(dx * dx + dy * dy)
end
--- Get the squared distance between two vectors.
-- @tparam vec2 a Left hand operand
-- @tparam vec2 b Right hand operand
-- @treturn number dist
function vec2.dist2(a, b)
local dx = a.x - b.x
local dy = a.y - b.y
return dx * dx + dy * dy
end
--- Scale a vector by a scalar.
-- @tparam vec2 a Left hand operand
-- @tparam number b Right hand operand
-- @treturn vec2 out
function vec2.scale(a, b)
return new(
a.x * b,
a.y * b
)
end
--- Rotate a vector.
-- @tparam vec2 a Vector to rotate
-- @tparam number phi Angle to rotate vector by (in radians)
-- @treturn vec2 out
function vec2.rotate(a, phi)
local c = cos(phi)
local s = sin(phi)
return new(
c * a.x - s * a.y,
s * a.x + c * a.y
)
end
--- Get the perpendicular vector of a vector.
-- @tparam vec2 a Vector to get perpendicular axes from
-- @treturn vec2 out
function vec2.perpendicular(a)
return new(-a.y, a.x)
end
--- Signed angle from one vector to another.
-- Rotations from +x to +y are positive.
-- @tparam vec2 a Vector
-- @tparam vec2 b Vector
-- @treturn number angle in (-pi, pi]
function vec2.angle_to(a, b)
if b then
local angle = atan2(b.y, b.x) - atan2(a.y, a.x)
-- convert to (-pi, pi]
if angle > math.pi then
angle = angle - 2 * math.pi
elseif angle <= -math.pi then
angle = angle + 2 * math.pi
end
return angle
end
return atan2(a.y, a.x)
end
--- Unsigned angle between two vectors.
-- Directionless and thus commutative.
-- @tparam vec2 a Vector
-- @tparam vec2 b Vector
-- @treturn number angle in [0, pi]
function vec2.angle_between(a, b)
if b then
if vec2.is_vec2(a) then
return acos(a:dot(b) / (a:len() * b:len()))
end
return acos(vec3.dot(a, b) / (vec3.len(a) * vec3.len(b)))
end
return 0
end
--- Lerp between two vectors.
-- @tparam vec2 a Left hand operand
-- @tparam vec2 b Right hand operand
-- @tparam number s Step value
-- @treturn vec2 out
function vec2.lerp(a, b, s)
return a + (b - a) * s
end
--- Unpack a vector into individual components.
-- @tparam vec2 a Vector to unpack
-- @treturn number x
-- @treturn number y
function vec2.unpack(a)
return a.x, a.y
end
--- Return the component-wise minimum of two vectors.
-- @tparam vec2 a Left hand operand
-- @tparam vec2 b Right hand operand
-- @treturn vec2 A vector where each component is the lesser value for that component between the two given vectors.
function vec2.component_min(a, b)
return new(math.min(a.x, b.x), math.min(a.y, b.y))
end
--- Return the component-wise maximum of two vectors.
-- @tparam vec2 a Left hand operand
-- @tparam vec2 b Right hand operand
-- @treturn vec2 A vector where each component is the lesser value for that component between the two given vectors.
function vec2.component_max(a, b)
return new(math.max(a.x, b.x), math.max(a.y, b.y))
end
--- Return a boolean showing if a table is or is not a vec2.
-- @tparam vec2 a Vector to be tested
-- @treturn boolean is_vec2
function vec2.is_vec2(a)
if type(a) == "cdata" then
return ffi.istype("cpml_vec2", a)
end
return
type(a) == "table" and
type(a.x) == "number" and
type(a.y) == "number"
end
--- Return a boolean showing if a table is or is not a zero vec2.
-- @tparam vec2 a Vector to be tested
-- @treturn boolean is_zero
function vec2.is_zero(a)
return a.x == 0 and a.y == 0
end
--- Convert point from cartesian to polar.
-- @tparam vec2 a Vector to convert
-- @treturn number radius
-- @treturn number theta
function vec2.to_polar(a)
local radius = sqrt(a.x^2 + a.y^2)
local theta = atan2(a.y, a.x)
theta = theta > 0 and theta or theta + 2 * math.pi
return radius, theta
end
-- Round all components to nearest int (or other precision).
-- @tparam vec2 a Vector to round.
-- @tparam precision Digits after the decimal (round numebr if unspecified)
-- @treturn vec2 Rounded vector
function vec2.round(a, precision)
return vec2.new(private.round(a.x, precision), private.round(a.y, precision))
end
-- Negate x axis only of vector.
-- @tparam vec2 a Vector to x-flip.
-- @treturn vec2 x-flipped vector
function vec2.flip_x(a)
return vec2.new(-a.x, a.y)
end
-- Negate y axis only of vector.
-- @tparam vec2 a Vector to y-flip.
-- @treturn vec2 y-flipped vector
function vec2.flip_y(a)
return vec2.new(a.x, -a.y)
end
-- Convert vec2 to vec3.
-- @tparam vec2 a Vector to convert.
-- @tparam number the new z component, or nil for 0
-- @treturn vec3 Converted vector
function vec2.to_vec3(a, z)
return vec3(a.x, a.y, z or 0)
end
--- Return a formatted string.
-- @tparam vec2 a Vector to be turned into a string
-- @treturn string formatted
function vec2.to_string(a)
return string.format("(%+0.3f,%+0.3f)", a.x, a.y)
end
vec2_mt.__index = vec2
vec2_mt.__tostring = vec2.to_string
function vec2_mt.__call(_, x, y)
return vec2.new(x, y)
end
function vec2_mt.__unm(a)
return new(-a.x, -a.y)
end
function vec2_mt.__eq(a, b)
if not vec2.is_vec2(a) or not vec2.is_vec2(b) then
return false
end
return a.x == b.x and a.y == b.y
end
function vec2_mt.__add(a, b)
assert(vec2.is_vec2(a), "__add: Wrong argument type for left hand operand. (<cpml.vec2> expected)")
assert(vec2.is_vec2(b), "__add: Wrong argument type for right hand operand. (<cpml.vec2> expected)")
return a:add(b)
end
function vec2_mt.__sub(a, b)
assert(vec2.is_vec2(a), "__add: Wrong argument type for left hand operand. (<cpml.vec2> expected)")
assert(vec2.is_vec2(b), "__add: Wrong argument type for right hand operand. (<cpml.vec2> expected)")
return a:sub(b)
end
function vec2_mt.__mul(a, b)
assert(vec2.is_vec2(a), "__mul: Wrong argument type for left hand operand. (<cpml.vec2> expected)")
assert(vec2.is_vec2(b) or type(b) == "number", "__mul: Wrong argument type for right hand operand. (<cpml.vec2> or <number> expected)")
if vec2.is_vec2(b) then
return a:mul(b)
end
return a:scale(b)
end
function vec2_mt.__div(a, b)
assert(vec2.is_vec2(a), "__div: Wrong argument type for left hand operand. (<cpml.vec2> expected)")
assert(vec2.is_vec2(b) or type(b) == "number", "__div: Wrong argument type for right hand operand. (<cpml.vec2> or <number> expected)")
if vec2.is_vec2(b) then
return a:div(b)
end
return a:scale(1 / b)
end
if status then
xpcall(function() -- Allow this to silently fail; assume failure means someone messed with package.loaded
ffi.metatype(new, vec2_mt)
end, function() end)
end
vec2 = setmetatable({}, vec2_mt)
end
--
-- BLOCK utils
--
do
--- Clamps a value within the specified range.
-- @param value Input value
-- @param min Minimum output value
-- @param max Maximum output value
-- @return number
function utils.clamp(value, min, max)
return math.max(math.min(value, max), min)
end
--- Returns `value` if it is equal or greater than |`size`|, or 0.
-- @param value
-- @param size
-- @return number
function utils.deadzone(value, size)
return abs(value) >= size and value or 0
end
--- Check if value is equal or greater than threshold.
-- @param value
-- @param threshold
-- @return boolean
function utils.threshold(value, threshold)
-- I know, it barely saves any typing at all.
return abs(value) >= threshold
end
--- Check if value is equal or less than threshold.
-- @param value
-- @param threshold
-- @return boolean
function utils.tolerance(value, threshold)
-- I know, it barely saves any typing at all.
return abs(value) <= threshold
end
--- Scales a value from one range to another.
-- @param value Input value
-- @param min_in Minimum input value
-- @param max_in Maximum input value
-- @param min_out Minimum output value
-- @param max_out Maximum output value
-- @return number
function utils.map(value, min_in, max_in, min_out, max_out)
return ((value) - (min_in)) * ((max_out) - (min_out)) / ((max_in) - (min_in)) + (min_out)
end
--- Linear interpolation.
-- Performs linear interpolation between 0 and 1 when `low` < `progress` < `high`.
-- @param low value to return when `progress` is 0
-- @param high value to return when `progress` is 1
-- @param progress (0-1)
-- @return number
function utils.lerp(low, high, progress)
return low * (1 - progress) + high * progress
end
--- Exponential decay
-- @param low initial value
-- @param high target value
-- @param rate portion of the original value remaining per second
-- @param dt time delta
-- @return number
function utils.decay(low, high, rate, dt)
return utils.lerp(low, high, 1.0 - math.exp(-rate * dt))
end
--- Hermite interpolation.
-- Performs smooth Hermite interpolation between 0 and 1 when `low` < `progress` < `high`.
-- @param progress (0-1)
-- @param low value to return when `progress` is 0
-- @param high value to return when `progress` is 1
-- @return number
function utils.smoothstep(progress, low, high)
local t = utils.clamp((progress - low) / (high - low), 0.0, 1.0)
return t * t * (3.0 - 2.0 * t)
end
--- Round number at a given precision.
-- Truncates `value` at `precision` points after the decimal (whole number if
-- left unspecified).
-- @param value
-- @param precision
-- @return number
utils.round = private.round
--- Wrap `value` around if it exceeds `limit`.
-- @param value
-- @param limit
-- @return number
function utils.wrap(value, limit)
if value < 0 then
value = value + utils.round(((-value/limit)+1))*limit
end
return value % limit
end
--- Check if a value is a power-of-two.
-- Returns true if a number is a valid power-of-two, otherwise false.
-- @author undef
-- @param value