summaryrefslogtreecommitdiff
path: root/honey/mesh.lua
diff options
context:
space:
mode:
authorsanine <sanine.not@pm.me>2023-03-13 02:42:16 -0500
committersanine <sanine.not@pm.me>2023-03-13 02:42:16 -0500
commit89572c1648128456822cf2dda07b13e78cfc2813 (patch)
tree78cafed06eb4cb261e53d0de28fa7e170ce55d6f /honey/mesh.lua
parentbb8c38bffba86cda05e0e8e9b52fb68301286b53 (diff)
render all shapes
Diffstat (limited to 'honey/mesh.lua')
-rw-r--r--honey/mesh.lua95
1 files changed, 95 insertions, 0 deletions
diff --git a/honey/mesh.lua b/honey/mesh.lua
new file mode 100644
index 0000000..430d5c3
--- /dev/null
+++ b/honey/mesh.lua
@@ -0,0 +1,95 @@
+local mesh = {}
+local gl = honey.gl
+setmetatable(mesh, {__index=_G})
+setfenv(1, mesh)
+
+
+local function insertVertex(vertices, attrib, vertex)
+ local pos = 3*vertex.v_idx
+ for i=1,3 do
+ table.insert(vertices, attrib.vertices[pos+i])
+ end
+
+ local normal = 3*vertex.vn_idx
+ for i=1,3 do
+ table.insert(vertices, attrib.normals[normal+i])
+ end
+
+ local tex = 3*vertex.vt_idx
+ for i=1,2 do
+ table.insert(vertices, attrib.texcoords[tex+i])
+ end
+end
+
+
+function loadShape(shape, attrib)
+ local vertices = {}
+ local indices = {}
+
+ local start = shape.face_offset
+ local finish = start + shape.length
+ for i=start,finish-1 do
+ assert(attrib.face_num_verts[i+1] == 3, "non-triangular face!")
+ for j=0,2 do
+ local vertex = attrib.faces[(3*i) + j + 1]
+ insertVertex(vertices, attrib, vertex)
+ table.insert(indices, #indices)
+ end
+ end
+
+ return vertices, indices
+end
+
+
+function loadFile(filename)
+ local flags = honey.tinyobj.FLAG_TRIANGULATE
+ local attrib, shapes, materials = honey.tinyobj.parse_obj(filename, flags)
+
+ local meshes = {}
+ for _, shape in ipairs(shapes) do
+ local vertices, indices = loadShape(shape, attrib)
+ table.insert(meshes, Mesh(vertices, indices))
+ end
+ return meshes
+end
+
+
+Mesh = {}
+Mesh.__index = Mesh
+
+
+function Mesh.new(_, vertices, indices)
+ local self = {}
+ setmetatable(self, Mesh)
+
+ self.vertexArray = gl.GenVertexArrays()
+ self.vertexBuffer = gl.GenBuffers()
+ self.elementBuffer = gl.GenBuffers()
+ self.vertexCount = #indices
+
+ 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, indices, gl.STATIC_DRAW)
+
+ gl.VertexAttribPointer(0, 3, false, 8, 0)
+ gl.EnableVertexAttribArray(0)
+ gl.VertexAttribPointer(1, 3, false, 8, 3)
+ gl.EnableVertexAttribArray(1)
+ gl.VertexAttribPointer(2, 2, false, 8, 6)
+ gl.EnableVertexAttribArray(2)
+
+ return self
+end
+setmetatable(Mesh, {__call=Mesh.new})
+
+
+function Mesh.drawElements(self)
+ gl.BindVertexArray(self.vertexArray)
+ gl.DrawElements(gl.TRIANGLES, self.vertexCount, gl.UNSIGNED_INT, 0)
+end
+
+
+return mesh