481 lines
16 KiB
Luau
481 lines
16 KiB
Luau
--!strict
|
|
-- model/off: OFF (Geomview Object File Format), text, read + write. Written from the Geomview OFF description
|
|
-- (geomview.org/docs/html/OFF.html).
|
|
-- Decode: the header keyword [ST][C][N]OFF (texture coordinates, vertex colours, normals; the counts may follow on the
|
|
-- same line), `nv nf [ne]`, vertex lines `x y z [nx ny nz] [r g b [a]] [s t]`, face lines `n i1 .. in [colour]`;
|
|
-- `#` comments and blank lines anywhere. Vertices: POSITION f32 x3, NORMAL f32 x3, TEXCOORD_0 f32 x2, COLOR_0: unorm8
|
|
-- x4 when the colours are integers (0..255) and some value is above 1, else f32 x4 (alpha full when only RGB is given).
|
|
-- Faces: triangles as u32 indices; n-gons fan-triangulated (opts.triangulate, default true: right for convex faces;
|
|
-- faces of fewer than 3 vertices are dropped, prim.extras.faceOfTriangle maps triangles to file faces when there are
|
|
-- face colours) or kept as mode "polygons" (prim.faces). Face colours (3 or 4 values after the indices; integers or
|
|
-- floats as for vertices; faces without one get opaque white): prim.extras.faceColors, one per file face. A single
|
|
-- value after the indices (a colormap index) is ignored (meta.source.colormap = true). No faces: mode "points".
|
|
-- meta.source = { format, keyword, vertices, faces, edges }.
|
|
-- Encode: every primitive in world space (node transforms applied) into one vertex list, NOFF / COFF / STOFF prefixes
|
|
-- for NORMAL / COLOR_0 / TEXCOORD_0 (unorm8 colours as integers 0..255, other colour types as floats 0..1), n-gons
|
|
-- natively, face colours from prim.extras.faceColors (a single primitive), point clouds with 0 faces; lines are
|
|
-- skipped. Floats print as %.9g (f32-exact). Not supported: 4OFF / nOFF (homogeneous / n-dimensional) and binary OFF
|
|
-- (UNSUPPORTED).
|
|
|
|
-- ------------------------------------------------------------------------------------------------ requires
|
|
local Err = require("@formats/core/Err")
|
|
local Bytes = require("@formats/core/Bytes")
|
|
local Types = require("@formats/Types")
|
|
local Flatten = require("@formats/codecs/MeshFlatten")
|
|
|
|
-- ------------------------------------------------------------------------------------------------ contract
|
|
local Off = {
|
|
name = "off",
|
|
category = "model",
|
|
extensions = { "off" },
|
|
mime = { "model/off", "text/plain" },
|
|
deps = { "core/Err", "core/Bytes", "Types", "codecs/MeshFlatten" },
|
|
caps = { decode = true, encode = true, polygons = true, points = true, colors = true, binary = false },
|
|
}
|
|
|
|
-- ------------------------------------------------------------------------------------------------ types
|
|
export type DecodeOptions = {
|
|
triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps them as mode "polygons"
|
|
maxVertices: number?, -- default 2^24
|
|
maxFaces: number?, -- default 2^25
|
|
}
|
|
export type EncodeOptions = {
|
|
colors: boolean?, -- write COLOR_0 (COFF) and prim.extras.faceColors when present (default true)
|
|
normals: boolean?, -- write NORMAL (NOFF) when present (default true)
|
|
texcoords: boolean?, -- write TEXCOORD_0 (STOFF) when present (default true)
|
|
comment: string?, -- a "# ..." line after the header keyword
|
|
}
|
|
|
|
-- ------------------------------------------------------------------------------------------------ constants
|
|
local writef32, writeu8, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu32
|
|
|
|
-- ------------------------------------------------------------------------------------------------ sniff
|
|
function Off.sniff(r: Bytes.Reader): number
|
|
local head = r:peek(512)
|
|
for _ = 1, 16 do -- leading comment lines
|
|
local rest = string.match(head, "^%s*#[^\n]*\n(.*)$")
|
|
if not rest then
|
|
break
|
|
end
|
|
head = rest
|
|
end
|
|
local kw = string.match(head, "^%s*(%w+)")
|
|
if kw and string.match(kw, "^S?T?C?N?4?n?OFF$") then
|
|
return 0.9
|
|
end
|
|
return 0
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ decode
|
|
-- colours: a list of numbers + whether a token looked like a float; decide unorm8 or f32
|
|
type ColorSet = { values: { number }, float: boolean, max: number }
|
|
|
|
local function colorType(c: ColorSet): string
|
|
return if not c.float and c.max > 1 then "unorm8" else "f32"
|
|
end
|
|
|
|
-- the colour accessor for count entries of 4 values (nan = absent: opaque white)
|
|
local function colorAccessor(c: ColorSet, count: number): (Types.Accessor?, string?)
|
|
local t = colorType(c)
|
|
local buf = buffer.create(count * (if t == "unorm8" then 4 else 16))
|
|
local vals = c.values
|
|
for i = 0, count * 4 - 1 do
|
|
local v = vals[i + 1]
|
|
if t == "unorm8" then
|
|
if v ~= v then
|
|
v = 255
|
|
elseif v < 0 or v > 255 or v % 1 ~= 0 then
|
|
return nil, "colour value out of range"
|
|
end
|
|
writeu8(buf, i, v)
|
|
else
|
|
writef32(buf, i * 4, if v ~= v then 1 else v)
|
|
end
|
|
end
|
|
return Types.Scene.accessor(buf, t, 4, count), nil
|
|
end
|
|
|
|
local function addColor(c: ColorSet, toks: { string }, from: number, n: number)
|
|
local vals = c.values
|
|
for k = 0, 3 do
|
|
if k < n then
|
|
local s = toks[from + k]
|
|
local v = tonumber(s) :: number
|
|
table.insert(vals, v)
|
|
if not c.float and string.find(s, "[%.eEnN]") then
|
|
c.float = true
|
|
end
|
|
if v > c.max then
|
|
c.max = v
|
|
end
|
|
else
|
|
table.insert(vals, 0 / 0) -- absent: full (opaque white)
|
|
end
|
|
end
|
|
end
|
|
|
|
function Off.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
|
|
local triangulate = true
|
|
if opts and opts.triangulate == false then
|
|
triangulate = false
|
|
end
|
|
local maxVertices = opts and opts.maxVertices or 2 ^ 24
|
|
local maxFaces = opts and opts.maxFaces or 2 ^ 25
|
|
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
|
|
-- the next non-empty line's tokens (comments stripped)
|
|
local at = 1
|
|
local lineNo = 0
|
|
local function line(): { string }?
|
|
while at <= #text do
|
|
local e = string.find(text, "\n", at, true) or (#text + 1)
|
|
local s = string.sub(text, at, e - 1)
|
|
at = e + 1
|
|
lineNo += 1
|
|
local hash = string.find(s, "#", 1, true)
|
|
if hash then
|
|
s = string.sub(s, 1, hash - 1)
|
|
end
|
|
local toks = {}
|
|
for w in string.gmatch(s, "%S+") do
|
|
table.insert(toks, w)
|
|
end
|
|
if #toks > 0 then
|
|
return toks
|
|
end
|
|
end
|
|
return nil
|
|
end
|
|
local head = line()
|
|
if not head then
|
|
return nil, Err.new(Err.TRUNCATED, "empty file")
|
|
end
|
|
local kw = head[1]
|
|
local rest = kw
|
|
local st, hasC, hasN = false, false, false
|
|
if string.sub(rest, 1, 2) == "ST" then
|
|
st, rest = true, string.sub(rest, 3)
|
|
end
|
|
if string.sub(rest, 1, 1) == "C" then
|
|
hasC, rest = true, string.sub(rest, 2)
|
|
end
|
|
if string.sub(rest, 1, 1) == "N" then
|
|
hasN, rest = true, string.sub(rest, 2)
|
|
end
|
|
if rest == "4OFF" or rest == "nOFF" or rest == "4nOFF" then
|
|
return nil, Err.new(Err.UNSUPPORTED, kw .. " (homogeneous / n-dimensional vertices)")
|
|
elseif rest ~= "OFF" then
|
|
return nil, Err.new(Err.CORRUPT, "bad header keyword " .. string.sub(kw, 1, 20))
|
|
end
|
|
local counts: { string }
|
|
if head[2] == "BINARY" then
|
|
return nil, Err.new(Err.UNSUPPORTED, "binary OFF")
|
|
elseif #head >= 3 then
|
|
counts = { head[2], head[3], head[4] }
|
|
else
|
|
local c = line()
|
|
if not c then
|
|
return nil, Err.new(Err.TRUNCATED, "no counts line")
|
|
end
|
|
counts = c
|
|
end
|
|
local nv, nf, ne = tonumber(counts[1]), tonumber(counts[2]), tonumber(counts[3] or "0")
|
|
if not nv or not nf or nv < 0 or nf < 0 or nv % 1 ~= 0 or nf % 1 ~= 0 then
|
|
return nil, Err.new(Err.CORRUPT, "bad counts line")
|
|
end
|
|
if nv > maxVertices then
|
|
return nil, Err.new(Err.LIMIT, string.format("%d vertices is over the %d vertex limit", nv, maxVertices))
|
|
end
|
|
if nf > maxFaces then
|
|
return nil, Err.new(Err.LIMIT, string.format("%d faces is over the %d face limit", nf, maxFaces))
|
|
end
|
|
-- every vertex / face line takes at least 6 / 2 bytes
|
|
if nv * 6 + nf * 2 > #text - at + 2 then
|
|
return nil, Err.new(Err.TRUNCATED, "fewer lines than the counts need")
|
|
end
|
|
local fixed = 3 + (if hasN then 3 else 0) + (if st then 2 else 0)
|
|
local pos = buffer.create(nv * 12)
|
|
local nrm = if hasN then buffer.create(nv * 12) else nil
|
|
local tex = if st then buffer.create(nv * 8) else nil
|
|
local vcol: ColorSet = { values = {}, float = false, max = 0 }
|
|
for i = 0, nv - 1 do
|
|
local t = line()
|
|
if not t then
|
|
return nil, Err.new(Err.TRUNCATED, string.format("vertex %d missing", i))
|
|
end
|
|
local n = #t
|
|
local nc = 0
|
|
if hasC then
|
|
nc = n - fixed
|
|
if nc ~= 3 and nc ~= 4 then
|
|
return nil, Err.new(Err.CORRUPT, string.format("vertex %d: expected %d values and an RGB / RGBA colour", i, fixed))
|
|
end
|
|
elseif n < fixed then
|
|
return nil, Err.new(Err.CORRUPT, string.format("vertex %d: expected %d values", i, fixed))
|
|
end
|
|
for k = 1, fixed + nc do
|
|
if tonumber(t[k]) == nil then
|
|
return nil, Err.new(Err.CORRUPT, string.format("vertex %d: bad number", i))
|
|
end
|
|
end
|
|
writef32(pos, i * 12, tonumber(t[1]) :: number)
|
|
writef32(pos, i * 12 + 4, tonumber(t[2]) :: number)
|
|
writef32(pos, i * 12 + 8, tonumber(t[3]) :: number)
|
|
local k = 4
|
|
if nrm then
|
|
writef32(nrm, i * 12, tonumber(t[4]) :: number)
|
|
writef32(nrm, i * 12 + 4, tonumber(t[5]) :: number)
|
|
writef32(nrm, i * 12 + 8, tonumber(t[6]) :: number)
|
|
k = 7
|
|
end
|
|
if hasC then
|
|
addColor(vcol, t, k, nc)
|
|
k += nc
|
|
end
|
|
if tex then
|
|
writef32(tex, i * 8, tonumber(t[k]) :: number)
|
|
writef32(tex, i * 8 + 4, tonumber(t[k + 1]) :: number)
|
|
end
|
|
end
|
|
local sizes = buffer.create(nf * 4)
|
|
local corners: { number } = {}
|
|
local fcol: ColorSet = { values = {}, float = false, max = 0 }
|
|
local anyFaceColor, colormap = false, false
|
|
for f = 0, nf - 1 do
|
|
local t = line()
|
|
if not t then
|
|
return nil, Err.new(Err.TRUNCATED, string.format("face %d missing", f))
|
|
end
|
|
local n = tonumber(t[1])
|
|
if n == nil or n < 0 or n % 1 ~= 0 or #t < n + 1 then
|
|
return nil, Err.new(Err.CORRUPT, string.format("face %d: bad vertex count", f))
|
|
end
|
|
writeu32(sizes, f * 4, n)
|
|
for k = 2, n + 1 do
|
|
local v = tonumber(t[k])
|
|
if v == nil or v < 0 or v >= nv or v % 1 ~= 0 then
|
|
return nil, Err.new(Err.CORRUPT, string.format("face %d: vertex index out of range", f))
|
|
end
|
|
table.insert(corners, v)
|
|
end
|
|
local nc = #t - n - 1
|
|
if nc == 3 or nc == 4 then
|
|
for k = n + 2, #t do
|
|
if tonumber(t[k]) == nil then
|
|
return nil, Err.new(Err.CORRUPT, string.format("face %d: bad colour", f))
|
|
end
|
|
end
|
|
addColor(fcol, t, n + 2, nc)
|
|
anyFaceColor = true
|
|
else
|
|
if nc == 1 then
|
|
colormap = true
|
|
end
|
|
addColor(fcol, t, 1, 0)
|
|
end
|
|
end
|
|
-- the primitive
|
|
local attrs: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, nv) }
|
|
if nrm then
|
|
attrs.NORMAL = Types.Scene.accessor(nrm, "f32", 3, nv)
|
|
end
|
|
if hasC then
|
|
local acc, cerr = colorAccessor(vcol, nv)
|
|
if not acc then
|
|
return nil, Err.new(Err.CORRUPT, "vertex " .. tostring(cerr))
|
|
end
|
|
attrs.COLOR_0 = acc
|
|
end
|
|
if tex then
|
|
attrs.TEXCOORD_0 = Types.Scene.accessor(tex, "f32", 2, nv)
|
|
end
|
|
local prim: Types.Primitive = { attributes = attrs, mode = "points" }
|
|
local extras: { [string]: any } = {}
|
|
if anyFaceColor then
|
|
local acc, cerr = colorAccessor(fcol, nf)
|
|
if not acc then
|
|
return nil, Err.new(Err.CORRUPT, "face " .. tostring(cerr))
|
|
end
|
|
extras.faceColors = acc
|
|
end
|
|
if nf > 0 then
|
|
local total = #corners
|
|
local cbuf = buffer.create(total * 4)
|
|
for i = 1, total do
|
|
writeu32(cbuf, (i - 1) * 4, corners[i])
|
|
end
|
|
local allTri = total == nf * 3
|
|
if allTri then
|
|
for f = 0, nf - 1 do
|
|
if buffer.readu32(sizes, f * 4) ~= 3 then
|
|
allTri = false
|
|
break
|
|
end
|
|
end
|
|
end
|
|
if allTri then
|
|
prim.mode = "triangles"
|
|
prim.indices = Types.Scene.accessor(cbuf, "u32", 1, total)
|
|
elseif triangulate then
|
|
local tris: { number } = {}
|
|
local fot: { number } = {}
|
|
local p = 0
|
|
for f = 0, nf - 1 do
|
|
local s = buffer.readu32(sizes, f * 4)
|
|
for k = 1, s - 2 do
|
|
table.insert(tris, corners[p + 1])
|
|
table.insert(tris, corners[p + k + 1])
|
|
table.insert(tris, corners[p + k + 2])
|
|
table.insert(fot, f)
|
|
end
|
|
p += s
|
|
end
|
|
local ib = buffer.create(#tris * 4)
|
|
for i, v in tris do
|
|
writeu32(ib, (i - 1) * 4, v)
|
|
end
|
|
prim.mode = "triangles"
|
|
prim.indices = Types.Scene.accessor(ib, "u32", 1, #tris)
|
|
if anyFaceColor then
|
|
local fb = buffer.create(#fot * 4)
|
|
for i, v in fot do
|
|
writeu32(fb, (i - 1) * 4, v)
|
|
end
|
|
extras.faceOfTriangle = Types.Scene.accessor(fb, "u32", 1, #fot)
|
|
end
|
|
else
|
|
prim.mode = "polygons"
|
|
prim.indices = Types.Scene.accessor(cbuf, "u32", 1, total)
|
|
prim.faces = Types.Scene.accessor(sizes, "u32", 1, nf)
|
|
end
|
|
end
|
|
if next(extras) then
|
|
prim.extras = extras
|
|
end
|
|
local scene = Types.Scene.fromPrimitive(prim, nil)
|
|
scene.meta.source = { format = "off", keyword = kw, vertices = nv, faces = nf, edges = ne or 0, colormap = colormap or nil }
|
|
return scene, nil
|
|
end
|
|
|
|
-- ------------------------------------------------------------------------------------------------ encode
|
|
local scratch = buffer.create(4)
|
|
local function fnum(v: number): string?
|
|
writef32(scratch, 0, v)
|
|
v = buffer.readf32(scratch, 0)
|
|
if v ~= v or v == math.huge or v == -math.huge then
|
|
return nil
|
|
end
|
|
return string.format("%.9g", v)
|
|
end
|
|
|
|
-- a colour attribute's 4 components of entry i (0-based) as text
|
|
local function colorText(a: Flatten.Attr, vals: { number }, comps: number, i: number): string
|
|
local out = table.create(4)
|
|
for c = 1, 4 do
|
|
local v = if c <= comps then vals[i * comps + c] else nil
|
|
if a.raw and a.type == "unorm8" then
|
|
out[c] = string.format("%d", if v == nil then 255 else math.clamp(v, 0, 255))
|
|
else
|
|
if v == nil then
|
|
v = 1
|
|
elseif a.raw then
|
|
v = if a.type == "unorm16" then v / 65535 elseif a.type == "snorm8" then math.max(v / 127, -1) else math.max(v / 32767, -1)
|
|
end
|
|
out[c] = fnum(v :: number) or "0"
|
|
end
|
|
end
|
|
return table.concat(out, " ")
|
|
end
|
|
|
|
function Off.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
|
|
local o: EncodeOptions = opts or {}
|
|
local wantC, wantN, wantT = o.colors ~= false, o.normals ~= false, o.texcoords ~= false
|
|
local m, merr = Flatten.merge(scene, function(name: string): boolean
|
|
return (name == "NORMAL" and wantN) or (name == "COLOR_0" and wantC) or (name == "TEXCOORD_0" and wantT)
|
|
end, { triangulate = false })
|
|
if not m then
|
|
return nil, Err.new(Err.ARG, tostring(merr))
|
|
end
|
|
local A = m.attrs
|
|
local P, N, C, T = A.POSITION, A.NORMAL, A.COLOR_0, A.TEXCOORD_0
|
|
if T and T.raw then
|
|
return nil, Err.new(Err.ARG, "TEXCOORD_0 of a normalized integer type")
|
|
end
|
|
local nv = m.count
|
|
local sizes = m.sizes or {}
|
|
local nf = #sizes
|
|
local out = table.create(nv + nf + 3)
|
|
table.insert(out, (if T then "ST" else "") .. (if C then "C" else "") .. (if N then "N" else "") .. "OFF")
|
|
if o.comment then
|
|
table.insert(out, "# " .. string.gsub(o.comment, "[\r\n]", " "))
|
|
end
|
|
table.insert(out, string.format("%d %d 0", nv, nf))
|
|
local pv = P.values
|
|
for i = 0, nv - 1 do
|
|
local x, y, z = fnum(pv[i * 3 + 1]), fnum(pv[i * 3 + 2]), fnum(pv[i * 3 + 3])
|
|
if not (x and y and z) then
|
|
return nil, Err.new(Err.ARG, "OFF cannot hold a non-finite coordinate")
|
|
end
|
|
local s = x .. " " .. y .. " " .. z
|
|
if N then
|
|
local nvv = N.values
|
|
s ..= " " .. (fnum(nvv[i * 3 + 1]) or "0") .. " " .. (fnum(nvv[i * 3 + 2]) or "0") .. " " .. (fnum(nvv[i * 3 + 3]) or "0")
|
|
end
|
|
if C then
|
|
s ..= " " .. colorText(C, C.values, C.components, i)
|
|
end
|
|
if T then
|
|
local tv, tc = T.values, T.components
|
|
s ..= " " .. (fnum(tv[i * tc + 1]) or "0") .. " " .. (fnum(if tc >= 2 then tv[i * tc + 2] else 0) or "0")
|
|
end
|
|
table.insert(out, s)
|
|
end
|
|
-- face colours of a single primitive (per file face, or through faceOfTriangle)
|
|
local fc: Flatten.Attr? = nil
|
|
local fcMap: { number }? = nil
|
|
if wantC and #m.parts == 1 and nf > 0 then
|
|
local ex = m.parts[1].prim.extras
|
|
local acc = type(ex) == "table" and ex.faceColors
|
|
if acc then
|
|
local raw = acc.type == "unorm8" or acc.type == "unorm16" or acc.type == "snorm8" or acc.type == "snorm16"
|
|
local vals = Flatten.numbers(acc, raw)
|
|
if vals then
|
|
local a: Flatten.Attr = { type = acc.type, components = acc.components, raw = raw, values = vals }
|
|
if acc.count == nf then
|
|
fc = a
|
|
elseif ex.faceOfTriangle then
|
|
local fot = Flatten.numbers(ex.faceOfTriangle, true)
|
|
if fot and #fot == nf then
|
|
fc, fcMap = a, fot
|
|
for _, f in fot do
|
|
if f < 0 or f >= acc.count then
|
|
fc = nil
|
|
break
|
|
end
|
|
end
|
|
end
|
|
end
|
|
end
|
|
end
|
|
end
|
|
local corners = m.corners
|
|
local p = 0
|
|
for f = 1, nf do
|
|
local s = sizes[f]
|
|
local line = table.create(s + 2)
|
|
line[1] = string.format("%d", s)
|
|
for k = 1, s do
|
|
line[k + 1] = string.format("%d", corners[p + k])
|
|
end
|
|
p += s
|
|
if fc then
|
|
local src = if fcMap then fcMap[f] else f - 1
|
|
table.insert(line, colorText(fc, fc.values, fc.components, src))
|
|
end
|
|
table.insert(out, table.concat(line, " "))
|
|
end
|
|
table.insert(out, "")
|
|
return buffer.fromstring(table.concat(out, "\n")), nil
|
|
end
|
|
|
|
return Off
|