Skip to content

Instantly share code, notes, and snippets.

@td2sk
Last active June 1, 2016 13:18
Show Gist options
  • Save td2sk/1b2817326faf9721d407236d9500ed83 to your computer and use it in GitHub Desktop.
Save td2sk/1b2817326faf9721d407236d9500ed83 to your computer and use it in GitHub Desktop.
-- This is free and unencumbered software released into the public domain.
local function cubic_bezier_implicit(t, p1, p2)
return p1 * (1-t) ^ 2 * t + p2 * (1-t) * t ^ 2 + t ^ 3
end
local function t_search(x, p1, p2)
if x == 0 then
return 0
elseif x == 1 then
return 1
end
local eps = 2 ^ -16
local tmin = 0.0
local tmax = 1.0
local t_guess
local x_guess
while true do
t_guess = (tmin + tmax) / 2
x_guess = cubic_bezier_implicit(t_guess, p1, p2)
if (tmax - tmin < eps) then
return t_guess
elseif (math.abs(x_guess - x) < eps) then
return t_guess
elseif x_guess < x then
tmin = t_guess
else
tmax = t_guess
end
end
end
mod = {}
function mod.cubic_bezier(n, p1x, p1y, p2x, p2y)
return coroutine.create(function()
for i = 1, n - 1 do
t_guess = t_search(i / n, p1x, p2x)
coroutine.yield(cubic_bezier_implicit(t_guess, p1y, p2y))
end
while true do
coroutine.yield(1)
end
end)
end
function mod.ease(n)
return mod.cubic_bezier(n, 0.25, 0.1, 0.25, 1.0)
end
function mod.linear(n)
return coroutine.create(function()
for i = 1, n - 1 do
coroutine.yield(i / n)
end
while true do
coroutine.yield(1)
end
end)
end
function mod.ease_in(n)
return mod.cubic_bezier(n, 0.42, 0.0, 1.0, 1.0)
end
function mod.ease_out(n)
return mod.cubic_bezier(n, 0.0, 0.0, 0.58, 1.0)
end
function mod.ease_in_out(n)
return mod.cubic_bezier(0.42, 0.0, 0.58, 1.0)
end
return mod
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment