Files
rosetta/src/Formats/model/obj/init.luau
T

764 lines
26 KiB
Luau

--!strict
-- model/obj: Wavefront OBJ (+ MTL), from Paul Bourke's OBJ / MTL specifications and what Blender / Maya / assimp
-- write. Supports: v (with the common "v x y z r g b" vertex colour extension), vt, vn, f with every index form
-- (v, v/vt, v//vn, v/vt/vn, negative = relative), l, p, o / g (nodes), usemtl / mtllib (materials: Phong + the PBR
-- extension, texture maps with -o / -s / -bm options; texture images stay encoded bytes or file names, see Types), line
-- continuations, comments. n-gons are fan-triangulated by default (opts.triangulate = false keeps them as "polygons",
-- MeshOps.triangulate ear-clips concave ones). TEXCOORD_0 is flipped to glTF's top-left origin (opts.flipV = false
-- keeps OBJ's).
-- Nodes: one per object (o); groups (g) inside an object become child nodes; files without o: one root node per group.
-- Each node has a mesh with one primitive per material. Vertices are unwelded per (v, vt, vn) combination.
-- Not supported: free-form geometry (curv, surf, ...: skipped and counted in meta.source.skipped), smoothing groups
-- (s: kept per node in extras.obj.smoothing, not used to compute normals).
-- encode: every mesh primitive of the scene baked into world space, one o per node; materials into a .mtl (written to
-- opts.files[<name>.mtl] when opts.files is a table, see Types), embedded texture bytes into opts.files too.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Mtl = require("@formats/model/obj/Mtl")
-- ------------------------------------------------------------------------------------------------ contract
local Obj = {
name = "obj",
category = "model",
extensions = { "obj" },
mime = { "model/obj" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, materials = true, polygons = true, vertexColors = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps "polygons" primitives
flipV: boolean?, -- TEXCOORD_0.v = 1 - v (default true: glTF's convention)
mtl: (string | buffer)?, -- the material library text, when not found through resolve / files
resolve: ((uri: string) -> any)?, -- reads mtllib / texture files (the api sets it for paths)
files: { [string]: any }?, -- or: the other files by name
maxVertices: number?, -- refuse more v / vt / vn / corners (default 2^25)
}
export type EncodeOptions = {
name: string?, -- the destination file name: the .mtl is named after it (default "model.mtl")
mtlName: string?, -- the .mtl file name (overrides name)
files: { [string]: any }?, -- receives the .mtl and embedded textures
flipV: boolean?, -- default true (the inverse of decode)
normals: boolean?, -- write vn (default true when the primitives have NORMAL)
texcoords: boolean?, -- write vt (default true when the primitives have TEXCOORD_0)
colors: boolean?, -- write vertex colours after v (default true when COLOR_0 exists)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Obj.sniff(r: Bytes.Reader): number
local head = r:peek(512)
if string.find(head, "\0", 1, true) then
return 0
end
if string.find(head, "^%s*v%s+[%-%d%.]") or string.find(head, "\n%s*v%s+[%-%d%.]") then
return 0.6
end
if string.find(head, "^#") and (string.find(head, "\nmtllib ") or string.find(head, "\no ") or string.find(head, "\ng ")) then
return 0.4
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function fetch(opts: DecodeOptions?, uri: string): string?
if not opts then
return nil
end
local v: any = nil
if type(opts.files) == "table" then
v = opts.files[uri]
if v == nil then
v = opts.files[string.match(uri, "([^/\\]+)$") or uri]
end
end
if v == nil and type(opts.resolve) == "function" then
local ok, res = pcall(opts.resolve, uri)
v = if ok then res else nil
end
if type(v) == "buffer" then
return buffer.tostring(v)
elseif type(v) == "string" then
return v
end
return nil
end
type Prim = {
material: string?,
mode: string,
cv: { number }, -- per corner: position index (0-based), texcoord index (-1 none), normal index (-1 none)
ct: { number },
cn: { number },
faces: { number }, -- corners per face (polygons / lines)
hasT: boolean,
hasN: boolean,
}
type Section = { object: string?, group: string?, prims: { Prim }, byKey: { [string]: Prim }, smoothing: string? }
function Obj.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local triangulate = not (opts and opts.triangulate == false)
local flipV = not (opts and opts.flipV == false)
local maxV = opts and opts.maxVertices or 2 ^ 25
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local P, C, UV, N = {}, {}, {}, {}
local np, nt, nn = 0, 0, 0
local hasColor = false
local sections: { Section } = {}
local byName: { [string]: Section } = {}
local cur: Section? = nil
local object: string? = nil
local group: string? = nil
local material: string? = nil
local smoothing: string? = nil
local mtllibs: { string } = {}
local skipped = 0
local corners = 0
local hasObjects = false
local lineNo = 0
local pos = 1
local len = #text
local function section(): Section
if cur then
return cur
end
local key = (object or "") .. "\0" .. (group or "")
local s = byName[key]
if not s then
s = { object = object, group = group, prims = {}, byKey = {}, smoothing = smoothing }
byName[key] = s
table.insert(sections, s)
end
cur = s
return s
end
local function prim(mode: string): Prim
local s = section()
local key = mode .. "\0" .. (material or "")
local p = s.byKey[key]
if not p then
p = { material = material, mode = mode, cv = {}, ct = {}, cn = {}, faces = {}, hasT = false, hasN = false }
s.byKey[key] = p
table.insert(s.prims, p)
end
return p
end
-- one corner "v/vt/vn" -> indices (0-based, -1 for none) | nil
local function corner(tok: string): (number?, number, number)
local a, b, c = string.match(tok, "^([^/]*)/?([^/]*)/?([^/]*)$")
local vi = tonumber(a)
if not vi then
return nil, -1, -1
end
vi = if vi < 0 then np + vi else vi - 1
local ti, ni = -1, -1
local t = tonumber(b)
if t then
ti = if t < 0 then nt + t else t - 1
if ti < 0 or ti >= nt then
return nil, -1, -1
end
end
local n = tonumber(c)
if n then
ni = if n < 0 then nn + n else n - 1
if ni < 0 or ni >= nn then
return nil, -1, -1
end
end
if vi < 0 or vi >= np then
return nil, -1, -1
end
return vi, ti, ni
end
local fs: { string } = {}
while pos <= len do
local e = string.find(text, "\n", pos, true) or (len + 1)
local line = string.sub(text, pos, e - 1)
pos = e + 1
lineNo += 1
-- continuation lines
while string.sub(line, -1) == "\\" or string.sub(line, -2) == "\\\r" do
line = string.gsub(line, "\\\r?$", " ")
local e2 = string.find(text, "\n", pos, true) or (len + 1)
line ..= string.sub(text, pos, e2 - 1)
pos = e2 + 1
lineNo += 1
end
local key, rest = string.match(line, "^%s*(%S+)%s*(.-)%s*$")
if key == nil or string.sub(key, 1, 1) == "#" then
continue
end
local rest: string = rest :: string -- both captures match together
local hash = string.find(rest, "#", 1, true)
if hash then
rest = string.gsub(string.sub(rest, 1, hash - 1), "%s+$", "")
end
if key == "v" then
local x, y, z, a, b, c = string.match(rest, "^(%S+)%s+(%S+)%s+(%S+)%s*(%S*)%s*(%S*)%s*(%S*)")
local fx, fy, fz = tonumber(x), tonumber(y), tonumber(z)
if not fx or not fy or not fz then
return nil, Err.new(Err.CORRUPT, "bad vertex on line " .. lineNo)
end
if np >= maxV then
return nil, Err.new(Err.LIMIT, "over " .. maxV .. " vertices")
end
P[np * 3 + 1], P[np * 3 + 2], P[np * 3 + 3] = fx, fy, fz
local cr, cg, cb = tonumber(a), tonumber(b), tonumber(c)
if cr and cg and cb then
hasColor = true
C[np * 3 + 1], C[np * 3 + 2], C[np * 3 + 3] = cr, cg, cb
end
np += 1
elseif key == "vt" then
local u, v = string.match(rest, "^(%S+)%s*(%S*)")
local fu = tonumber(u)
if not fu then
return nil, Err.new(Err.CORRUPT, "bad texture coordinate on line " .. lineNo)
end
if nt >= maxV then
return nil, Err.new(Err.LIMIT, "over " .. maxV .. " texture coordinates")
end
local fv = tonumber(v) or 0
UV[nt * 2 + 1], UV[nt * 2 + 2] = fu, if flipV then 1 - fv else fv
nt += 1
elseif key == "vn" then
local x, y, z = string.match(rest, "^(%S+)%s+(%S+)%s+(%S+)")
local fx, fy, fz = tonumber(x), tonumber(y), tonumber(z)
if not fx or not fy or not fz then
return nil, Err.new(Err.CORRUPT, "bad normal on line " .. lineNo)
end
if nn >= maxV then
return nil, Err.new(Err.LIMIT, "over " .. maxV .. " normals")
end
N[nn * 3 + 1], N[nn * 3 + 2], N[nn * 3 + 3] = fx, fy, fz
nn += 1
elseif key == "f" or key == "l" or key == "p" then
table.clear(fs)
for tok in string.gmatch(rest, "%S+") do
table.insert(fs, tok)
end
local k = #fs
local mode = if key == "f" then (if triangulate then "triangles" else "polygons") elseif key == "l" then "lines" else "points"
if (key == "f" and k < 3) or (key == "l" and k < 2) or k < 1 then
return nil, Err.new(Err.CORRUPT, "an element with too few corners on line " .. lineNo)
end
corners += k
if corners > maxV * 4 then
return nil, Err.new(Err.LIMIT, "too many face corners")
end
local p = prim(mode)
local base = #p.cv
for i, tok in fs do
local vi, ti, ni = corner(tok)
if not vi then
return nil, Err.new(Err.CORRUPT, "bad index '" .. tok .. "' on line " .. lineNo)
end
p.cv[base + i], p.ct[base + i], p.cn[base + i] = vi, ti, ni
if ti >= 0 then
p.hasT = true
end
if ni >= 0 then
p.hasN = true
end
end
if mode == "triangles" and k > 3 then
-- fan: rewrite the k corners as (k - 2) triangles
local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {})
local o = base
for a = 2, k - 1 do
for _, j in { 1, a, a + 1 } do
o += 1
p.cv[o], p.ct[o], p.cn[o] = cv[j], ct[j], cn[j]
end
end
elseif mode == "lines" then
-- a polyline -> segments
local cv, ct, cn = table.move(p.cv, base + 1, base + k, 1, {}), table.move(p.ct, base + 1, base + k, 1, {}), table.move(p.cn, base + 1, base + k, 1, {})
local o = base
for a = 1, k - 1 do
for _, j in { a, a + 1 } do
o += 1
p.cv[o], p.ct[o], p.cn[o] = cv[j], ct[j], cn[j]
end
end
elseif mode == "polygons" then
table.insert(p.faces, k)
end
elseif key == "o" then
object = rest
group = nil
hasObjects = true
cur = nil
elseif key == "g" then
group = if rest == "" then nil else rest
cur = nil
elseif key == "usemtl" then
material = rest
elseif key == "mtllib" then
table.insert(mtllibs, rest)
elseif key == "s" then
smoothing = rest
if cur then
cur.smoothing = cur.smoothing or rest
end
else
skipped += 1
end
end
-- materials
local scene = Types.Scene.new()
local matIndex: { [string]: number } = {}
local texIndex: { [string]: number } = {}
local function texture(map: Mtl.Map): number
local file = string.gsub(map.file, "\\", "/")
local i = texIndex[file]
if i then
return i
end
local tex: Types.Texture = { uri = file, mime = Mtl.mime(file) }
local data = fetch(opts, file)
if data then
tex.data = buffer.fromstring(data)
end
if map.options.clamp and map.options.clamp[1] == "on" then
tex.sampler = { wrapS = "clamp", wrapT = "clamp" }
end
table.insert(scene.textures, tex)
i = #scene.textures
texIndex[file] = i
return i
end
local mtlText = if opts and opts.mtl then (if type(opts.mtl) == "buffer" then buffer.tostring(opts.mtl) else opts.mtl) else nil
local missing: { string } = {}
local libs: { string } = {}
if mtlText then
table.insert(libs, mtlText :: string)
end
for _, lib in mtllibs do
local t = fetch(opts, lib)
if t then
table.insert(libs, t)
elseif not mtlText then
table.insert(missing, lib)
end
end
for _, lt in libs do
for _, e in Mtl.parse(lt) do
if not matIndex[e.name] then
table.insert(scene.materials, Mtl.toMaterial(e, texture))
matIndex[e.name] = #scene.materials
end
end
end
-- materials named by usemtl but not defined anywhere: a default one with the name
for _, s in sections do
for _, p in s.prims do
if p.material and not matIndex[p.material] then
table.insert(scene.materials, Types.Scene.material(p.material))
scene.materials[#scene.materials].metallic = 0
matIndex[p.material] = #scene.materials
end
end
end
-- vertices: one per distinct (v, vt, vn) in each primitive
local f32 = buffer.writef32
local KT, KN = nt + 1, nn + 1
local numericKeys = np * KT * KN < 2 ^ 52
local function build(p: Prim): Types.Primitive
local n = #p.cv
local map: { [any]: number } = {}
local verts: { number } = {}
local idx = buffer.create(n * 4)
local count = 0
for i = 1, n do
local v, t, nr = p.cv[i], p.ct[i], p.cn[i]
local key: any = if numericKeys then (v * KT + (t + 1)) * KN + (nr + 1) else string.format("%d/%d/%d", v, t, nr)
local k = map[key]
if k == nil then
k = count
map[key] = k
count += 1
verts[count * 3 - 2], verts[count * 3 - 1], verts[count * 3] = v, t, nr
end
buffer.writeu32(idx, (i - 1) * 4, k)
end
local pb = buffer.create(count * 12)
local tb = if p.hasT then buffer.create(count * 8) else nil
local nb = if p.hasN then buffer.create(count * 12) else nil
local cb = if hasColor then buffer.create(count * 12) else nil
for k = 0, count - 1 do
local v, t, nr = verts[k * 3 + 1], verts[k * 3 + 2], verts[k * 3 + 3]
f32(pb, k * 12, P[v * 3 + 1])
f32(pb, k * 12 + 4, P[v * 3 + 2])
f32(pb, k * 12 + 8, P[v * 3 + 3])
if tb and t >= 0 then
f32(tb, k * 8, UV[t * 2 + 1])
f32(tb, k * 8 + 4, UV[t * 2 + 2])
end
if nb and nr >= 0 then
f32(nb, k * 12, N[nr * 3 + 1])
f32(nb, k * 12 + 4, N[nr * 3 + 2])
f32(nb, k * 12 + 8, N[nr * 3 + 3])
end
if cb then
f32(cb, k * 12, C[v * 3 + 1] or 1)
f32(cb, k * 12 + 4, C[v * 3 + 2] or 1)
f32(cb, k * 12 + 8, C[v * 3 + 3] or 1)
end
end
local A = Types.Scene.accessor
local attrs: { [string]: Types.Accessor } = { POSITION = A(pb, "f32", 3, count) }
if tb then
attrs.TEXCOORD_0 = A(tb, "f32", 2, count)
end
if nb then
attrs.NORMAL = A(nb, "f32", 3, count)
end
if cb then
attrs.COLOR_0 = A(cb, "f32", 3, count)
end
local out: Types.Primitive = { attributes = attrs, indices = A(idx, "u32", 1, n), mode = p.mode :: any, material = if p.material then matIndex[p.material] else nil }
if p.mode == "points" then
out.indices = if count == n then nil else out.indices
end
if p.mode == "polygons" then
local fb = buffer.create(#p.faces * 4)
for i, k in p.faces do
buffer.writeu32(fb, (i - 1) * 4, k)
end
out.faces = A(fb, "u32", 1, #p.faces)
end
return out
end
-- nodes: objects at the root, their groups as children; without objects every group is a root
local objectNode: { [string]: number } = {}
for _, s in sections do
if #s.prims > 0 then
local mesh: Types.Mesh = { name = s.group or s.object, primitives = {} }
for _, p in s.prims do
table.insert(mesh.primitives, build(p))
end
table.insert(scene.meshes, mesh)
local node: Types.Node = { name = s.group or s.object, children = {}, mesh = #scene.meshes }
if s.smoothing then
node.extras = { obj = { smoothing = s.smoothing } }
end
if hasObjects and s.object and s.group then
local oi = objectNode[s.object]
if not oi then
table.insert(scene.nodes, { name = s.object, children = {} })
oi = #scene.nodes
objectNode[s.object] = oi
table.insert(scene.roots, oi)
end
table.insert(scene.nodes, node)
table.insert(scene.nodes[oi].children, #scene.nodes)
else
if hasObjects and s.object and not s.group and objectNode[s.object] == nil then
table.insert(scene.nodes, node)
objectNode[s.object] = #scene.nodes
table.insert(scene.roots, #scene.nodes)
elseif hasObjects and s.object and objectNode[s.object] then
-- the object's own faces after its groups: a child too
table.insert(scene.nodes, node)
table.insert(scene.nodes[objectNode[s.object]].children, #scene.nodes)
else
table.insert(scene.nodes, node)
table.insert(scene.roots, #scene.nodes)
end
end
end
end
scene.meta.up = "y"
scene.meta.source = {
format = "obj",
positions = np,
texcoords = nt,
normals = nn,
vertexColors = hasColor,
mtllib = if #mtllibs > 0 then mtllibs else nil,
missingMtl = if #missing > 0 then missing else nil,
skipped = skipped,
}
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- the shortest decimal that reads back as the same f32
local probe = buffer.create(4)
local function f32str(v: number): string
if v ~= v or v == math.huge or v == -math.huge then
return "0"
end
if v == math.floor(v) and math.abs(v) < 1e7 then
return string.format("%d", v)
end
buffer.writef32(probe, 0, v)
local want = buffer.readf32(probe, 0)
for _, f in { "%.6g", "%.7g", "%.8g" } do
local s = string.format(f, v)
buffer.writef32(probe, 0, tonumber(s) :: number)
if buffer.readf32(probe, 0) == want then
return s
end
end
return string.format("%.9g", v)
end
local function nameOk(s: string): string
local t = string.gsub(s, "[\r\n]", " ")
return t
end
local EXT: { [string]: string } = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/ktx2"] = "ktx2" }
function Obj.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.nodes) ~= "table" or type(scene.meshes) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Scene")
end
local flipV = not (opts and opts.flipV == false)
local base: string = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model"
local mtlName = opts and opts.mtlName or (base .. ".mtl")
local files = opts and opts.files
local placed = Types.Scene.flatten(scene)
local out = { "# written by formats-luau" }
local mats = scene.materials or {}
-- material names (unique), texture file names
local names: { string } = {}
local used: { [string]: boolean } = {}
for i, m in mats do
local n = string.gsub(m.name or ("material_" .. i), "%s", "_")
while used[n] do
n ..= "_" .. i
end
used[n] = true
names[i] = n
end
local texFiles: { [number]: string } = {}
local function textureFile(i: number): string?
if texFiles[i] then
return texFiles[i]
end
local tex = scene.textures and scene.textures[i]
if not tex then
return nil
end
local file = tex.uri
if (file == nil or string.find(file, "^data:")) and tex.data then
file = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png")
end
if file and tex.data and type(files) == "table" then
files[file] = tex.data
end
texFiles[i] = file
return file
end
if #mats > 0 then
table.insert(out, "mtllib " .. mtlName)
if type(files) == "table" then
files[mtlName] = Mtl.write(mats, names, textureFile)
end
end
local nv, nt, nn = 0, 0, 0
local lastNode = -1
for _, pl in placed do
local prim = pl.primitive
local attrs = prim.attributes
local pos = attrs and attrs.POSITION
if not pos then
continue
end
local P = Types.Scene.reader(pos)
if not P then
return nil, Err.new(Err.ARG, "bad POSITION accessor")
end
if buffer.len(pos.data) < pos.count * pos.components * (Types.COMPONENT_SIZE[pos.type] or 4) then
return nil, Err.new(Err.ARG, "POSITION data is smaller than its count")
end
local m = pl.matrix
local ident = m == Types.Scene.IDENTITY
local node = scene.nodes[pl.node]
if pl.node ~= lastNode then
lastNode = pl.node
table.insert(out, "o " .. nameOk(node.name or ("node_" .. pl.node)))
end
local n = pos.count
local Cc = if attrs.COLOR_0 and not (opts and opts.colors == false) then Types.Scene.reader(attrs.COLOR_0 :: Types.Accessor) else nil
local T = if attrs.TEXCOORD_0 and not (opts and opts.texcoords == false) then Types.Scene.reader(attrs.TEXCOORD_0 :: Types.Accessor) else nil
local Nr = if attrs.NORMAL and not (opts and opts.normals == false) then Types.Scene.reader(attrs.NORMAL :: Types.Accessor) else nil
for _, a in { attrs.COLOR_0, attrs.TEXCOORD_0, attrs.NORMAL } do
if a and (a.count < n or buffer.len(a.data) < a.count * a.components * (Types.COMPONENT_SIZE[a.type] or 4)) then
return nil, Err.new(Err.ARG, "an attribute is shorter than POSITION")
end
end
-- the normal matrix (inverse transpose) for baked normals
local nm: { number }? = nil
if Nr and not ident then
local a, b, c, d, e, f, g, h, i = m[1], m[5], m[9], m[2], m[6], m[10], m[3], m[7], m[11]
local det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)
local k = if det ~= 0 then 1 / det else 1
nm = { (e * i - f * h) * k, -(d * i - f * g) * k, (d * h - e * g) * k, -(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, (b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k }
end
for v = 0, n - 1 do
local x, y, z = P(v, 0), P(v, 1), P(v, 2)
if not ident then
x, y, z = m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15]
end
if Cc then
table.insert(out, string.format("v %s %s %s %s %s %s", f32str(x), f32str(y), f32str(z), f32str(Cc(v, 0)), f32str(Cc(v, 1)), f32str(Cc(v, 2))))
else
table.insert(out, string.format("v %s %s %s", f32str(x), f32str(y), f32str(z)))
end
end
if T then
for v = 0, n - 1 do
local tv = T(v, 1)
table.insert(out, string.format("vt %s %s", Mtl.num(T(v, 0)), Mtl.num(if flipV then 1 - tv else tv)))
end
end
if Nr then
for v = 0, n - 1 do
local x, y, z = Nr(v, 0), Nr(v, 1), Nr(v, 2)
if nm then
x, y, z = nm[1] * x + nm[4] * y + nm[7] * z, nm[2] * x + nm[5] * y + nm[8] * z, nm[3] * x + nm[6] * y + nm[9] * z
local l = math.sqrt(x * x + y * y + z * z)
if l > 0 then
x, y, z = x / l, y / l, z / l
end
end
table.insert(out, string.format("vn %s %s %s", f32str(x), f32str(y), f32str(z)))
end
end
if prim.material and names[prim.material] then
table.insert(out, "usemtl " .. names[prim.material])
end
local function ref(i: number): string
local s = tostring(nv + i + 1)
if T and Nr then
return string.format("%s/%d/%d", s, nt + i + 1, nn + i + 1)
elseif T then
return string.format("%s/%d", s, nt + i + 1)
elseif Nr then
return string.format("%s//%d", s, nn + i + 1)
end
return s
end
-- the corner list
local ind = prim.indices
local I: ((number, number) -> number)? = if ind then Types.Scene.reader(ind) else nil
local count = if ind then ind.count else n
if ind and buffer.len(ind.data) < ind.count * (Types.COMPONENT_SIZE[ind.type] or 4) then
return nil, Err.new(Err.ARG, "indices data is smaller than its count")
end
local function at(i: number): number
return if I then I(i, 0) else i
end
for i = 0, count - 1 do
if at(i) >= n then
return nil, Err.new(Err.ARG, "index out of range")
end
end
local mirror = not ident and (m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3])) < 0
local function face(list: { number })
local parts = table.create(#list + 1)
parts[1] = "f"
if mirror then
for k = #list, 1, -1 do
table.insert(parts, ref(list[k]))
end
else
for k = 1, #list do
table.insert(parts, ref(list[k]))
end
end
table.insert(out, table.concat(parts, " "))
end
local mode = prim.mode or "triangles"
if mode == "triangles" then
for t = 0, count // 3 - 1 do
face({ at(t * 3), at(t * 3 + 1), at(t * 3 + 2) })
end
elseif mode == "polygons" then
local F = if prim.faces then Types.Scene.reader(prim.faces) else nil
if not F or not prim.faces then
return nil, Err.new(Err.ARG, "polygons without faces")
end
local o = 0
for f = 0, prim.faces.count - 1 do
local k = F(f, 0)
if o + k > count then
return nil, Err.new(Err.ARG, "faces run past the indices")
end
local list = table.create(k) :: { number }
for j = 0, k - 1 do
list[j + 1] = at(o + j)
end
if k >= 3 then
face(list)
end
o += k
end
elseif mode == "triangle_strip" or mode == "triangle_fan" then
for t = 0, count - 3 do
local a, b, c = at(t), at(t + 1), at(t + 2)
if mode == "triangle_fan" then
a = at(0)
elseif t % 2 == 1 then
a, b = b, a
end
face({ a, b, c })
end
elseif mode == "lines" then
for s = 0, count // 2 - 1 do
table.insert(out, "l " .. ref(at(s * 2)) .. " " .. ref(at(s * 2 + 1)))
end
elseif mode == "line_strip" or mode == "line_loop" then
local parts = { "l" }
for i = 0, count - 1 do
table.insert(parts, ref(at(i)))
end
if mode == "line_loop" and count > 0 then
table.insert(parts, ref(at(0)))
end
table.insert(out, table.concat(parts, " "))
elseif mode == "points" then
for i = 0, count - 1 do
table.insert(out, "p " .. ref(at(i)))
end
end
nv += n
if T then
nt += n
end
if Nr then
nn += n
end
end
table.insert(out, "")
return buffer.fromstring(table.concat(out, "\n")), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- encodeMtl(scene, opts?) -> the .mtl text for the scene's materials (what encode puts in opts.files)
function Obj.encodeMtl(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(scene) ~= "table" or type(scene.materials) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Scene")
end
local files: { [string]: string } = {}
local o: any = table.clone(opts or {})
o.files = files
o.mtlName = "x.mtl"
local _, err = Obj.encode(scene, o)
if err then
return nil, err
end
local text = files["x.mtl"]
return buffer.fromstring(text or ""), nil
end
return Obj