summaryrefslogtreecommitdiff
path: root/honey/ecs/collision.lua
blob: 5c0452bdc7dd70012be69fad080199c82e1e1fff (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
local glm = require 'honey.glm'
local Vec3 = glm.Vec3
local ode = honey.ode

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


--===== collision space =====--


local function createGeom(self, id, collision)
	local geom
	if collision.class == "sphere" then
		geom = ode.CreateSphere(self.space, collision.radius)
	elseif collision.class == "capsule" then
		geom = ode.CreateCapsule(self.space, collision.radius, collision.length)
	elseif collision.class == "plane" then
		local node = self.db:getComponent(id, "node")
		local m = node.matrix
		local normal = node.matrix:mulv3(Vec3{0,1,0}):normalize()
		local position = Vec3{m[1][4], m[2][4], m[3][4]}
		print(position)
		local d = normal:dot(position)
		print(normal, d)
		geom = ode.CreatePlane(self.space, normal[1], normal[2], normal[3], d)
	end

	ode.GeomSetData(geom, id)
	
	collision._geom = geom
	collision._gc = honey.util.gc_canary(function()
		print("release geom for id"..id)
		ode.GeomDestroy(geom)
	end)
end

system = function(params)
	local db = params.db
	local space = params.space
	return {
		db=db,
		space=space,
		priority=0,
		update = function(self, dt)
			local query = self.db:queryComponent("collision")
			for id, collision in pairs(query) do
				if not collision._geom then
					createGeom(self, id, collision)
					print(id, collision._geom)
				end
			end
		end
	}
end



return module