Advertisement
CloneTrooper1019

parseObj (WIP?)

Dec 9th, 2014
338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.58 KB | None | 0 0
  1. function parseOBJ(objFile)
  2.     -- Parses an OBJ File into a data array.
  3.     local obj = {
  4.         Verts = {};
  5.         Norms = {};
  6.         Texs = {};
  7.         Faces = {};
  8.     }
  9.     local currentMtl = "";
  10.     for line in objFile:gmatch("[^\r\n]+") do
  11.         if #line > 0 then
  12.             local info = {}
  13.             local tag = ""
  14.             local process = ""
  15.             for char in line:gmatch(".") do
  16.                 if char == " " then
  17.                     if tag == "" then
  18.                         tag = process
  19.                     else
  20.                         table.insert(info,tonumber(process) or process)
  21.                     end
  22.                     process = ""
  23.                 else
  24.                     process = process .. char
  25.                 end
  26.             end
  27.             if tag == "g" then
  28.                 currentMtl = info[1]
  29.             elseif tag == "v" then
  30.                 local Vert = {
  31.                     Mtl = currentMtl;
  32.                     Coords = Vector3.new(unpack(info));
  33.                 };
  34.                 table.insert(obj.Verts,Vert)
  35.             elseif tag == "vn" then
  36.                 local Norm = Vector3.new(unpack(info));
  37.                 table.insert(obj.Norms,Norm)
  38.             elseif tag == "vt" then
  39.                 local texCoord = Vector2.new(unpack(info))
  40.                 table.insert(obj.Texs,texCoord)
  41.             elseif tag == "f" then
  42.                 local triangle = {}
  43.                 local v,t,n
  44.                 for _,pair in pairs(info) do
  45.                     local index = {}
  46.                     if type(pair) == "number" then
  47.                         v = pair
  48.                     elseif string.find(pair,"//") then
  49.                         v,n = string.match(pair,"(%S+)//(%S+)")
  50.                     else
  51.                         v,t,n = string.match(pair,"(%S+)/(%S+)/(%S+)")
  52.                         if not v or not t or not n then
  53.                             v,t = string.match(pair,"(%S+)/(%S+)")
  54.                         end
  55.                     end
  56.                 end
  57.                 triangle.Vertex = tonumber(v)
  58.                 triangle.Texture = tonumber(t)
  59.                 triangle.Normal = tonumber(n)              
  60.                 table.insert(obj.Faces,triangle)
  61.             end
  62.         end
  63.     end
  64.     return obj
  65. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement