ws-3d: model/obj (OBJ + MTL read/write: objects/groups -> nodes, per-material primitives, n-gons fan-triangulated or kept as polygons, vertex colours, lines/points, PBR MTL extension, texture maps with options, files through opts.files/resolve); tests vs assimp + trimesh, and assimp/trimesh reading our output

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 08:46:04 -05:00
1 parent 58f6b32541
commit c3bbae0271
6 files changed
+1641

No files matched your search

+294
View File
@@ -0,0 +1,294 @@
--!strict
-- model/obj/Mtl: Wavefront .mtl material libraries (Paul Bourke's MTL spec + the common PBR extension: Pr, Pm, Ps, Pc,
-- Pcr, aniso, anisor, Ke, map_Pr, map_Pm, map_Ke, norm). parse(text) -> { name -> { statement -> values } } keeping
-- every statement; toMaterial maps one onto the Scene Material (glTF PBR, Phong values in extras.obj); write is the
-- reverse (from extras.obj when present, else from the PBR fields).
local Types = require("@formats/Types")
local Mtl = {}
export type Map = { file: string, options: { [string]: { string } } } -- -o / -s / -bm / -clamp / ... with their values
export type Entry = { name: string, values: { [string]: { number } }, maps: { [string]: Map }, order: { string } }
-- the number of arguments of each texture map option (Bourke): -o / -s / -t take 1..3 numbers
local OPT_ARGS = { blendu = 1, blendv = 1, cc = 1, clamp = 1, mm = 2, bm = 1, boost = 1, texres = 1, imfchan = 1, type = 1 }
local MAPS = {
map_Ka = true, map_Kd = true, map_Ks = true, map_Ke = true, map_Ns = true, map_d = true, map_Tr = true,
map_bump = true, bump = true, map_Bump = true, disp = true, decal = true, refl = true, norm = true, map_Pr = true,
map_Pm = true, map_Ps = true, map_Pc = true, map_Pcr = true, map_RMA = true, map_ORM = true, map_aniso = true,
}
Mtl.MAPS = MAPS
local function parseMap(args: { string }): Map
local opts: { [string]: { string } } = {}
local i = 1
while i <= #args and string.sub(args[i], 1, 1) == "-" and tonumber(args[i]) == nil do
local key = string.sub(args[i], 2)
local vals = {}
i += 1
local n = OPT_ARGS[key]
if n then
for _ = 1, n do
if i <= #args then
table.insert(vals, args[i])
i += 1
end
end
else
-- -o / -s / -t: up to three numbers
while i <= #args and #vals < 3 and tonumber(args[i]) ~= nil and i < #args do
table.insert(vals, args[i])
i += 1
end
end
opts[key] = vals
end
-- the file name is the rest (it may contain spaces)
local file = table.concat(args, " ", i)
return { file = file, options = opts }
end
-- parse(text) -> { Entry } in file order
function Mtl.parse(text: string): { Entry }
local out: { Entry } = {}
local cur: Entry? = nil
for line in string.gmatch(text, "[^\r\n]+") do
local l = string.gsub(line, "#.*$", "")
local words = {}
for w in string.gmatch(l, "%S+") do
table.insert(words, w)
end
local key = words[1]
if key == "newmtl" then
cur = { name = table.concat(words, " ", 2), values = {}, maps = {}, order = {} }
table.insert(out, cur :: Entry)
elseif key and cur then
local e = cur :: Entry
local args = table.move(words, 2, #words, 1, {})
if MAPS[key] then
e.maps[key] = parseMap(args)
table.insert(e.order, key)
else
local nums = {}
for _, a in args do
local v = tonumber(a)
if v == nil then
nums = nil :: any
break
end
table.insert(nums, v)
end
if nums then
if e.values[key] == nil then
table.insert(e.order, key)
end
e.values[key] = nums
end
end
end
end
return out
end
local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", webp = "image/webp", gif = "image/gif", bmp = "image/bmp", tga = "image/x-tga", tif = "image/tiff", tiff = "image/tiff", dds = "image/vnd-ms.dds", ktx2 = "image/ktx2", exr = "image/x-exr", hdr = "image/vnd.radiance" }
function Mtl.mime(file: string): string?
local ext = string.match(file, "%.([%w]+)$")
return if ext then MIME[string.lower(ext)] else nil
end
-- toMaterial(entry, texture) -> Material: texture(map) returns the scene texture index for a map
function Mtl.toMaterial(e: Entry, texture: (Map) -> number): Types.Material
local m = Types.Scene.material(e.name)
local v = e.values
local kd = v.Kd
if kd and #kd >= 3 then
m.baseColor = { kd[1], kd[2], kd[3], 1 }
end
local d = if v.d then v.d[1] elseif v.Tr then 1 - v.Tr[1] else 1
m.baseColor[4] = d
if d < 1 then
m.alphaMode = "blend"
end
local ke = v.Ke
if ke and #ke >= 3 then
m.emissive = { ke[1], ke[2], ke[3] }
end
m.metallic = if v.Pm then v.Pm[1] else 0
if v.Pr then
m.roughness = v.Pr[1]
elseif v.Ns then
m.roughness = math.clamp(math.sqrt(2 / (math.max(v.Ns[1], 0) + 2)), 0, 1)
end
local function ref(key: string): Types.TextureRef?
local map = e.maps[key]
if not map or map.file == "" then
return nil
end
local r: Types.TextureRef = { texture = texture(map) }
local o, s = map.options.o, map.options.s
if o or s then
r.transform = {
offset = if o then { tonumber(o[1]) or 0, tonumber(o[2]) or 0 } else nil,
scale = if s then { tonumber(s[1]) or 1, tonumber(s[2]) or 1 } else nil,
}
end
if map.options.bm then
r.scale = tonumber(map.options.bm[1])
end
return r
end
m.baseColorTexture = ref("map_Kd")
m.emissiveTexture = ref("map_Ke")
m.normalTexture = ref("norm") or ref("map_bump") or ref("bump") or ref("map_Bump")
m.metallicRoughnessTexture = ref("map_ORM") or ref("map_RMA")
if m.emissiveTexture and not ke then
m.emissive = { 1, 1, 1 }
end
-- everything else as it was, for the writer and for Phong renderers
local extra: { [string]: any } = {}
for k, vals in v do
extra[k] = vals
end
local maps: { [string]: any } = {}
for k, map in e.maps do
maps[k] = { file = map.file, options = map.options, texture = texture(map) }
end
m.extras = { obj = { values = extra, maps = maps, order = e.order } }
return m
end
local function num(v: number): string
if v == math.floor(v) and math.abs(v) < 1e15 then
return string.format("%d", v)
end
for _, f in { "%.6g", "%.9g", "%.17g" } do
local s = string.format(f, v)
if tonumber(s) == v then
return s
end
end
return string.format("%.17g", v)
end
Mtl.num = num
-- write(materials, name, textureFile) -> MTL text. textureFile(index) -> the file name a map refers to.
function Mtl.write(materials: { Types.Material }, names: { string }, textureFile: (number) -> string?): string
local out = { "# written by formats-luau" }
for i, m in materials do
table.insert(out, "")
table.insert(out, "newmtl " .. names[i])
local saved = m.extras and m.extras.obj
local values: { [string]: { number } } = {}
local maps: { [string]: any } = {}
local order: { string } = {}
if type(saved) == "table" and type(saved.values) == "table" then
for k, vals in saved.values do
values[k] = vals
end
for k, mp in saved.maps or {} do
maps[k] = mp
end
order = table.clone(saved.order or {})
end
-- the PBR fields win over the saved Phong values they map to
local bc = m.baseColor or { 1, 1, 1, 1 }
values.Kd = { bc[1], bc[2], bc[3] }
if (bc[4] or 1) < 1 or values.d then
values.d = { bc[4] or 1 }
values.Tr = nil
end
local em = m.emissive or { 0, 0, 0 }
if em[1] ~= 0 or em[2] ~= 0 or em[3] ~= 0 or values.Ke then
values.Ke = { em[1], em[2], em[3] }
end
if not (saved and saved.values and saved.values.Ns and not saved.values.Pr) then
values.Pr = { m.roughness }
end
if m.metallic ~= 0 or values.Pm then
values.Pm = { m.metallic }
end
local function setMap(key: string, ref: Types.TextureRef?)
if ref then
local file = textureFile(ref.texture)
if file then
local prev = maps[key]
local options = if prev and prev.texture == ref.texture then prev.options else {}
options = table.clone(options or {})
if ref.transform then
if ref.transform.offset then
options.o = { num(ref.transform.offset[1]), num(ref.transform.offset[2]) }
end
if ref.transform.scale then
options.s = { num(ref.transform.scale[1]), num(ref.transform.scale[2]) }
end
end
if ref.scale and key ~= "map_Kd" then
options.bm = { num(ref.scale) }
end
maps[key] = { file = file, options = options, texture = ref.texture }
end
end
end
setMap("map_Kd", m.baseColorTexture)
setMap("map_Ke", m.emissiveTexture)
if m.normalTexture and not maps.map_bump and not maps.bump and not maps.map_Bump then
setMap("norm", m.normalTexture)
end
setMap("map_ORM", m.metallicRoughnessTexture)
-- the saved order first, then the rest sorted
local keys = {}
local seen = {}
for _, k in order do
if (values[k] or maps[k]) and not seen[k] then
table.insert(keys, k)
seen[k] = true
end
end
local rest = {}
for k in values do
if not seen[k] then
table.insert(rest, k)
end
end
for k in maps do
if not seen[k] and not values[k] then
table.insert(rest, k)
end
end
table.sort(rest)
for _, k in rest do
seen[k] = true
table.insert(keys, k)
end
for _, k in keys do
local mp = maps[k]
if mp and type(mp.file) == "string" then
local file = if type(mp.texture) == "number" then (textureFile(mp.texture) or mp.file) else mp.file
local parts = { k }
local okeys = {}
for ok in mp.options or {} do
table.insert(okeys, ok)
end
table.sort(okeys)
for _, ok in okeys do
table.insert(parts, "-" .. ok)
for _, ov in mp.options[ok] do
table.insert(parts, tostring(ov))
end
end
table.insert(parts, file)
table.insert(out, table.concat(parts, " "))
elseif values[k] then
local parts = { k }
for _, x in values[k] do
table.insert(parts, num(x))
end
table.insert(out, table.concat(parts, " "))
end
end
end
table.insert(out, "")
return table.concat(out, "\n")
end
return Mtl
+762
View File
@@ -0,0 +1,762 @@
--!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 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 = { ["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 = 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) else nil
local T = if attrs.TEXCOORD_0 and not (opts and opts.texcoords == false) then Types.Scene.reader(attrs.TEXCOORD_0) else nil
local Nr = if attrs.NORMAL and not (opts and opts.normals == false) then Types.Scene.reader(attrs.NORMAL) 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)
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 = {}
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
+235
View File
@@ -0,0 +1,235 @@
-- model/obj tests: OBJ / MTL files (materials and texture maps, objects and groups, n-gons, negative indices, vertex
-- colours, continuations, lines and points, a concave polygon, assimp's exporter output) against assimp (meshes,
-- vertices, faces, bounds, materials) and trimesh (area, triangles); MTL mapping; ear clipping (MeshOps) against the
-- exact polygon area; round trips through the writer, and assimp / trimesh reading our output (obj_xcheck); errors;
-- the fuzz no-throw pass. Fixtures: tools/fixtures/obj.py.
local T = require("@tests/T")
local Obj = require("@formats/model/obj")
local MeshOps = require("@formats/ops/MeshOps")
local Bytes = require("@formats/core/Bytes")
local Err = require("@formats/core/Err")
local Cases = require("@tests/gen/obj_cases")
local Xcheck = require("@tests/gen/obj_xcheck")
local t = T.suite("obj")
local function decode(data: any, opts: any?): (any, any)
local b = if type(data) == "string" then buffer.fromstring(data) else data
return Obj.decode(Bytes.reader(b), opts)
end
t:eq(Obj.name, "obj", "name")
t:eq(Obj.category, "model", "category")
t:check(Obj.caps.decode and Obj.caps.encode, "caps")
local function near(a: number, b: number, eps: number): boolean
return math.abs(a - b) <= eps * math.max(1, math.abs(a), math.abs(b))
end
local function triArea(prim: any): number
local pos = prim.attributes.POSITION
local ind = prim.indices
local area = 0
local function P(i: number, k: number): number
return buffer.readf32(pos.data, (i * 3 + k) * 4)
end
for tri = 0, ind.count // 3 - 1 do
local a, b, c = buffer.readu32(ind.data, tri * 12), buffer.readu32(ind.data, tri * 12 + 4), buffer.readu32(ind.data, tri * 12 + 8)
local e1 = { P(b, 0) - P(a, 0), P(b, 1) - P(a, 1), P(b, 2) - P(a, 2) }
local e2 = { P(c, 0) - P(a, 0), P(c, 1) - P(a, 1), P(c, 2) - P(a, 2) }
local x, y, z = e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1]
area += math.sqrt(x * x + y * y + z * z) / 2
end
return area
end
-- the counts assimp reports: meshes (= our primitives), vertices, faces (triangles + line segments + points)
local function counts(scene: any): (number, number, number)
local prims, verts, faces = 0, 0, 0
for _, m in scene.meshes do
for _, p in m.primitives do
prims += 1
verts += p.attributes.POSITION.count
local n = if p.indices then p.indices.count else p.attributes.POSITION.count
faces += if p.mode == "triangles" then n // 3 elseif p.mode == "lines" then n // 2 else n
end
end
return prims, verts, faces
end
local function checkAgainst(scene: any, assimp: any, trimesh: any?, label: string, vertices: boolean, fanArea: number)
local prims, verts, faces = counts(scene)
t:eq(prims, assimp.meshes, label .. ": meshes (assimp)")
if vertices then
t:eq(verts, assimp.vertices, label .. ": vertices (assimp)")
end
t:eq(faces, assimp.faces, label .. ": faces (assimp)")
local lo, hi = MeshOps.bounds(scene)
t:check(lo and hi, label .. ": bounds")
for k = 1, 3 do
t:check(near(lo[k], assimp.min[k], 1e-5) and near(hi[k], assimp.max[k], 1e-5), label .. ": bounds = assimp's")
end
local all = MeshOps.merge(scene)
t:check(near(triArea(all), fanArea, 1e-5), string.format("%s: area %g, exact fan area %g", label, triArea(all), fanArea))
if trimesh then
local merged = MeshOps.merge(scene)
t:eq(merged.indices.count // 3, trimesh.faces, label .. ": triangles (trimesh)")
t:check(near(triArea(merged), trimesh.area, 1e-5), string.format("%s: area %g, trimesh %g", label, triArea(merged), trimesh.area))
end
end
local byName = {}
for _, c in Cases do
byName[c.name] = c
local scene, err = decode(c.data, { files = c.files })
t:check(scene, c.name .. ": decode: " .. tostring(err))
checkAgainst(scene, c.assimp, c.trimesh, c.name, not c.noVertexCount, c.fanArea)
if #scene.materials > 0 then
t:eq(#scene.materials, c.assimp.materials, c.name .. ": materials (assimp)")
end
-- round trip through our writer
local files = {}
local out, eerr = Obj.encode(scene, { name = "rt.obj", files = files })
t:check(out, c.name .. ": encode: " .. tostring(eerr))
local back, berr = decode(out, { files = files })
t:check(back, c.name .. ": decode our OBJ: " .. tostring(berr))
local p1, v1, f1 = counts(scene)
local p2, v2, f2 = counts(back)
t:check(p1 == p2 and v1 == v2 and f1 == f2, c.name .. ": round trip counts")
local m1, m2 = MeshOps.merge(scene), MeshOps.merge(back)
for _, attr in { "POSITION", "TEXCOORD_0", "NORMAL", "COLOR_0" } do
local a, b = m1.attributes[attr], m2.attributes[attr]
t:check((a == nil) == (b == nil), c.name .. ": round trip has " .. attr)
if a and b then
t:check(buffer.tostring(a.data) == buffer.tostring(b.data), c.name .. ": round trip " .. attr .. " exact")
end
end
if m1.indices then
t:check(buffer.tostring(m1.indices.data) == buffer.tostring(m2.indices.data), c.name .. ": round trip indices")
end
t:eq(#back.materials, #scene.materials, c.name .. ": round trip materials")
end
-- the reference tools read our output like the original
for _, x in Xcheck do
local orig = byName[string.sub(x.name, 4)]
t:check(orig ~= nil, x.name .. ": a case")
t:eq(x.assimp.faces, orig.assimp.faces, x.name .. ": assimp faces of our file")
if not orig.noVertexCount then
t:eq(x.assimp.vertices, orig.assimp.vertices, x.name .. ": assimp vertices of our file")
end
t:eq(x.assimp.materials, orig.assimp.materials, x.name .. ": assimp materials of our file")
for k = 1, 3 do
t:check(near(x.assimp.min[k], orig.assimp.min[k], 1e-5) and near(x.assimp.max[k], orig.assimp.max[k], 1e-5), x.name .. ": assimp bounds of our file")
end
if orig.trimesh then
t:check(near(x.trimesh.area, orig.trimesh.area, 1e-5) and x.trimesh.faces == orig.trimesh.faces, x.name .. ": trimesh area of our file")
end
end
t:note("%d files match assimp / trimesh; %d of our files read back by assimp / trimesh", #Cases, #Xcheck)
-- the cube in detail: nodes, materials, textures
do
local c = byName["cube.obj"]
local s = decode(c.data, { files = c.files })
t:eq(#s.roots, 1, "one object")
local root = s.nodes[s.roots[1]]
t:check(root.name == "Cube" and #root.children == 2 and root.mesh == nil, "the object holds two groups")
t:check(s.nodes[root.children[1]].name == "top" and s.nodes[root.children[2]].name == "bottom", "group names")
local red, blue = s.materials[1], s.materials[2]
t:check(red.name == "red" and red.baseColor[1] == 1 and red.baseColor[2] == 0 and red.metallic == 0, "red: Kd, not metallic")
t:check(near(red.roughness, math.sqrt(2 / 52), 1e-9), "red: roughness from Ns")
local tex = s.textures[red.baseColorTexture.texture]
t:check(tex.uri == "textures/tex.png" and tex.mime == "image/png" and tex.data and buffer.len(tex.data) > 30, "map_Kd: uri, mime, bytes through opts.files")
t:check(red.baseColorTexture.transform.scale[1] == 2 and red.baseColorTexture.transform.offset[1] == 0.5, "map_Kd -s / -o")
t:check(red.normalTexture and red.normalTexture.scale == 0.5, "map_Bump -bm")
t:check(red.extras.obj.values.Ns[1] == 50 and red.extras.obj.values.illum[1] == 2, "Phong values in extras")
t:check(blue.baseColor[4] == 0.5 and blue.alphaMode == "blend" and blue.roughness == 0.25 and blue.metallic == 1 and blue.emissive[3] == 0.3, "blue: d, Pr, Pm, Ke")
t:check(s.nodes[root.children[1]].extras.obj.smoothing == "1", "smoothing group kept")
-- the uv flip
local top = s.meshes[s.nodes[root.children[1]].mesh].primitives[1]
t:check(top.attributes.TEXCOORD_0 ~= nil and buffer.readf32(top.attributes.TEXCOORD_0.data, 4) == 1, "vt 0 0 -> (0, 1) (top-left origin)")
local s2 = decode(c.data, { files = c.files, flipV = false })
local top2 = s2.meshes[s2.nodes[s2.nodes[s2.roots[1]].children[1]].mesh].primitives[1]
t:check(buffer.readf32(top2.attributes.TEXCOORD_0.data, 4) == 0, "flipV = false")
-- without the MTL: named default materials, the library listed as missing
local s3 = decode(c.data)
t:check(#s3.materials == 2 and s3.meta.source.missingMtl[1] == "cube.mtl", "missing mtllib")
-- through opts.mtl / resolve
local s4 = decode(c.data, { mtl = c.files["cube.mtl"] })
t:check(s4.materials[1].baseColor[1] == 1 and s4.textures[1].data == nil, "opts.mtl (texture bytes not found)")
local asked = {}
local s5 = decode(c.data, { resolve = function(uri: string): any
table.insert(asked, uri)
return c.files[uri]
end })
t:check(s5.materials[2].baseColor[4] == 0.5 and table.find(asked, "cube.mtl") and table.find(asked, "textures/tex.png"), "opts.resolve")
-- the MTL written back keeps the maps and their options
local files = {}
Obj.encode(s, { name = "x.obj", files = files })
local mtl = files["x.mtl"]
t:check(type(mtl) == "string" and string.find(mtl, "map_Kd -o 0.5 0 -s 2 2 textures/tex.png", 1, true) ~= nil, "MTL map_Kd written: " .. tostring(mtl))
t:check(string.find(mtl, "newmtl blue", 1, true) and string.find(mtl, "\nd 0.5", 1, true), "MTL blue written")
t:check(files["textures/tex.png"] ~= nil, "texture bytes written to opts.files")
end
-- polygons: triangulate = false keeps them; ear clipping gets the concave area right, the fan does not
do
local c = byName["concave.obj"]
local s = decode(c.data, { triangulate = false })
local p = s.meshes[1].primitives[1]
t:check(p.mode == "polygons" and p.faces.count == 2 and p.indices.count == 14, "polygons kept")
local tri = MeshOps.triangulate(p) :: any
t:check(near(triArea(tri), c.polygonArea, 1e-9), "ear clipping area " .. triArea(tri) .. " = " .. c.polygonArea)
local fan = MeshOps.triangulate(p, { method = "fan" }) :: any
t:check(near(triArea(fan), c.trimesh.area, 1e-9), "fan area = trimesh's (fan) area")
-- n-gons written as n-gons
local out = Obj.encode(s) :: buffer
t:check(string.find(buffer.tostring(out), "\nf 7 8 9 10 11 12 13 14", 1, true) ~= nil, "an octagon written as one face")
local back = decode(out, { triangulate = false })
t:eq(back.meshes[1].primitives[1].faces.count, 2, "polygons round trip")
end
-- lines and points
do
local s = decode(byName["wire.obj"].data)
local modes = {}
for _, p in s.meshes[1].primitives do
modes[p.mode] = p
end
t:check(modes.lines and modes.lines.indices.count == 8 and modes.points and modes.triangles, "l (polyline -> 4 segments), p, f")
end
-- errors
do
local _, e = decode("v 0 0 0\nf 1 2 3\n")
t:check(e and e.code == Err.CORRUPT, "index out of range: " .. tostring(e))
local _, e2 = decode("v 0 0\n")
t:check(e2 and e2.code == Err.CORRUPT, "short vertex: " .. tostring(e2))
local _, e3 = decode(byName["random.obj"].data, { maxVertices = 10 })
t:check(e3 and e3.code == Err.LIMIT, "maxVertices: " .. tostring(e3))
local _, e4 = Obj.encode({} :: any)
t:check(e4 and e4.code == Err.ARG, "encode junk")
t:check(Obj.sniff(Bytes.reader(buffer.fromstring(byName["cube.obj"].data))) > 0, "sniff an OBJ")
t:eq(Obj.sniff(Bytes.reader(buffer.fromstring("\137PNG\r\n\26\n"))), 0, "sniff a PNG")
local empty = decode("# nothing\n")
t:check(empty and #empty.nodes == 0, "an empty file is an empty scene")
end
-- fuzz
do
local samples = {}
for _, c in Cases do
table.insert(samples, c.data)
end
t:fuzz("decode", function(b: buffer)
local s = Obj.decode(Bytes.reader(b), { triangulate = false })
if s then
Obj.encode(s)
MeshOps.merge(s)
end
return s
end, samples, { mutations = 40 })
end
t:done()
+61
View File
@@ -0,0 +1,61 @@
# Shared helpers for the model fixture generators (obj.py, gltf.py): reference tools through nix.
# assimp_info(ctx, paths) -> [ { meshes, materials, vertices, faces, nodes, min, max, perMesh = [ { vertices, faces } ] } ]
# trimesh_metrics(ctx, paths) -> [ { area, faces, bounds, volume? } ] (trimesh, process=False, every geometry merged)
# luau_encode(ctx, script) -> { name: bytes }: runs a Luau script (repo-relative, .luaurc aliases) that prints
# "<name>\t<hex>" lines: how a generator gets our encoder's output for the reference tools to read back.
import json, os, re, subprocess, tempfile, shutil
FLOAT = r"(-?[\d.]+(?:e[-+]?\d+)?|-?nan|-?inf)"
def assimp_info(ctx, paths):
out = []
for p in paths:
txt = ctx.nix("assimp", ["assimp", "info", p]).decode("utf-8", "replace")
def num(label):
m = re.search(r"^" + label + r":\s+(\d+)", txt, re.M)
return int(m.group(1)) if m else -1
def point(label):
m = re.search(label + r"\s+\(" + FLOAT + " " + FLOAT + " " + FLOAT + r"\)", txt)
return [float(m.group(i)) for i in (1, 2, 3)] if m else []
per = [{"vertices": int(a), "faces": int(c)} for a, b, c in re.findall(r"^\s+\d+ \(.*?\): \[(\d+) / (\d+) / (\d+) \|", txt, re.M)]
out.append({
"meshes": num("Meshes"), "materials": num("Materials"), "vertices": num("Vertices"), "faces": num("Faces"),
"nodes": num("Nodes"), "min": point("Minimum point"), "max": point("Maximum point"), "perMesh": per,
})
return out
TRIMESH = r"""
import json, sys, trimesh, numpy as np
res = []
for p in json.loads(sys.stdin.read()):
m = trimesh.load(p, force="mesh", process=False)
d = {"area": float(m.area), "faces": int(len(m.faces)), "bounds": [float(v) for v in np.asarray(m.bounds).ravel()] if len(m.faces) else []}
res.append(d)
print(json.dumps(res))
"""
def trimesh_metrics(ctx, paths):
out = ctx.python(["trimesh", "numpy", "networkx", "lxml", "pillow"], TRIMESH, input=json.dumps(paths).encode())
return json.loads(out)
def luau_encode(ctx, script):
exe = shutil.which("luau")
cmd = [exe, script] if exe else ["nix", "shell", "nixpkgs#luau", "-c", "luau", script]
res = subprocess.run(cmd, cwd=ctx.root, capture_output=True, check=True)
files = {}
for line in res.stdout.decode().split("\n"):
if "\t" in line:
name, hexdata = line.split("\t", 1)
files[name] = bytes.fromhex(hexdata.strip())
return files
def tempdir():
return tempfile.mkdtemp(prefix="formats-model-")
+32
View File
@@ -0,0 +1,32 @@
-- tools/fixtures/_obj_encode: run by tools/fixtures/obj.py (luau CLI, repo root): decodes every OBJ case with our
-- reader, encodes it again with our writer and prints "<file>\t<hex>" lines (the OBJ, its .mtl, textures) for the
-- reference tools (assimp, trimesh) to read back.
local Obj = require("@formats/model/obj")
local Bytes = require("@formats/core/Bytes")
local Cases = require("@tests/gen/obj_cases")
local HEX = {}
for i = 0, 255 do
HEX[i] = string.format("%02x", i)
end
local function hex(s: string): string
local out = table.create(#s)
for i = 1, #s do
out[i] = HEX[string.byte(s, i)]
end
return table.concat(out)
end
for _, c in Cases do
local scene, err = Obj.decode(Bytes.reader(buffer.fromstring(c.data)), { files = c.files })
if not scene then
error(c.name .. ": " .. tostring(err))
end
local name = "rt_" .. c.name
local files = {}
local out = assert(Obj.encode(scene, { name = name, files = files }))
print(name .. "\t" .. hex(buffer.tostring(out)))
for fname, data in files do
print(fname .. "\t" .. hex(if type(data) == "string" then data else buffer.tostring(data)))
end
end
+257
View File
@@ -0,0 +1,257 @@
# OBJ fixtures (tools/fixtures.py): OBJ / MTL files written here (materials, textures, objects and groups, n-gons,
# negative indices, vertex colours, continuation lines, comments, lines and points, a concave polygon) and files
# exported by assimp (from generated PLY meshes), with reference values from assimp (`assimp info`: meshes, materials,
# vertices, faces, bounds) and trimesh (area, triangle count, bounds).
# tests/gen/obj_cases.luau { name, data, files = { name -> bytes }, assimp = {...}, trimesh = {...}, polygonArea? }
# tests/gen/obj_xcheck.luau our encoder's output for every case (tools/fixtures/_obj_encode.luau), read back by assimp
# and trimesh: { name, assimp, trimesh, want = the original's values }
import importlib.util, math, os, struct
INPUTS = ["src/Formats/model/obj", "tools/fixtures/_model_ref.py", "tools/fixtures/_obj_encode.luau"]
def ref_module(ctx):
spec = importlib.util.spec_from_file_location("_model_ref", os.path.join(ctx.root, "tools", "fixtures", "_model_ref.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
return m
def png_1x1():
import zlib
def ch(t, d):
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
return b"\x89PNG\r\n\x1a\n" + ch(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 6, 0, 0, 0)) + ch(b"IDAT", zlib.compress(b"\0\xff\0\0\xff")) + ch(b"IEND", b"")
def fmt(v):
return "%.6g" % v
CUBE = """# a cube: one object, two groups, two materials, a textured quad
mtllib cube.mtl
o Cube
v 0 0 0
v 1 0 0
v 1 1 0
v 0 1 0
v 0 0 1
v 1 0 1
v 1 1 1
v 0 1 1
vt 0 0
vt 1 0
vt 1 1
vt 0 1
vn 0 0 1
g top
usemtl red
s 1
f 5/1/1 6/2/1 7/3/1 8/4/1
g bottom
usemtl blue
f 1 4 3 2
f 1 2 6 5
f 2 3 7 6
f 3 4 8 7
f 4 1 5 8
"""
CUBE_MTL = """# materials
newmtl red
Ka 0.1 0.1 0.1
Kd 1 0 0
Ks 0.5 0.5 0.5
Ns 50
illum 2
map_Kd -s 2 2 1 -o 0.5 0 0 textures/tex.png
map_Bump -bm 0.5 normal.png
newmtl blue
Kd 0 0 1
d 0.5
Pr 0.25
Pm 1
Ke 0.1 0.2 0.3
"""
def sphere(rng, rings, segs, colors=False):
vs, fs = [], []
for i in range(rings - 1): # no poles: assimp turns degenerate triangles into lines
th = math.pi * (i + 1) / rings
for j in range(segs):
ph = 2 * math.pi * j / segs
vs.append((math.sin(th) * math.cos(ph), math.cos(th), math.sin(th) * math.sin(ph)))
for i in range(rings - 2):
for j in range(segs):
a, b = i * segs + j, i * segs + (j + 1) % segs
c, d = a + segs, b + segs
fs.append((a, c, d, b))
return vs, fs
def random_obj(rng):
vs, fs = sphere(rng, 6, 9)
lines = ["# random sphere: quads, triangles, pentagons, negative indices, vertex colours, continuations"]
for v in vs:
lines.append("v %s %s %s %s %s %s" % (fmt(v[0]), fmt(v[1]), fmt(v[2]), fmt(rng.random()), fmt(rng.random()), fmt(rng.random())))
for k in range(len(vs)):
lines.append("vt %s %s" % (fmt(rng.random()), fmt(rng.random())))
lines.append("vn 0 1 0")
lines.append("vn 1 0 0")
lines.append("g sphere")
n = len(vs)
for i, f in enumerate(fs):
if i % 7 == 0:
# negative (relative) indices
lines.append("f " + " ".join("%d/%d" % (v - n, v - n) for v in f))
elif i % 7 == 1:
lines.append("f " + " ".join("%d//%d" % (v + 1, 1 + i % 2) for v in f))
elif i % 7 == 2:
lines.append("f %d/%d/1 %d/%d/2 \\\n %d/%d/1 %d/%d/2" % (f[0] + 1, f[0] + 1, f[1] + 1, f[1] + 1, f[2] + 1, f[2] + 1, f[3] + 1, f[3] + 1))
elif i % 7 == 3:
lines.append("f %d %d %d" % (f[0] + 1, f[1] + 1, f[2] + 1))
lines.append("f %d %d %d" % (f[0] + 1, f[2] + 1, f[3] + 1))
else:
lines.append("f " + " ".join("%d/%d" % (v + 1, v + 1) for v in f))
# a convex pentagon and a hexagon
base = len(vs)
for k in range(5):
lines.append("v %s %s 2" % (fmt(math.cos(2 * math.pi * k / 5)), fmt(math.sin(2 * math.pi * k / 5))))
lines.append("g pentagon")
lines.append("f " + " ".join(str(base + k + 1) for k in range(5)))
return "\n".join(lines) + "\n"
def concave():
# an L-shaped hexagon (area 3) and a U-shaped octagon (area 5) in the xz plane, as n-gons
L = [(0, 0), (2, 0), (2, 1), (1, 1), (1, 2), (0, 2)]
U = [(3, 0), (6, 0), (6, 2), (5, 2), (5, 1), (4, 1), (4, 2), (3, 2)]
lines = ["o shapes"]
for x, z in L + U:
lines.append("v %d 0 %d" % (x, z))
lines.append("f " + " ".join(str(k + 1) for k in range(len(L))))
lines.append("f " + " ".join(str(len(L) + k + 1) for k in range(len(U))))
area = sum(abs(sum(p[i][0] * p[(i + 1) % len(p)][1] - p[(i + 1) % len(p)][0] * p[i][1] for i in range(len(p)))) / 2 for p in (L, U))
return "\n".join(lines) + "\n", area
def lines_points():
return """o wire
v 0 0 0
v 1 0 0
v 1 1 0
v 0 1 0
l 1 2 3 4 1
p 1 3
f 1 2 3
"""
def ply_torus(rng, R=2.0, r=0.5, a=24, b=12):
vs, fs = [], []
for i in range(a):
for j in range(b):
u, v = 2 * math.pi * i / a, 2 * math.pi * j / b
vs.append(((R + r * math.cos(v)) * math.cos(u), r * math.sin(v), (R + r * math.cos(v)) * math.sin(u)))
for i in range(a):
for j in range(b):
p, q = i * b + j, ((i + 1) % a) * b + j
p2, q2 = i * b + (j + 1) % b, ((i + 1) % a) * b + (j + 1) % b
fs.append((p, p2, q2, q))
head = "ply\nformat ascii 1.0\nelement vertex %d\nproperty float x\nproperty float y\nproperty float z\nelement face %d\nproperty list uchar int vertex_indices\nend_header\n" % (len(vs), len(fs))
body = "".join("%r %r %r\n" % v for v in vs) + "".join("4 %d %d %d %d\n" % f for f in fs)
return (head + body).encode()
def fan_area(text):
# the area of every face fan-triangulated (an exact reference in double precision)
text = text.replace("\\\n", " ")
V, A = [], 0.0
for l in text.split("\n"):
w = l.split()
if not w:
continue
if w[0] == "v":
V.append([float(x) for x in w[1:4]])
elif w[0] == "f":
idx = []
for c in w[1:]:
v = int(c.split("/")[0])
idx.append(v - 1 if v > 0 else len(V) + v)
for k in range(1, len(idx) - 1):
a, b, c = V[idx[0]], V[idx[k]], V[idx[k + 1]]
e1 = [b[i] - a[i] for i in range(3)]
e2 = [c[i] - a[i] for i in range(3)]
x, y, z = e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]
A += math.sqrt(x * x + y * y + z * z) / 2
return A
def generate(ctx):
M = ref_module(ctx)
rng = ctx.rng(11)
tmp = M.tempdir()
cases = []
def add(name, data, files=None, **extra):
path = os.path.join(tmp, name)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "wb") as f:
f.write(data)
for fn, fd in (files or {}).items():
p = os.path.join(tmp, fn)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(fd)
c = {"name": name, "data": data, "files": files or {}, "path": path, "fanArea": fan_area(data.decode())}
c.update(extra)
cases.append(c)
png = png_1x1()
add("cube.obj", CUBE.encode(), {"cube.mtl": CUBE_MTL.encode(), "textures/tex.png": png, "normal.png": png})
# assimp joins mixed-attribute corners differently (136 vertices where the file has 101 distinct v/vt/vn): no
# vertex count check for this one
# and trimesh gets its area wrong (12.60 for 12.52: mixed index forms?): only the exact fan area here
add("random.obj", random_obj(rng).encode(), noVertexCount=True, noTrimesh=True)
text, area = concave()
add("concave.obj", text.encode(), polygonArea=area)
add("wire.obj", lines_points().encode(), noTrimesh=True)
# assimp's OBJ exporter, from a PLY torus
ply = os.path.join(tmp, "torus.ply")
with open(ply, "wb") as f:
f.write(ply_torus(rng))
out = os.path.join(tmp, "torus_assimp.obj")
ctx.nix("assimp", ["assimp", "export", ply, out])
files = {}
if os.path.exists(out[:-4] + ".mtl"):
files["torus_assimp.mtl"] = open(out[:-4] + ".mtl", "rb").read()
add("torus_assimp.obj", open(out, "rb").read(), files)
paths = [c["path"] for c in cases]
infos = M.assimp_info(ctx, paths)
tm = M.trimesh_metrics(ctx, [c["path"] for c in cases if not c.get("noTrimesh")])
k = 0
for c, info in zip(cases, infos):
c["assimp"] = info
if not c.get("noTrimesh"):
c["trimesh"] = tm[k]
k += 1
for c in cases:
del c["path"]
ctx.emit("obj_cases", cases)
# the reference tools read our encoder's output (decode -> encode in Luau, then assimp / trimesh)
ours = M.luau_encode(ctx, "tools/fixtures/_obj_encode.luau")
xtmp = M.tempdir()
names = []
for name, data in sorted(ours.items()):
p = os.path.join(xtmp, name)
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "wb") as f:
f.write(data)
if name.endswith(".obj"):
names.append(name)
xinfos = M.assimp_info(ctx, [os.path.join(xtmp, n) for n in names])
xtm = M.trimesh_metrics(ctx, [os.path.join(xtmp, n) for n in names])
ctx.emit("obj_xcheck", [{"name": n, "assimp": a, "trimesh": t} for n, a, t in zip(names, xinfos, xtm)])