Skip to content

Instantly share code, notes, and snippets.

@bortels
Created November 2, 2012 04:05
Show Gist options
  • Save bortels/3998656 to your computer and use it in GitHub Desktop.
Save bortels/3998656 to your computer and use it in GitHub Desktop.
PLY loading class for Codea
-- minor modifications from https://dl.dropbox.com/u/80475380/CodeaForumPictures/Main.lua
--
-- call with m = PLY:parsePLY(string)
PLY = class()
function PLY:readLine()
-- Read one line of ply string. Return without \n. Return nil, if end is reached.
local endLine = false
local c
local maxLen = string.len(self.data)
local startIdx = self.idx
local endIdx = selfidx
if startIdx >= maxLen then
return nil
end
while endLine == false do
if self.idx > maxLen then
endLine = true
endIdx = maxLen
else
c = string.sub(self.data, self.idx, self.idx)
if c == '\n' then
endLine = true
endIdx = self.idx - 1
end
self.idx = self.idx + 1
end
end
return string.sub(self.data, startIdx, endIdx) -- Without \n
end
function PLY:parsePLY(d)
self.data = d
self.idx = 1
msh = mesh()
-- Parse PLY string.
local l = ""
local nrVtx = 0
l = PLY:readLine()
nrVtx = l
local nrTri = 0
l = PLY:readLine()
nrTri = l
-- Iterate vertices:
local vertices = {}
local normals = {}
local texCoords = {}
for i = 1,nrVtx do
l = PLY:readLine()
local token
local lineTbl = {}
for token in string.gmatch(l, "[^%s]+") do
table.insert(lineTbl, token)
end
table.insert(vertices, vec3(lineTbl[1], lineTbl[2], lineTbl[3]))
table.insert(normals, vec3(lineTbl[4], lineTbl[5], lineTbl[6]))
table.insert(texCoords, vec2(lineTbl[7], lineTbl[8]))
end
local mshVertices = {}
local mshTexCoords = {}
-- Iterate faces:
print (nrTri.." Triangles:")
for i = 1,nrTri do
l = PLY:readLine()
local token
local id = 0
for token in string.gmatch(l, "[^%s]+") do
if id > 0 then -- Ignore first number which is # of vertices (which is 3 here).
local idx = token + 1
local v3 = vertices[idx]
table.insert(mshVertices, v3)
local v2 = texCoords[idx]
table.insert(mshTexCoords, v2)
end
id = id + 1
end
end
-- msh.texture = readImage("Dropbox:monkey_2")
msh.vertices = mshVertices
msh.colors = colors
msh.texCoords = mshTexCoords
msh:setColors(255,255,255,255)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment