aboutsummaryrefslogtreecommitdiff
path: root/libs/hump
diff options
context:
space:
mode:
Diffstat (limited to 'libs/hump')
-rw-r--r--libs/hump/camera.lua216
-rw-r--r--libs/hump/class.lua98
-rw-r--r--libs/hump/gamestate.lua116
-rw-r--r--libs/hump/timer.lua215
4 files changed, 645 insertions, 0 deletions
diff --git a/libs/hump/camera.lua b/libs/hump/camera.lua
new file mode 100644
index 0000000..cb86a79
--- /dev/null
+++ b/libs/hump/camera.lua
@@ -0,0 +1,216 @@
+--[[
+Copyright (c) 2010-2015 Matthias Richter
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+Except as contained in this notice, the name(s) of the above copyright holders
+shall not be used in advertising or otherwise to promote the sale, use or
+other dealings in this Software without prior written authorization.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+]]--
+
+local _PATH = (...):match('^(.*[%./])[^%.%/]+$') or ''
+local cos, sin = math.cos, math.sin
+
+local camera = {}
+camera.__index = camera
+
+-- Movement interpolators (for camera locking/windowing)
+camera.smooth = {}
+
+function camera.smooth.none()
+ return function(dx,dy) return dx,dy end
+end
+
+function camera.smooth.linear(speed)
+ assert(type(speed) == "number", "Invalid parameter: speed = "..tostring(speed))
+ return function(dx,dy, s)
+ -- normalize direction
+ local d = math.sqrt(dx*dx+dy*dy)
+ local dts = math.min((s or speed) * love.timer.getDelta(), d) -- prevent overshooting the goal
+ if d > 0 then
+ dx,dy = dx/d, dy/d
+ end
+
+ return dx*dts, dy*dts
+ end
+end
+
+function camera.smooth.damped(stiffness)
+ assert(type(stiffness) == "number", "Invalid parameter: stiffness = "..tostring(stiffness))
+ return function(dx,dy, s)
+ local dts = love.timer.getDelta() * (s or stiffness)
+ return dx*dts, dy*dts
+ end
+end
+
+
+local function new(x,y, zoom, rot, smoother)
+ x,y = x or love.graphics.getWidth()/2, y or love.graphics.getHeight()/2
+ zoom = zoom or 1
+ rot = rot or 0
+ smoother = smoother or camera.smooth.none() -- for locking, see below
+ return setmetatable({x = x, y = y, scale = zoom, rot = rot, smoother = smoother}, camera)
+end
+
+function camera:lookAt(x,y)
+ self.x, self.y = x, y
+ return self
+end
+
+function camera:move(dx,dy)
+ self.x, self.y = self.x + dx, self.y + dy
+ return self
+end
+
+function camera:position()
+ return self.x, self.y
+end
+
+function camera:rotate(phi)
+ self.rot = self.rot + phi
+ return self
+end
+
+function camera:rotateTo(phi)
+ self.rot = phi
+ return self
+end
+
+function camera:zoom(mul)
+ self.scale = self.scale * mul
+ return self
+end
+
+function camera:zoomTo(zoom)
+ self.scale = zoom
+ return self
+end
+
+function camera:attach(x,y,w,h, noclip)
+ x,y = x or 0, y or 0
+ w,h = w or love.graphics.getWidth(), h or love.graphics.getHeight()
+
+ self._sx,self._sy,self._sw,self._sh = love.graphics.getScissor()
+ if not noclip then
+ love.graphics.setScissor(x,y,w,h)
+ end
+
+ local cx,cy = x+w/2, y+h/2
+ love.graphics.push()
+ love.graphics.translate(cx, cy)
+ love.graphics.scale(self.scale)
+ love.graphics.rotate(self.rot)
+ love.graphics.translate(-self.x, -self.y)
+end
+
+function camera:detach()
+ love.graphics.pop()
+ love.graphics.setScissor(self._sx,self._sy,self._sw,self._sh)
+end
+
+function camera:draw(...)
+ local x,y,w,h,noclip,func
+ local nargs = select("#", ...)
+ if nargs == 1 then
+ func = ...
+ elseif nargs == 5 then
+ x,y,w,h,func = ...
+ elseif nargs == 6 then
+ x,y,w,h,noclip,func = ...
+ else
+ error("Invalid arguments to camera:draw()")
+ end
+
+ self:attach(x,y,w,h,noclip)
+ func()
+ self:detach()
+end
+
+-- world coordinates to camera coordinates
+function camera:cameraCoords(x,y, ox,oy,w,h)
+ ox, oy = ox or 0, oy or 0
+ w,h = w or love.graphics.getWidth(), h or love.graphics.getHeight()
+
+ -- x,y = ((x,y) - (self.x, self.y)):rotated(self.rot) * self.scale + center
+ local c,s = cos(self.rot), sin(self.rot)
+ x,y = x - self.x, y - self.y
+ x,y = c*x - s*y, s*x + c*y
+ return x*self.scale + w/2 + ox, y*self.scale + h/2 + oy
+end
+
+-- camera coordinates to world coordinates
+function camera:worldCoords(x,y, ox,oy,w,h)
+ ox, oy = ox or 0, oy or 0
+ w,h = w or love.graphics.getWidth(), h or love.graphics.getHeight()
+
+ -- x,y = (((x,y) - center) / self.scale):rotated(-self.rot) + (self.x,self.y)
+ local c,s = cos(-self.rot), sin(-self.rot)
+ x,y = (x - w/2 - ox) / self.scale, (y - h/2 - oy) / self.scale
+ x,y = c*x - s*y, s*x + c*y
+ return x+self.x, y+self.y
+end
+
+function camera:mousePosition(ox,oy,w,h)
+ local mx,my = love.mouse.getPosition()
+ return self:worldCoords(mx,my, ox,oy,w,h)
+end
+
+-- camera scrolling utilities
+function camera:lockX(x, smoother, ...)
+ local dx, dy = (smoother or self.smoother)(x - self.x, self.y, ...)
+ self.x = self.x + dx
+ return self
+end
+
+function camera:lockY(y, smoother, ...)
+ local dx, dy = (smoother or self.smoother)(self.x, y - self.y, ...)
+ self.y = self.y + dy
+ return self
+end
+
+function camera:lockPosition(x,y, smoother, ...)
+ return self:move((smoother or self.smoother)(x - self.x, y - self.y, ...))
+end
+
+function camera:lockWindow(x, y, x_min, x_max, y_min, y_max, smoother, ...)
+ -- figure out displacement in camera coordinates
+ x,y = self:cameraCoords(x,y)
+ local dx, dy = 0,0
+ if x < x_min then
+ dx = x - x_min
+ elseif x > x_max then
+ dx = x - x_max
+ end
+ if y < y_min then
+ dy = y - y_min
+ elseif y > y_max then
+ dy = y - y_max
+ end
+
+ -- transform displacement to movement in world coordinates
+ local c,s = cos(-self.rot), sin(-self.rot)
+ dx,dy = (c*dx - s*dy) / self.scale, (s*dx + c*dy) / self.scale
+
+ -- move
+ self:move((smoother or self.smoother)(dx,dy,...))
+end
+
+-- the module
+return setmetatable({new = new, smooth = camera.smooth},
+ {__call = function(_, ...) return new(...) end})
diff --git a/libs/hump/class.lua b/libs/hump/class.lua
new file mode 100644
index 0000000..7d62707
--- /dev/null
+++ b/libs/hump/class.lua
@@ -0,0 +1,98 @@
+--[[
+Copyright (c) 2010-2013 Matthias Richter
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+Except as contained in this notice, the name(s) of the above copyright holders
+shall not be used in advertising or otherwise to promote the sale, use or
+other dealings in this Software without prior written authorization.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+]]--
+
+local function include_helper(to, from, seen)
+ if from == nil then
+ return to
+ elseif type(from) ~= 'table' then
+ return from
+ elseif seen[from] then
+ return seen[from]
+ end
+
+ seen[from] = to
+ for k,v in pairs(from) do
+ k = include_helper({}, k, seen) -- keys might also be tables
+ if to[k] == nil then
+ to[k] = include_helper({}, v, seen)
+ end
+ end
+ return to
+end
+
+-- deeply copies `other' into `class'. keys in `other' that are already
+-- defined in `class' are omitted
+local function include(class, other)
+ return include_helper(class, other, {})
+end
+
+-- returns a deep copy of `other'
+local function clone(other)
+ return setmetatable(include({}, other), getmetatable(other))
+end
+
+local function new(class)
+ -- mixins
+ class = class or {} -- class can be nil
+ local inc = class.__includes or {}
+ if getmetatable(inc) then inc = {inc} end
+
+ for _, other in ipairs(inc) do
+ if type(other) == "string" then
+ other = _G[other]
+ end
+ include(class, other)
+ end
+
+ -- class implementation
+ class.__index = class
+ class.init = class.init or class[1] or function() end
+ class.include = class.include or include
+ class.clone = class.clone or clone
+
+ -- constructor call
+ return setmetatable(class, {__call = function(c, ...)
+ local o = setmetatable({}, c)
+ o:init(...)
+ return o
+ end})
+end
+
+-- interface for cross class-system compatibility (see https://github.com/bartbes/Class-Commons).
+if class_commons ~= false and not common then
+ common = {}
+ function common.class(name, prototype, parent)
+ return new{__includes = {prototype, parent}}
+ end
+ function common.instance(class, ...)
+ return class(...)
+ end
+end
+
+
+-- the module
+return setmetatable({new = new, include = include, clone = clone},
+ {__call = function(_,...) return new(...) end})
diff --git a/libs/hump/gamestate.lua b/libs/hump/gamestate.lua
new file mode 100644
index 0000000..059dbb9
--- /dev/null
+++ b/libs/hump/gamestate.lua
@@ -0,0 +1,116 @@
+--[[
+Copyright (c) 2010-2013 Matthias Richter
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+Except as contained in this notice, the name(s) of the above copyright holders
+shall not be used in advertising or otherwise to promote the sale, use or
+other dealings in this Software without prior written authorization.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+]]--
+
+local function __NULL__() end
+
+ -- default gamestate produces error on every callback
+local state_init = setmetatable({leave = __NULL__},
+ {__index = function() error("Gamestate not initialized. Use Gamestate.switch()") end})
+local stack = {state_init}
+local initialized_states = setmetatable({}, {__mode = "k"})
+local state_is_dirty = true
+
+local GS = {}
+function GS.new(t) return t or {} end -- constructor - deprecated!
+
+local function change_state(stack_offset, to, ...)
+ local pre = stack[#stack]
+
+ -- initialize only on first call
+ ;(initialized_states[to] or to.init or __NULL__)(to)
+ initialized_states[to] = __NULL__
+
+ stack[#stack+stack_offset] = to
+ state_is_dirty = true
+ return (to.enter or __NULL__)(to, pre, ...)
+end
+
+function GS.switch(to, ...)
+ assert(to, "Missing argument: Gamestate to switch to")
+ assert(to ~= GS, "Can't call switch with colon operator")
+ ;(stack[#stack].leave or __NULL__)(stack[#stack])
+ return change_state(0, to, ...)
+end
+
+function GS.push(to, ...)
+ assert(to, "Missing argument: Gamestate to switch to")
+ assert(to ~= GS, "Can't call push with colon operator")
+ return change_state(1, to, ...)
+end
+
+function GS.pop(...)
+ assert(#stack > 1, "No more states to pop!")
+ local pre, to = stack[#stack], stack[#stack-1]
+ stack[#stack] = nil
+ ;(pre.leave or __NULL__)(pre)
+ state_is_dirty = true
+ return (to.resume or __NULL__)(to, pre, ...)
+end
+
+function GS.current()
+ return stack[#stack]
+end
+
+-- XXX: don't overwrite love.errorhandler by default:
+-- this callback is different than the other callbacks
+-- (see http://love2d.org/wiki/love.errorhandler)
+-- overwriting thi callback can result in random crashes (issue #95)
+local all_callbacks = { 'draw', 'update' }
+
+-- fetch event callbacks from love.handlers
+for k in pairs(love.handlers) do
+ all_callbacks[#all_callbacks+1] = k
+end
+
+function GS.registerEvents(callbacks)
+ local registry = {}
+ callbacks = callbacks or all_callbacks
+ for _, f in ipairs(callbacks) do
+ registry[f] = love[f] or __NULL__
+ love[f] = function(...)
+ registry[f](...)
+ return GS[f](...)
+ end
+ end
+end
+
+local function_cache = {}
+
+-- forward any undefined functions
+setmetatable(GS, {__index = function(_, func)
+ -- call function only if at least one 'update' was called beforehand
+ -- (see issue #46)
+ if not state_is_dirty or func == 'update' then
+ state_is_dirty = false
+ function_cache[func] = function_cache[func] or function(...)
+ return (stack[#stack][func] or __NULL__)(stack[#stack], ...)
+ end
+ return function_cache[func]
+ end
+ return __NULL__
+end})
+
+return GS
diff --git a/libs/hump/timer.lua b/libs/hump/timer.lua
new file mode 100644
index 0000000..8315f68
--- /dev/null
+++ b/libs/hump/timer.lua
@@ -0,0 +1,215 @@
+--[[
+Copyright (c) 2010-2013 Matthias Richter
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+Except as contained in this notice, the name(s) of the above copyright holders
+shall not be used in advertising or otherwise to promote the sale, use or
+other dealings in this Software without prior written authorization.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+]]--
+
+local Timer = {}
+Timer.__index = Timer
+
+local function _nothing_() end
+
+local function updateTimerHandle(handle, dt)
+ -- handle: {
+ -- time = <number>,
+ -- after = <function>,
+ -- during = <function>,
+ -- limit = <number>,
+ -- count = <number>,
+ -- }
+ handle.time = handle.time + dt
+ handle.during(dt, math.max(handle.limit - handle.time, 0))
+
+ while handle.time >= handle.limit and handle.count > 0 do
+ if handle.after(handle.after) == false then
+ handle.count = 0
+ break
+ end
+ handle.time = handle.time - handle.limit
+ handle.count = handle.count - 1
+ end
+end
+
+function Timer:update(dt)
+ -- timers may create new timers, which leads to undefined behavior
+ -- in pairs() - so we need to put them in a different table first
+ local to_update = {}
+ for handle in pairs(self.functions) do
+ to_update[handle] = handle
+ end
+
+ for handle in pairs(to_update) do
+ if self.functions[handle] then
+ updateTimerHandle(handle, dt)
+ if handle.count == 0 then
+ self.functions[handle] = nil
+ end
+ end
+ end
+end
+
+function Timer:during(delay, during, after)
+ local handle = { time = 0, during = during, after = after or _nothing_, limit = delay, count = 1 }
+ self.functions[handle] = true
+ return handle
+end
+
+function Timer:after(delay, func)
+ return self:during(delay, _nothing_, func)
+end
+
+function Timer:every(delay, after, count)
+ local count = count or math.huge -- exploit below: math.huge - 1 = math.huge
+ local handle = { time = 0, during = _nothing_, after = after, limit = delay, count = count }
+ self.functions[handle] = true
+ return handle
+end
+
+function Timer:cancel(handle)
+ self.functions[handle] = nil
+end
+
+function Timer:clear()
+ self.functions = {}
+end
+
+function Timer:script(f)
+ local co = coroutine.wrap(f)
+ co(function(t)
+ self:after(t, co)
+ coroutine.yield()
+ end)
+end
+
+Timer.tween = setmetatable({
+ -- helper functions
+ out = function(f) -- 'rotates' a function
+ return function(s, ...) return 1 - f(1-s, ...) end
+ end,
+ chain = function(f1, f2) -- concatenates two functions
+ return function(s, ...) return (s < .5 and f1(2*s, ...) or 1 + f2(2*s-1, ...)) * .5 end
+ end,
+
+ -- useful tweening functions
+ linear = function(s) return s end,
+ quad = function(s) return s*s end,
+ cubic = function(s) return s*s*s end,
+ quart = function(s) return s*s*s*s end,
+ quint = function(s) return s*s*s*s*s end,
+ sine = function(s) return 1-math.cos(s*math.pi/2) end,
+ expo = function(s) return 2^(10*(s-1)) end,
+ circ = function(s) return 1 - math.sqrt(1-s*s) end,
+
+ back = function(s,bounciness)
+ bounciness = bounciness or 1.70158
+ return s*s*((bounciness+1)*s - bounciness)
+ end,
+
+ bounce = function(s) -- magic numbers ahead
+ local a,b = 7.5625, 1/2.75
+ return math.min(a*s^2, a*(s-1.5*b)^2 + .75, a*(s-2.25*b)^2 + .9375, a*(s-2.625*b)^2 + .984375)
+ end,
+
+ elastic = function(s, amp, period)
+ amp, period = amp and math.max(1, amp) or 1, period or .3
+ return (-amp * math.sin(2*math.pi/period * (s-1) - math.asin(1/amp))) * 2^(10*(s-1))
+ end,
+}, {
+
+-- register new tween
+__call = function(tween, self, len, subject, target, method, after, ...)
+ -- recursively collects fields that are defined in both subject and target into a flat list
+ local function tween_collect_payload(subject, target, out)
+ for k,v in pairs(target) do
+ local ref = subject[k]
+ assert(type(v) == type(ref), 'Type mismatch in field "'..k..'".')
+ if type(v) == 'table' then
+ tween_collect_payload(ref, v, out)
+ else
+ local ok, delta = pcall(function() return (v-ref)*1 end)
+ assert(ok, 'Field "'..k..'" does not support arithmetic operations')
+ out[#out+1] = {subject, k, delta}
+ end
+ end
+ return out
+ end
+
+ method = tween[method or 'linear'] -- see __index
+ local payload, t, args = tween_collect_payload(subject, target, {}), 0, {...}
+
+ local last_s = 0
+ return self:during(len, function(dt)
+ t = t + dt
+ local s = method(math.min(1, t/len), unpack(args))
+ local ds = s - last_s
+ last_s = s
+ for _, info in ipairs(payload) do
+ local ref, key, delta = unpack(info)
+ ref[key] = ref[key] + delta * ds
+ end
+ end, after)
+end,
+
+-- fetches function and generated compositions for method `key`
+__index = function(tweens, key)
+ if type(key) == 'function' then return key end
+
+ assert(type(key) == 'string', 'Method must be function or string.')
+ if rawget(tweens, key) then return rawget(tweens, key) end
+
+ local function construct(pattern, f)
+ local method = rawget(tweens, key:match(pattern))
+ if method then return f(method) end
+ return nil
+ end
+
+ local out, chain = rawget(tweens,'out'), rawget(tweens,'chain')
+ return construct('^in%-([^-]+)$', function(...) return ... end)
+ or construct('^out%-([^-]+)$', out)
+ or construct('^in%-out%-([^-]+)$', function(f) return chain(f, out(f)) end)
+ or construct('^out%-in%-([^-]+)$', function(f) return chain(out(f), f) end)
+ or error('Unknown interpolation method: ' .. key)
+end})
+
+-- Timer instancing
+function Timer.new()
+ return setmetatable({functions = {}, tween = Timer.tween}, Timer)
+end
+
+-- default instance
+local default = Timer.new()
+
+-- module forwards calls to default instance
+local module = {}
+for k in pairs(Timer) do
+ if k ~= "__index" then
+ module[k] = function(...) return default[k](default, ...) end
+ end
+end
+module.tween = setmetatable({}, {
+ __index = Timer.tween,
+ __newindex = function(k,v) Timer.tween[k] = v end,
+ __call = function(t, ...) return default:tween(...) end,
+})
+
+return setmetatable(module, {__call = Timer.new})