CapsAdmin

Untitled

Jun 10th, 2013
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.32 KB | None | 0 0
  1. function decode_obj(data)
  2.    
  3.     local vertices = {}
  4.     local normals = {}
  5.     local uvs = {}
  6.    
  7.     local function insert_triangle(output, indexes)
  8.         local triangle = {}
  9.        
  10.         local vertex_i, uv_i, normal_i = indexes:match("(%d+)/(%d+)/(%d+)")
  11.        
  12.         vertex_i = tonumber(vertex_i)
  13.         uv_i = tonumber(uv_i)
  14.         normal_i = tonumber(normal_i)
  15.        
  16.         if vertex_i then
  17.             triangle.pos = vertices[vertex_i]
  18.         end
  19.        
  20.         if uv_i then
  21.             triangle.uv = uvs[uv_i]
  22.         end
  23.        
  24.         if normal_i then
  25.             triangle.normal = normals[normal_i]
  26.         end
  27.        
  28.         table.insert(output, triangle)
  29.     end
  30.    
  31.     -- get all the types
  32.     for type, x, y, z in data:gmatch("(.-)%s+(.-)%s+(.-)%s+(.-)\n") do
  33.         if type == "v" then
  34.             table.insert(vertices, Vec3(tonumber(x),tonumber(y),tonumber(z)))
  35.         end
  36.        
  37.         if type == "vn" then
  38.             table.insert(normals, Vec3(tonumber(x),tonumber(y),tonumber(z)))
  39.         end
  40.        
  41.         if type == "vt" then
  42.             table.insert(uvs, Vec2(tonumber(x),tonumber(y)))
  43.         end
  44.     end
  45.    
  46.     local output = {}
  47.    
  48.     -- assemble them
  49.     for type, a, b, c, d in data:gmatch("(.-)%s+(.-)%s+(.-)%s+(.-)\n") do
  50.         if type == "f" then
  51.             if a and b and c then
  52.                 insert_triangle(output, a)
  53.                 insert_triangle(output, c)
  54.                 insert_triangle(output, b)
  55.             elseif a and b and c and d then
  56.                 error("quad is not implemented!", 2)
  57.             end
  58.         end
  59.     end
  60.        
  61.     return output
  62. end
Advertisement
Add Comment
Please, Sign In to add comment