summaryrefslogtreecommitdiff
path: root/honey/ecs/script.lua
blob: a9b76449becb649bb0da7b151d5937bff493b915 (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
local glfw = honey.glfw

local ecs  = require 'honey.ecs.ecs'
local node = require 'honey.ecs.node'

local module = {}
setmetatable(module, {__index=_G})
setfenv(1, module)


-- helper function for retrieving script functions 
getFunction = function(script)
	local f = require(script.script)
	if script.func then
		return f[script.func]
	else
		return f
	end
end


--===== dispatch messages to handlers =====--

dispatch = function(db, msg, data)
	local query = db:queryComponent(msg)
	for id, handler in pairs(query) do
		local f = getFunction(handler)
		f(entities, id, data)
	end
end

--===== bind window events to script handlers =====--

bindEvents = function(window, db)
	glfw.SetFramebufferSizeCallback(window, function(w, width, height)
		dispatch(db, "onFramebufferSize", {window=w, width=width, height=height})
	end)
	
	glfw.SetKeyCallback(window, function(w, key, scancode, action, mods)
		dispatch(db, "onKey", {window=w, key=key, scancode=scancode, action=action, mods=mods})
	end)

	glfw.SetCursorPosCallback(window, function(w, xpos, ypos)
		dispatch(db, "onCursorPos", {window=w, xpos=xpos, ypos=ypos})
	end)

	glfw.SetMouseButtonCallback(window, function(w, button, action, mods)
		dispatch(db, "onMouseButton", {window=w, button=button, action=action, mods=mods})
	end)
end

--===== script system =====--

local script = ecs.System("script", function(db, dt, params)
	local entities = db:queryComponent("script")
	for id, script in pairs(entities) do
		local f = getFunction(script)
		f(db, id, dt)
	end
end)
script:addDependencies(node.system)

system = {script}


return module