| 1 | require "dokidoki.module" |
| 2 | [[ make, unit, |
| 3 | add, sub, neg, mul, div, dot, cross, project, |
| 4 | mag, sqrmag, angle, norm, eq, coords, |
| 5 | rotate, rotate90, rotate_to, rotate_from, |
| 6 | random, |
| 7 | zero, i, j ]] |
| 8 | |
| 9 | function make (x, y) return setmetatable({x=x, y=y}, mt) end |
| 10 | local make = make |
| 11 | function unit (angle) return make(math.cos(angle), math.sin(angle)) end |
| 12 | |
| 13 | function add (a, b) return make(a.x + b.x, a.y + b.y) end |
| 14 | function sub (a, b) return make(a.x - b.x, a.y - b.y) end |
| 15 | function neg (v) return make(-v.x, -v.y) end |
| 16 | function mul (v, s) return make(s * v.x, s * v.y) end |
| 17 | function div (v, s) return make(v.x / s, v.y / s) end |
| 18 | function dot (a, b) return a.x * b.x + a.y * b.y end |
| 19 | function cross (a, b) return a.x * b.y - a.y * b.x end |
| 20 | function project(a, b) return b * (dot(a, b) / sqrmag(b)) end |
| 21 | |
| 22 | function mag (v) return math.sqrt(v.x * v.x + v.y * v.y) end |
| 23 | function sqrmag (v) return dot(v, v) end |
| 24 | function angle (v) return math.atan2(v.y, v.x) end |
| 25 | function norm (v) return v / mag(v) end |
| 26 | function eq (a, b) return a.x == b.x and a.y == b.y end |
| 27 | function coords (v) return v.x, v.y end |
| 28 | |
| 29 | function rotate(v, a) |
| 30 | local sin_a, cos_a = math.sin(a), math.cos(a) |
| 31 | return make(v.x * cos_a - v.y * sin_a, v.y * cos_a + v.x * sin_a) |
| 32 | end |
| 33 | |
| 34 | function rotate90(v) |
| 35 | return make(-v.y, v.x) |
| 36 | end |
| 37 | |
| 38 | function rotate_to(v, i) |
| 39 | return make(i.x * v.x - i.y * v.y, i.y * v.x + i.x * v.y) |
| 40 | end |
| 41 | |
| 42 | function rotate_from(v, i) |
| 43 | return make(i.x * v.x + i.y * v.y, - i.y * v.x + i.x * v.y) |
| 44 | end |
| 45 | |
| 46 | function random() |
| 47 | return unit(math.random() * math.pi * 2) * math.sqrt(math.random()) |
| 48 | end |
| 49 | |
| 50 | mt = |
| 51 | { |
| 52 | __add = add, |
| 53 | __sub = sub, |
| 54 | __mul = function (a, b) |
| 55 | return type(a) == 'number' and mul(b, a) or mul(a, b) |
| 56 | end, |
| 57 | __div = div, |
| 58 | __unm = neg, |
| 59 | __eq = eq, |
| 60 | |
| 61 | __tostring = function (v) |
| 62 | return '(' .. v.x .. ', ' .. v.y .. ')' |
| 63 | end, |
| 64 | } |
| 65 | |
| 66 | zero = make(0, 0) |
| 67 | i = make(1, 0) |
| 68 | j = make(0, 1) |
| 69 | |
| 70 | return setmetatable( |
| 71 | get_module_exports(), |
| 72 | {__call = function (_, x, y) return make(x, y) end}) |