aboutsummaryrefslogtreecommitdiff
path: root/src/utils.lua
blob: 5b8258c2ec5b796d59ddb9df427532e54018f974 (plain)
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
function is_filetype(filename, types)
  types = types or {}

  for _, type in ipairs(types) do
    if filename:match("%."..type.."$") then
      return true
    end
  end
  return false
end

function randf_range(max, min)
  return math.random() * (max - min) + min
end

function lerp(a, b, c)
  return a + (b - a) * c
end

function dlerp(a, b, c)
  return lerp(b, a, 0.5^c)
end

function bton(bool)
  return bool and 1 or 0
end

function try(fn, ...)
  if fn then
    fn(...)
  end
end

function min(a, b)
  if a < b then
    return a
  end
  return b
end

function normalize(x, y)
  if x == 0 and y == 0 then
    return 0, 0
  end

  local leng = math.sqrt(x*x + y*y)
  return x / leng, y / leng
end

-- Top left corner
function point_in_rect(px, py, rx, ry, rw, rh)
  return px > rx and px < rx + rw and py > ry and py < ry + rh
end

function dist(x1, y1, x2, y2)
  local dx = x1 - x2
  local dy = y1 - y2
  return (dx*dx + dy*dy)^0.5
end

function sign(x)
  if x == 0 then
    return 0
  end
  return x < 0 and -1 or 1
end

function round(x)
  return math.floor(x + 0.5)
end

function clamp(a, min, max)
  return math.min(max, math.max(a, min))
end

function snap(x, step)
  return round(x / step) * step
end

function frac(x)
  return x - math.floor(x)
end

local function angle_diff(a, b)
  local diff = (b - a) % (math.pi * 2)
  return (2 * diff) % (math.pi * 2) - diff
end

function lerp_angle(a, b, t)
  return a + angle_diff(a, b) * (1 - 0.5^t)
end

function dot(x, y, xx, yy)
  return x*xx + y*yy
end

function vec_sqlen(x, y)
  return x*x + y*y
end

function vec_len(x, y)
  return math.sqrt(x*x + y*y)
end

function rotate_vec(x, y, r)
  local angle = math.atan2(y, x) + r
  local len = mathx.vec_len(x, y)
  return math.cos(angle) * len, math.sin(angle) * len
end

function table.shallow_copy(t)
  local t2 = {}
  for k,v in pairs(t) do
    t2[k] = v
  end
  return t2
end

function table.deep_copy(datatable)
  local tblRes={}
  if type(datatable)=="table" then
    for k,v in pairs(datatable) do 
      tblRes[table.deep_copy(k)] = table.deep_copy(v) 
    end
  else
    tblRes=datatable
  end
  return tblRes
end

EASING_FUNCTIONS = {
  Lerp = lerp
}