summaryrefslogtreecommitdiff
path: root/demo/first_person/mesh.lua
blob: cbaf5aa58fc83b307479612b92df5923335265c2 (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
local Mesh = {}
local gl = honey.gl
setmetatable(Mesh, {__index=_G})
setfenv(1, Mesh)


--===== creation =====--

local function loadScene(filename)
	local scene = honey.import.importFile(filename)
	local mesh = scene.meshes[1]
	local vertices = {}

	for i=1,#mesh.vertices do
		local position = mesh.vertices[i]
		local uv = mesh.uvs[1][i]
		local normal = mesh.normals[i]
		table.insert(vertices, position.x)
		table.insert(vertices, position.y)
		table.insert(vertices, position.z)

		table.insert(vertices, normal.x)
		table.insert(vertices, normal.y)
		table.insert(vertices, normal.z)

		table.insert(vertices, uv.x)
		table.insert(vertices, uv.y)
	end

	local elements = {}
	for _, face in ipairs(mesh.faces) do
		assert(#face == 3)
		for _, i in ipairs(face) do
			table.insert(elements, i)
		end
	end

	return vertices, elements
end


function Load(filename)
	local self = {}
	setmetatable(self, {__index=Mesh})

	self.transform = honey.glm.mat4()
	honey.glm.mat4_identity(self.transform)

	-- opengl mesh data
	self.vertexArray = gl.GenVertexArrays()
	self.vertexBuffer = gl.GenBuffers()
	self.elementBuffer = gl.GenBuffers()

	-- load data
	local vertices, elements = loadScene(filename)
	self.elementCount = #elements

	-- buffer data
	gl.BindVertexArray(self.vertexArray)
	gl.BindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer)
	gl.BufferData(gl.ARRAY_BUFFER, gl.FLOAT, vertices, gl.STATIC_DRAW)

	gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.elementBuffer)
	gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, gl.UNSIGNED_INT, elements, gl.STATIC_DRAW)

	-- set vertex attributes
	-- position
	gl.VertexAttribPointer(0, 3, false, 8, 0)
	gl.EnableVertexAttribArray(0)
	-- normals
	gl.VertexAttribPointer(1, 3, false, 8, 3)
	gl.EnableVertexAttribArray(1)
	-- uvs
	gl.VertexAttribPointer(2, 2, false, 8, 6)
	gl.EnableVertexAttribArray(2)

	return self
end


--===== methods =====--

local function vectorToTable(v)
	local tbl = {
		x = honey.glm.vec3_get(v, 0),
		y = honey.glm.vec3_get(v, 1),
		z = honey.glm.vec3_get(v, 2),
	}
	return tbl
end

function SetPosition(self, position)
	honey.glm.mat4_identity(self.transform)
	honey.glm.translate(self.transform, position)
end


function Draw(self)
	gl.BindVertexArray(self.vertexArray)
	gl.DrawElements(gl.TRIANGLES, self.elementCount, gl.UNSIGNED_INT, 0)
end


--===== fin =====--

return Mesh