Skip to content

Instantly share code, notes, and snippets.

@meta-hub
Last active August 4, 2022 04:29
Show Gist options
  • Save meta-hub/bc582cb05017663bfc7d556af7ae57d5 to your computer and use it in GitHub Desktop.
Save meta-hub/bc582cb05017663bfc7d556af7ae57d5 to your computer and use it in GitHub Desktop.
A curve metatable for lua.
local Curve = {}
function Curve:get(time)
for i=2,#self.keys,1 do
local nextKey = self.keys[i]
local preKey = self.keys[i-1]
if (nextKey.time == time) then
return nextKey.value
end
if (nextKey.time > time) then
local f = Curve.InverseLerp(preKey.time,nextKey.time,time)
return Curve.Lerp(preKey.value,nextKey.value,f)
end
end
return 0
end
function Curve:addKey(time,value)
table.insert(self.keys,{
time = time,
value = value,
})
table.sort(self.keys,function(a,b)
return a.time < b.time
end)
end
function Curve:flat()
local values = {}
for i=1,#self.keys,1 do
table.insert(values,self.keys[i].value)
end
return values
end
Curve.Lerp = function(a,b,f)
return a + ( b - a ) * Curve.Clamp01(f)
end
Curve.InverseLerp = function(a,b,f)
return Curve.Clamp01((f - a) / (b - a))
end
Curve.Clamp01 = function(f)
return math.min(1,math.max(0,f))
end
Curve.__index = Curve
setmetatable(Curve,{
__call = function(self,t)
local keys = t or {}
table.sort(keys,function(a,b)
return a.time < b.time
end)
return setmetatable({keys = keys},self)
end
})
--[[
local curve = Curve()
curve:addKey(0.00, 0.00)
curve:addKey(1.00, 1.00)
curve:addKey(0.50, 0.75)
print( curve:get(0.00) )
print( curve:get(0.25) )
print( curve:get(0.50) )
print( curve:get(0.75) )
print( curve:get(1.00) )
> 0.0
> 0.375
> 0.75
> 0.875
> 1.0
--]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment