merge ws/3d3

This commit is contained in:
4DBug committed 2026-10-31 15:39:55 -05:00
commit 47345b2c8f
96 files changed
+24729 -21

No files matched your search

+134 -2
View File
@@ -398,6 +398,18 @@ local list: { Entry } = {
return require("@formats/video/y4m")
end,
},
{
name = "3ds",
category = "model",
path = "model/3ds",
extensions = { "3ds" },
mime = { "application/x-3ds", "image/x-3ds" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Sampler" },
caps = { decode = true, encode = true, materials = true, textures = true, animation = true, cameras = true, lights = true, instancing = true },
load = function()
return require("@formats/model/3ds")
end,
},
{
name = "3mf",
category = "model",
@@ -410,6 +422,18 @@ local list: { Entry } = {
return require("@formats/model/3mf")
end,
},
{
name = "b3d",
category = "model",
path = "model/b3d",
extensions = { "b3d" },
mime = { "model/x-b3d" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/model/Mat4" },
caps = { decode = true, encode = false, materials = true, textures = true, skins = true, animation = true, colors = true },
load = function()
return require("@formats/model/b3d")
end,
},
{
name = "dae",
category = "model",
@@ -440,12 +464,48 @@ local list: { Entry } = {
path = "model/gltf",
extensions = { "gltf", "glb" },
mime = { "model/gltf+json", "model/gltf-binary" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff" },
caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff", "codecs/model/Draco" },
caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, draco = true },
load = function()
return require("@formats/model/gltf")
end,
},
{
name = "iqm",
category = "model",
path = "model/iqm",
extensions = { "iqm" },
mime = { "model/x-iqm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Sampler" },
caps = { decode = true, encode = true, materials = true, skins = true, animation = true, vertexColors = true },
load = function()
return require("@formats/model/iqm")
end,
},
{
name = "ldraw",
category = "model",
path = "model/ldraw",
extensions = { "ldr", "mpd", "dat" },
mime = { "application/x-ldraw", "application/x-multi-part-ldraw" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
caps = { decode = true, encode = false, materials = true, lines = true, instancing = true },
load = function()
return require("@formats/model/ldraw")
end,
},
{
name = "lwo",
category = "model",
path = "model/lwo",
extensions = { "lwo", "lxo" },
mime = { "image/x-lwo", "model/x-lwo" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks" },
caps = { decode = true, encode = false, materials = true, polygons = true, vertexColors = true, morphTargets = true },
load = function()
return require("@formats/model/lwo")
end,
},
{
name = "mca",
category = "model",
@@ -458,6 +518,18 @@ local list: { Entry } = {
return require("@formats/model/mca")
end,
},
{
name = "ms3d",
category = "model",
path = "model/ms3d",
extensions = { "ms3d" },
mime = { "application/x-ms3d" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" },
caps = { decode = true, encode = true, materials = true, skins = true, animation = true },
load = function()
return require("@formats/model/ms3d")
end,
},
{
name = "obj",
category = "model",
@@ -494,6 +566,18 @@ local list: { Entry } = {
return require("@formats/model/ply")
end,
},
{
name = "pmx",
category = "model",
path = "model/pmx",
extensions = { "pmx", "pmd" },
mime = { "model/x-pmx", "model/x-pmd" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text" },
caps = { decode = true, encode = false, materials = true, skins = true, morphTargets = true, pmd = true },
load = function()
return require("@formats/model/pmx")
end,
},
{
name = "qb",
category = "model",
@@ -590,6 +674,42 @@ local list: { Entry } = {
return require("@formats/model/vox")
end,
},
{
name = "vrml",
category = "model",
path = "model/vrml",
extensions = { "wrl", "wrz", "vrml" },
mime = { "model/vrml", "x-world/x-vrml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" },
caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true },
load = function()
return require("@formats/model/vrml")
end,
},
{
name = "x",
category = "model",
path = "model/x",
extensions = { "x" },
mime = { "model/x-directx", "text/x-directx" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/model/Mat4", "codecs/model/Rig" },
caps = { decode = true, encode = false, text = true, binary = true, compressed = true, materials = true, skins = true, animation = true, polygons = true, vertexColors = true },
load = function()
return require("@formats/model/x")
end,
},
{
name = "x3d",
category = "model",
path = "model/x3d",
extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" },
mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" },
caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true },
load = function()
return require("@formats/model/x3d")
end,
},
{
name = "step",
category = "cad",
@@ -698,6 +818,18 @@ local list: { Entry } = {
return require("@formats/archive/gzip")
end,
},
{
name = "pak",
category = "archive",
path = "archive/pak",
extensions = { "pak", "sin" },
mime = { "application/x-pak" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" },
caps = { decode = true, encode = true, variants = { "quake", "sin" } },
load = function()
return require("@formats/archive/pak")
end,
},
{
name = "tar",
category = "archive",
+135
View File
@@ -0,0 +1,135 @@
--!strict
-- archive/pak: Quake / Quake II / Half-Life PAK archives ("PACK": 56-byte names, 64-byte directory entries) and the
-- SiN variant ("SPAK": 120-byte names), read into the standard Archive (entries read lazily: a copy of the stored
-- bytes) and written from any Archive value. Written from the format description in the Quake source release
-- (common.c: dpackheader_t / dpackfile_t) and the Quake specs; no code taken.
-- Not supported: Daikatana's compressed PAK entries.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Sniff = require("@formats/core/Sniff")
local Archive = require("@formats/containers/Archive")
-- ------------------------------------------------------------------------------------------------ contract
local Pak = {
name = "pak",
category = "archive",
extensions = { "pak", "sin" },
mime = { "application/x-pak" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "containers/Archive" },
caps = { decode = true, encode = true, variants = { "quake", "sin" } },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = { maxEntries: number? } -- default 1e6
export type EncodeOptions = { variant: ("quake" | "sin")? } -- default: the source variant, else "quake"
-- ------------------------------------------------------------------------------------------------ constants
local VARIANTS = { quake = { magic = "PACK", nameLen = 56 }, sin = { magic = "SPAK", nameLen = 120 } }
-- ------------------------------------------------------------------------------------------------ sniff
function Pak.sniff(r: Bytes.Reader): number
if r:remaining() < 12 then
return 0
end
return math.max(Sniff.magic(r, "PACK", 0, 0.9), Sniff.magic(r, "SPAK", 0, 0.9))
end
-- ------------------------------------------------------------------------------------------------ decode
local function encode(archive: any, opts: any?): (buffer?, Err.Err?)
return Pak.encode(archive, opts)
end
function Pak.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local magic = r:string(4)
local dirOfs, dirLen = r:u32le(), r:u32le()
if r.err then
return nil, r.err
end
local variant = if magic == "PACK" then "quake" elseif magic == "SPAK" then "sin" else nil
if not variant then
return nil, Err.new(Err.CORRUPT, "bad magic", 0)
end
local nameLen = VARIANTS[variant].nameLen
local entrySize = nameLen + 8
local size = r.limit - r.base
if dirOfs + dirLen > size then
return nil, Err.new(Err.TRUNCATED, "directory past the end", 4)
end
if dirLen % entrySize ~= 0 then
return nil, Err.new(Err.CORRUPT, "directory size is not a multiple of " .. entrySize, 8)
end
local count = dirLen // entrySize
if count > (opts and opts.maxEntries or 1e6) then
return nil, Err.new(Err.LIMIT, "too many entries: " .. count)
end
local a = Archive.new("pak", encode)
local d = r:sub(dirOfs, dirLen)
for i = 0, count - 1 do
local name = d:fixed(nameLen)
local at, n = d:u32le(), d:u32le()
if d.err then
return nil, d.err
end
if at + n > size then
return nil, Err.new(Err.TRUNCATED, "entry " .. name .. " past the end", dirOfs + i * entrySize)
end
Archive.put(a, { name = name, size = n, dir = false, method = "store", offset = at, load = Archive.slice(r.buf, r.base + at, n) })
end
a.meta.source = { format = "pak", variant = variant, entries = count }
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Pak.encode(archive: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local items, err = Archive.collect(archive)
if not items then
return nil, err
end
local src = type(archive) == "table" and type(archive.meta) == "table" and archive.meta.source
local variant = opts and opts.variant or (if type(src) == "table" and src.format == "pak" then src.variant else nil) or "quake"
local v = VARIANTS[variant]
if not v then
return nil, Err.new(Err.ARG, "unknown variant " .. tostring(variant))
end
local files: { { name: string, data: buffer } } = {}
for _, it in items do
if not it.entry.dir then
local name = string.gsub(it.entry.name, "\\", "/")
if #name >= v.nameLen then
return nil, Err.new(Err.ARG, "name longer than " .. (v.nameLen - 1) .. " bytes: " .. name)
end
table.insert(files, { name = name, data = it.data })
end
end
local w = Bytes.writer()
w:string(v.magic)
w:u32le(0)
w:u32le(0)
local offsets: { number } = {}
for i, f in files do
offsets[i] = w:tell()
w:bytes(f.data)
end
local dirOfs = w:tell()
for i, f in files do
w:string(f.name)
w:fill(0, v.nameLen - #f.name)
w:u32le(offsets[i])
w:u32le(buffer.len(f.data))
end
w:setU32le(4, dirOfs)
w:setU32le(8, w:tell() - dirOfs)
return w:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- new(variant?) -> an empty PAK Archive: a:add(name, data); a:write()
function Pak.new(variant: ("quake" | "sin")?): any
local a = Archive.new("pak", encode)
a.meta.source = { format = "pak", variant = variant or "quake" }
return a
end
return Pak
+21
View File
@@ -13,6 +13,27 @@ local band, rshift, bor, lshift = bit32.band, bit32.rshift, bit32.bor, bit32.lsh
local Pixels = {}
-- palette(src, base, n, bgr?) -> a 256-entry u32 palette for indexed(): n RGB triples (BGR when bgr) at src[base..],
-- opaque; entries past n (or past the end of src) are opaque black. The game formats' 768-byte palettes (PLAYPAL,
-- Quake palette.lmp, Half-Life MDL / WAD3 / BSP 30 textures).
function Pixels.palette(src: buffer, base: number, n: number, bgr: boolean?): buffer
local pal = buffer.create(1024)
local m = if base >= 0 then math.clamp(math.min(n, (buffer.len(src) - base) // 3), 0, 256) else 0
for i = 0, 255 do
local v = 0xFF000000
if i < m then
local o = base + i * 3
local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2)
if bgr then
r, b = b, r
end
v = bor(0xFF000000, lshift(b, 16), lshift(g, 8), r)
end
writeu32(pal, i * 4, v)
end
return pal
end
-- 1, 2, 4 and 8 bpp through a 256-entry u32 palette (pal)
function Pixels.indexed(src: buffer, base: number, stride: number, bpp: number, dst: buffer, w: number, h: number,
topDown: boolean, pal: buffer)
@@ -0,0 +1,479 @@
--!strict
-- codecs/model/Draco/Attributes: Draco attribute decoding. The attributes decoders (one per connectivity: linear
-- sequencer for sequential meshes and point clouds, traversal sequencers for Edgebreaker), their attribute
-- descriptors, and the sequential attribute decoders: generic (raw values), integer, quantization (dequantized to
-- f32 exactly like the C++) and octahedral normals; prediction through codecs/model/Draco/Predict. Bitstream
-- versions 1.0 - 2.2. Ported from Google's Draco 1.5.7 (compression/attributes/*, compression/point_cloud/
-- point_cloud_decoder.cc, attributes/attribute_quantization_transform.cc, attribute_octahedron_transform.cc;
-- Apache-2.0, licenses/draco-LICENSE.txt).
local Reader = require("@formats/codecs/model/Draco/Reader")
local Connectivity = require("@formats/codecs/model/Draco/Connectivity")
local Predict = require("@formats/codecs/model/Draco/Predict")
local KdTree = require("@formats/codecs/model/Draco/KdTree")
local Attributes = {}
type D = Reader.D
-- data type ids (draco::DataType) -> byte length
local DT_LENGTH = { [1] = 1, [2] = 1, [3] = 2, [4] = 2, [5] = 4, [6] = 4, [7] = 8, [8] = 8, [9] = 4, [10] = 8, [11] = 1 }
Attributes.DT_LENGTH = DT_LENGTH
export type Attr = {
id: number, -- 0-based attribute id
type: number, -- GeometryAttribute::Type (0 POSITION, 1 NORMAL, 2 COLOR, 3 TEX_COORD, 4 GENERIC, 5.. transcoder types)
dataType: number,
comps: number,
normalized: boolean,
uniqueId: number,
seqType: number, -- 0 generic, 1 integer, 2 quantization, 3 normals
map: { number }?, -- point -> value (0-based values at [point + 1]); nil = identity
numValues: number,
portable: { number }?, -- the integer (portable) values
values: { number }?, -- the final values (numbers), flat
raw: buffer?, -- generic attributes: the raw values
quant: { min: { number }, range: number, bits: number }?,
octBits: number?,
scheme: Predict.Scheme?,
}
type Decoder = {
attrs: { Attr },
traversal: { ct: Connectivity.CT, enc: Connectivity.Enc, method: number }?,
md: Predict.MeshData?,
points: { number }?,
}
-- the geometry the attributes decode against
export type Geom = { numPoints: number, mesh: Connectivity.Mesh?, edgebreaker: boolean, kdTree: boolean }
local function zigzag(v: number): number
if v % 2 == 1 then
return -(v // 2) - 1
end
return v // 2
end
-- the parent (position) getter for a scheme: portable integers from 2.0 on, the final values before (truncated to
-- integers unless the scheme works in floats)
local function parentGetter(ver: number, pos: Attr, floats: boolean): Predict.Parent?
local old = ver < 0x0200
local vals = if old then pos.values else pos.portable
if not vals or pos.comps ~= 3 or (not old and pos.seqType == 3) then
return nil
end
local map = pos.map
local trunc = old and not floats
return function(point: number): (number, number, number)
local e = if map then (map[point + 1] or 0) else point
local o = e * 3
local x, y, z = vals[o + 1] or 0, vals[o + 2] or 0, vals[o + 3] or 0
if trunc then
x = if x < 0 then math.ceil(x) else math.floor(x)
y = if y < 0 then math.ceil(y) else math.floor(y)
z = if z < 0 then math.ceil(z) else math.floor(z)
end
return x, y, z
end
end
local function decodeIntegerValues(d: D, a: Attr, points: { number }, scheme: Predict.Scheme?): (boolean, string?)
local comps = if a.seqType == 3 then 2 else a.comps
local n = #points
local numValues = n * comps
if n == 0 then
return false, "no values"
end
local compressed = Reader.u8(d)
if d.bad then
return false, d.bad
end
local vals: { number }
if compressed > 0 then
local s = Reader.symbols(d, numValues, comps)
if not s then
return false, d.bad or "bad values"
end
vals = s
else
local nb = Reader.u8(d)
if d.bad then
return false, d.bad
end
if nb < 1 or nb > 4 then
return false, "bad value byte count"
end
if Reader.remaining(d) < nb * numValues then
return false, "truncated values"
end
vals = table.create(numValues, 0)
local b, p = d.b, d.pos
if nb == 4 then
for i = 1, numValues do
vals[i] = buffer.readu32(b, p)
p += 4
end
elseif nb == 1 then
for i = 1, numValues do
vals[i] = buffer.readu8(b, p)
p += 1
end
elseif nb == 2 then
for i = 1, numValues do
vals[i] = buffer.readu16(b, p)
p += 2
end
else
for i = 1, numValues do
vals[i] = buffer.readu16(b, p) + buffer.readu8(b, p + 2) * 65536
p += 3
end
end
d.pos = p
end
if not scheme or not scheme.tr.positive then
for i = 1, numValues do
vals[i] = zigzag(vals[i])
end
else
local i32 = Predict.i32
for i = 1, numValues do
vals[i] = i32(vals[i])
end
end
if scheme then
if not Predict.decodeData(scheme, d) then
return false, d.bad or "bad prediction data"
end
local ok, err = Predict.compute(scheme, vals, n, comps, points)
if not ok then
return false, err
end
end
a.portable = vals
a.numValues = n
return true, nil
end
local function decodeQuantInfo(d: D, a: Attr): boolean
local mins = table.create(a.comps, 0)
for c = 1, a.comps do
mins[c] = Reader.f32(d)
end
local range = Reader.f32(d)
local bits = Reader.u8(d)
if d.bad or bits < 1 or bits > 30 then
return false
end
a.quant = { min = mins, range = range, bits = bits }
return true
end
-- StoreValues: integer -> the data type; quantized -> f32; octahedral -> unit vectors
local function storeValues(a: Attr): (boolean, string?)
local src = a.portable :: { number }
local n = a.numValues
local fround = Predict.fround
if a.seqType == 1 then
local dt = a.dataType
local out = table.create(n * a.comps, 0)
for i = 1, n * a.comps do
local v = src[i]
if dt == 1 then
v = (v + 128) % 256 - 128
elseif dt == 2 or dt == 11 then
v %= 256
elseif dt == 3 then
v = (v + 32768) % 65536 - 32768
elseif dt == 4 then
v %= 65536
elseif dt == 6 then
v %= 4294967296
elseif dt ~= 5 then
return false, "unsupported: integer attribute of data type " .. dt
end
out[i] = v
end
a.values = out
elseif a.seqType == 2 then
local q = a.quant
if not q then
return false, "no quantization data"
end
local maxQ = 2 ^ q.bits - 1
local delta = fround(q.range / fround(maxQ))
local comps = a.comps
local mins = q.min
local out = table.create(n * comps, 0)
local k = 1
for _ = 1, n do
for c = 1, comps do
out[k] = fround(fround(fround(src[k]) * delta) + mins[c])
k += 1
end
end
a.values = out
elseif a.seqType == 3 then
local o = Predict.octahedron(a.octBits or 0)
if not o then
return false, "bad normal quantization"
end
local out = table.create(n * 3, 0)
for i = 0, n - 1 do
local x, y, z = Predict.octToVector(o, src[i * 2 + 1], src[i * 2 + 2])
out[i * 3 + 1], out[i * 3 + 2], out[i * 3 + 3] = x, y, z
end
a.values = out
end
return true, nil
end
-- decodes every attribute; returns them in attribute id order
function Attributes.decode(d: D, g: Geom): ({ Attr }?, string?)
local ver = d.ver
local numDecoders = Reader.u8(d)
if d.bad then
return nil, d.bad
end
local mesh = g.mesh
local decoders: { Decoder } = {}
for i = 0, numDecoders - 1 do
local dec: Decoder = { attrs = {}, traversal = nil, md = nil, points = nil }
if g.edgebreaker and mesh then
local attDataId = Reader.i8(d)
local decoderType = Reader.u8(d)
if d.bad then
return nil, d.bad
end
local ad = nil
if attDataId >= 0 then
ad = mesh.attrData[attDataId + 1]
if not ad or ad.decoderId >= 0 then
return nil, "bad attribute data id"
end
ad.decoderId = i
else
if mesh.posDecoderId >= 0 then
return nil, "two position decoders"
end
mesh.posDecoderId = i
end
local method = 0
if ver >= 0x0102 then
method = Reader.u8(d)
if d.bad or method >= 2 then
return nil, "bad traversal method"
end
end
local ct = mesh.ct :: Connectivity.CT
local enc
if decoderType == 0 then
if ad then
enc = ad.enc
ad.used = false
else
enc = mesh.posEnc :: Connectivity.Enc
end
dec.traversal = { ct = ct, enc = enc, method = method }
else
if method ~= 0 or not ad then
return nil, "bad corner attribute decoder"
end
local cad = ad :: Connectivity.AttrData
enc = cad.enc
dec.traversal = { ct = cad.ct :: Connectivity.CT, enc = enc, method = 0 }
end
-- prediction data: the attribute's own corner table when its seams are in use
local pct = if ad and ad.used then ad.ct :: Connectivity.CT else ct
dec.md = { ct = pct, e2c = enc.e2c, v2e = enc.v2e }
end
decoders[i + 1] = dec
end
-- the attribute descriptors
local all: { Attr } = {}
for _, dec in decoders do
local n = Reader.count(d, 0x0200)
if d.bad then
return nil, d.bad
end
if n == 0 or n > 5 * Reader.remaining(d) then
return nil, "bad attribute count"
end
for _ = 1, n do
local attType, dataType, comps, normalized = Reader.u8(d), Reader.u8(d), Reader.u8(d), Reader.u8(d)
if d.bad then
return nil, d.bad
end
if attType >= 9 or dataType == 0 or dataType >= 12 or comps == 0 then
return nil, "bad attribute descriptor"
end
local uniqueId = if ver < 0x0103 then Reader.u16(d) else Reader.varint(d)
local a: Attr = {
id = #all,
type = attType,
dataType = dataType,
comps = comps,
normalized = normalized > 0,
uniqueId = uniqueId,
seqType = 0,
map = nil,
numValues = 0,
}
table.insert(all, a)
table.insert(dec.attrs, a)
end
for _, a in (if g.kdTree then {} else dec.attrs) do
local t = Reader.u8(d)
if d.bad then
return nil, d.bad
end
if t > 3 then
return nil, "unknown attribute decoder " .. t
end
if (t == 2 or t == 3) and a.dataType ~= 9 then
return nil, "quantized attribute is not f32"
end
if t == 3 and a.comps ~= 3 then
return nil, "normal attribute without 3 components"
end
a.seqType = t
end
end
if d.bad then
return nil, d.bad
end
local function named(t: number): Attr?
for _, a in all do
if a.type == t then
return a
end
end
return nil
end
-- decode
for _, dec in decoders do
if g.kdTree then
local ok, err = KdTree.decode(d, dec.attrs, g.numPoints)
if not ok then
return nil, err
end
continue
end
local points: { number }
local trav = dec.traversal
if trav then
local faces = (mesh :: Connectivity.Mesh).faces
local p = Connectivity.traverse(trav.ct, faces, trav.enc, trav.method)
if not p then
return nil, "bad attribute traversal"
end
points = p
local numPoints = (mesh :: Connectivity.Mesh).numPoints
for _, a in dec.attrs do
local m = Connectivity.mapping(trav.ct, faces, trav.enc, numPoints)
if not m then
return nil, "bad attribute mapping"
end
a.map = m
end
else
points = table.create(g.numPoints, 0)
for i = 1, g.numPoints do
points[i] = i - 1
end
end
dec.points = points
-- portable values
for _, a in dec.attrs do
if a.seqType == 0 then
local stride = DT_LENGTH[a.dataType] * a.comps
local size = #points * stride
if Reader.remaining(d) < size then
return nil, "truncated attribute values"
end
local raw = buffer.create(size)
buffer.copy(raw, 0, d.b, d.pos, size)
d.pos += size
a.raw = raw
a.numValues = #points
continue
end
local psm = Reader.i8(d)
if d.bad then
return nil, d.bad
end
if psm < -2 or psm >= 7 then
return nil, "bad prediction scheme"
end
local scheme: Predict.Scheme? = nil
if psm ~= -2 then
local ptt = Reader.i8(d)
if d.bad then
return nil, d.bad
end
if ptt < -1 or ptt >= 4 then
return nil, "bad prediction transform"
end
if a.seqType == 3 then
if ptt == 2 or ptt == 3 then
scheme = Predict.new(psm, Predict.transform(ptt), dec.md)
end
elseif ptt == 1 then
scheme = Predict.new(psm, Predict.transform(1), dec.md)
end
end
if scheme and Predict.needsParent(scheme) then
local pos = named(0)
local getter = pos and parentGetter(ver, pos, scheme.method == 3)
if not getter then
return nil, "prediction needs the decoded positions"
end
scheme.parent = getter
end
if ver < 0x0200 then
if a.seqType == 2 and not decodeQuantInfo(d, a) then
return nil, d.bad or "bad quantization data"
elseif a.seqType == 3 then
a.octBits = Reader.u8(d)
end
end
local ok, err = decodeIntegerValues(d, a, points, scheme)
if not ok then
return nil, err
end
a.scheme = scheme
if ver < 0x0200 then
local ok2, err2 = storeValues(a)
if not ok2 then
return nil, err2
end
end
end
-- data needed by the transforms
if ver >= 0x0200 then
for _, a in dec.attrs do
if a.seqType == 2 then
if not decodeQuantInfo(d, a) then
return nil, d.bad or "bad quantization data"
end
elseif a.seqType == 3 then
a.octBits = Reader.u8(d)
end
end
if d.bad then
return nil, d.bad
end
for _, a in dec.attrs do
if a.seqType ~= 0 then
local ok, err = storeValues(a)
if not ok then
return nil, err
end
end
end
end
end
return all, nil
end
return Attributes
File diff suppressed because it is too large. Load diff
+156
View File
@@ -0,0 +1,156 @@
--!strict
-- codecs/model/Draco/Int64: the 64-bit integer arithmetic Draco's portable tex coord predictor relies on (int64 /
-- uint64 with wrap-around, truncating division, IntSqrt), on (hi, lo) pairs of 32-bit halves held in numbers (both
-- runtimes: no native 64-bit integers). Two's complement: hi >= 2^31 is negative when read as signed.
local Int64 = {}
local P32 = 4294967296
local P31 = 2147483648
function Int64.from(n: number): (number, number)
if n >= 0 then
return (n // P32) % P32, n % P32
end
local h, l = Int64.from(-n)
return Int64.neg(h, l)
end
function Int64.neg(h: number, l: number): (number, number)
if l == 0 then
return (P32 - h) % P32, 0
end
return P32 - 1 - h, P32 - l
end
function Int64.add(ah: number, al: number, bh: number, bl: number): (number, number)
local l = al + bl
local c = 0
if l >= P32 then
l -= P32
c = 1
end
return (ah + bh + c) % P32, l
end
function Int64.sub(ah: number, al: number, bh: number, bl: number): (number, number)
local nh, nl = Int64.neg(bh, bl)
return Int64.add(ah, al, nh, nl)
end
-- the product mod 2^64 (the same bits for signed and unsigned operands)
function Int64.mul(ah: number, al: number, bh: number, bl: number): (number, number)
local a0, a1, a2, a3 = al % 65536, al // 65536, ah % 65536, ah // 65536
local b0, b1, b2, b3 = bl % 65536, bl // 65536, bh % 65536, bh // 65536
local c0 = a0 * b0
local c1 = a1 * b0 + a0 * b1
local c2 = a2 * b0 + a1 * b1 + a0 * b2
local c3 = a3 * b0 + a2 * b1 + a1 * b2 + a0 * b3
local lo = c0 + (c1 % 65536) * 65536
local carry = lo // P32
lo %= P32
local hi = (c1 // 65536 + c2 + (c3 % 65536) * 65536 + carry) % P32
return hi, lo
end
function Int64.isNeg(h: number): boolean
return h >= P31
end
-- the signed value as a number (exact below 2^53 in magnitude)
function Int64.signed(h: number, l: number): number
if h >= P31 then
return (h - P32) * P32 + l
end
return h * P32 + l
end
-- the unsigned value as a number (rounded past 2^53)
function Int64.unsigned(h: number, l: number): number
return h * P32 + l
end
-- unsigned compare: -1, 0, 1
function Int64.ucmp(ah: number, al: number, bh: number, bl: number): number
if ah ~= bh then
return if ah < bh then -1 else 1
end
if al ~= bl then
return if al < bl then -1 else 1
end
return 0
end
-- signed compare: -1, 0, 1
function Int64.cmp(ah: number, al: number, bh: number, bl: number): number
local sa = if ah >= P31 then ah - P32 else ah
local sb = if bh >= P31 then bh - P32 else bh
if sa ~= sb then
return if sa < sb then -1 else 1
end
return Int64.ucmp(0, al, 0, bl)
end
-- unsigned division (b ~= 0): quotient, remainder
function Int64.udivmod(ah: number, al: number, bh: number, bl: number): (number, number, number, number)
if ah == 0 and bh == 0 then
return 0, al // bl, 0, al % bl
end
local qh, ql, rh, rl = 0, 0, 0, 0
for i = 63, 0, -1 do
-- r = r * 2 + bit i of a
local bit = if i >= 32 then (ah // 2 ^ (i - 32)) % 2 else (al // 2 ^ i) % 2
local over = rh >= P31
rh = (rh * 2 + rl // P31) % P32
rl = (rl * 2) % P32 + bit
if over or Int64.ucmp(rh, rl, bh, bl) >= 0 then
rh, rl = Int64.sub(rh, rl, bh, bl)
if i >= 32 then
qh += 2 ^ (i - 32)
else
ql += 2 ^ i
end
end
end
return qh, ql, rh, rl
end
-- signed division truncating toward zero (b ~= 0)
function Int64.div(ah: number, al: number, bh: number, bl: number): (number, number)
local na, nb = ah >= P31, bh >= P31
if na then
ah, al = Int64.neg(ah, al)
end
if nb then
bh, bl = Int64.neg(bh, bl)
end
local qh, ql = Int64.udivmod(ah, al, bh, bl)
if na ~= nb then
return Int64.neg(qh, ql)
end
return qh, ql
end
-- IntSqrt (draco/core/math_utils.h) on a uint64, step for step (wrap-around included)
function Int64.isqrt(h: number, l: number): (number, number)
if h == 0 and l == 0 then
return 0, 0
end
local acth, actl = h, l
local sh, sl = 0, 1
while Int64.ucmp(acth, actl, 0, 2) >= 0 do
sh, sl = Int64.add(sh, sl, sh, sl)
acth, actl = Int64.udivmod(acth, actl, 0, 4)
end
repeat
local qh, ql = Int64.udivmod(h, l, sh, sl)
local th, tl = Int64.add(sh, sl, qh, ql)
sh, sl = Int64.udivmod(th, tl, 0, 2)
if sh == 0 and sl == 0 then
return 0, 0
end
local pph, ppl = Int64.mul(sh, sl, sh, sl)
until Int64.ucmp(pph, ppl, h, l) <= 0
return sh, sl
end
return Int64
+363
View File
@@ -0,0 +1,363 @@
--!strict
-- codecs/model/Draco/KdTree: kd-tree coded point cloud attributes (bitstream 2.3): DynamicIntegerPointsKdTreeDecoder
-- at compression levels 0 - 6 (direct bits, rANS bits, folded 32-bit rANS numbers, selected axes) over all the
-- attributes of a decoder at once, then the signed offsets and the dequantization of f32 attributes. Ported from
-- Google's Draco 1.5.7 (compression/attributes/kd_tree_attributes_decoder.cc, compression/point_cloud/algorithms/
-- dynamic_integer_points_kd_tree_decoder.h, compression/bit_coders/{direct,folded_integer}_bit_decoder; Apache-2.0,
-- licenses/draco-LICENSE.txt). The pre-2.3 kd-tree layouts are not supported.
local Reader = require("@formats/codecs/model/Draco/Reader")
local Predict = require("@formats/codecs/model/Draco/Predict")
local KdTree = {}
type D = Reader.D
-- a bit source: next() -> 0 / 1, bits(n) -> value (MSB first); bits returns nil when a direct decoder runs out
type Src = { next: () -> number, bits: (n: number) -> number? }
local function direct(d: D): Src?
local size = Reader.u32(d)
if d.bad or size == 0 or size % 4 ~= 0 or size > Reader.remaining(d) then
Reader.fail(d, "kd-tree: bad direct bits")
return nil
end
local b, base, words = d.b, d.pos, size // 4
d.pos += size
local pos, used = 0, 0
return {
next = function(): number
if pos >= words then
return 0
end
local w = buffer.readu32(b, base + pos * 4)
local bit = bit32.extract(w, 31 - used)
used += 1
if used == 32 then
pos += 1
used = 0
end
return bit
end,
bits = function(n: number): number?
local remaining = 32 - used
if n <= remaining then
if pos >= words then
return nil
end
local w = buffer.readu32(b, base + pos * 4)
local v = bit32.extract(w, 32 - used - n, n)
used += n
if used == 32 then
pos += 1
used = 0
end
return v
end
if pos + 1 >= words then
return nil
end
local hiBits = bit32.extract(buffer.readu32(b, base + pos * 4), 0, remaining)
local lo = n - remaining
pos += 1
used = lo
local loBits = bit32.extract(buffer.readu32(b, base + pos * 4), 32 - lo, lo)
return hiBits * 2 ^ lo + loBits
end,
}
end
local function rans(d: D): Src?
local bd = Reader.bitDecoder(d)
if not bd then
return nil
end
local function nextBit(): number
return if Reader.bit(bd) then 1 else 0
end
return {
next = nextBit,
bits = function(n: number): number?
local v = 0
for _ = 1, n do
v = v * 2 + nextBit()
end
return v
end,
}
end
local function folded(d: D): Src?
local parts: { Reader.Bits } = {}
for i = 1, 32 do
local bd = Reader.bitDecoder(d)
if not bd then
return nil
end
parts[i] = bd
end
local main = Reader.bitDecoder(d)
if not main then
return nil
end
return {
next = function(): number
return if Reader.bit(main :: Reader.Bits) then 1 else 0
end,
bits = function(n: number): number?
local v = 0
for i = 1, n do
v = v * 2 + (if Reader.bit(parts[i]) then 1 else 0)
end
return v
end,
}
end
local function msb(n: number): number
local k = -1
while n >= 1 do
n = n // 2
k += 1
end
return k
end
-- DynamicIntegerPointsKdTreeDecoder::DecodePoints -> points (each a table of `dim` u32 values), or nil
local function decodePoints(d: D, level: number, dim: number, expected: number): ({ { number } }?, string?)
local bitLength = Reader.u32(d)
local numPoints = Reader.u32(d)
if d.bad then
return nil, d.bad
end
if bitLength > 32 then
return nil, "kd-tree: bad bit length"
end
if numPoints ~= expected then
return nil, "kd-tree: point count mismatch"
end
local out: { { number } } = {}
if numPoints == 0 then
return out, nil
end
local numbers = if level >= 4 then folded(d) elseif level >= 2 then rans(d) else direct(d)
local remainingBits = numbers and direct(d)
local axisDec = remainingBits and direct(d)
local half = axisDec and direct(d)
if not numbers or not remainingBits or not axisDec or not half then
return nil, d.bad or "kd-tree: bad bit decoders"
end
local selectAxis = level >= 6
local zero = table.create(dim, 0)
local baseStack: { { number } } = { table.clone(zero) }
local levelStack: { { number } } = { table.clone(zero) }
local stack = { { numPoints, 0, 0 } }
local decoded = 0
local p = table.create(dim, 0)
while #stack > 0 do
local st = stack[#stack]
stack[#stack] = nil
local n, lastAxis, sp = st[1], st[2], st[3]
local oldBase, levels = baseStack[sp + 1], levelStack[sp + 1]
if n > numPoints then
return nil, "kd-tree: bad point count"
end
local axis
if not selectAxis then
axis = if lastAxis == dim - 1 then 0 else lastAxis + 1
elseif n < 64 then
axis = 0
for a = 1, dim - 1 do
if levels[axis + 1] > levels[a + 1] then
axis = a
end
end
else
axis = (axisDec :: Src).bits(4) or 0
end
if axis >= dim then
return nil, "kd-tree: bad axis"
end
local lvl = levels[axis + 1]
if bitLength - lvl == 0 then
for _ = 1, n do
table.insert(out, table.clone(oldBase))
decoded += 1
end
if decoded > numPoints then
return nil, "kd-tree: too many points"
end
continue
end
if n <= 2 then
for _ = 1, n do
local a = axis
for _ = 1, dim do
local rb = bitLength - levels[a + 1]
local v = 0
if rb > 0 then
local got = remainingBits.bits(rb)
if got == nil then
return nil, "kd-tree: remaining bits run out"
end
v = got
end
p[a + 1] = bit32.bor(oldBase[a + 1], v)
a = if a == dim - 1 then 0 else a + 1
end
table.insert(out, table.clone(p))
decoded += 1
end
if decoded > numPoints then
return nil, "kd-tree: too many points"
end
continue
end
if decoded > numPoints then
return nil, "kd-tree: too many points"
end
local rbits = bitLength - lvl
local modifier = 2 ^ (rbits - 1)
local nb = table.clone(oldBase)
nb[axis + 1] = (nb[axis + 1] + modifier) % 4294967296
baseStack[sp + 2] = nb
local number = numbers.bits(msb(n)) or 0
local first = n // 2
if first < number then
return nil, "kd-tree: bad split"
end
first -= number
local second = n - first
if first ~= second and half.next() == 0 then
first, second = second, first
end
levels[axis + 1] += 1
levelStack[sp + 2] = table.clone(levels)
if sp + 2 > 32 * dim + 1 then
return nil, "kd-tree: too deep"
end
if first > 0 then
table.insert(stack, { first, axis, sp })
end
if second > 0 then
table.insert(stack, { second, axis, sp + 1 })
end
end
if decoded ~= expected then
return nil, "kd-tree: point count mismatch"
end
return out, nil
end
local SIGNED = { [1] = 8, [3] = 16, [5] = 32 }
-- decodes the attributes of one kd-tree decoder (Attributes.Attr records: dataType, comps; sets values / numValues)
function KdTree.decode(d: D, attrs: { any }, numPoints: number): (boolean, string?)
if d.ver < 0x0203 then
return false, "unsupported: kd-tree point clouds before bitstream 2.3"
end
local level = Reader.u8(d)
if d.bad then
return false, d.bad
end
if level > 6 then
return false, "kd-tree: bad compression level"
end
local dim = 0
for _, a in attrs do
local dt = a.dataType
if dt ~= 2 and dt ~= 4 and dt ~= 6 and dt ~= 1 and dt ~= 3 and dt ~= 5 and dt ~= 9 then
return false, "unsupported: kd-tree attribute of data type " .. dt
end
dim += a.comps
end
local points, err = decodePoints(d, level, dim, numPoints)
if not points then
return false, err
end
-- the portable values per attribute: the low bytes of each u32 for 8 / 16-bit types
local off = 0
for _, a in attrs do
local comps = a.comps
local vals = table.create(numPoints * comps, 0)
local mod = if a.dataType == 1 or a.dataType == 2 then 256 elseif a.dataType == 3 or a.dataType == 4 then 65536 else 4294967296
local raw = a.dataType == 9
for i, pt in points do
for c = 1, comps do
local v = pt[off + c]
vals[(i - 1) * comps + c] = if raw then v else v % mod
end
end
a.portable = vals
a.values = vals
a.numValues = numPoints
a.map = nil
off += comps
end
-- the data needed by the transforms: f32 quantization, then the signed minima
for _, a in attrs do
if a.dataType == 9 then
local mins = table.create(a.comps, 0)
for c = 1, a.comps do
mins[c] = Reader.f32(d)
end
local range = Reader.f32(d)
local bits = Reader.u8(d)
if d.bad or bits < 1 or bits > 30 then
return false, d.bad or "kd-tree: bad quantization"
end
a.quant = { min = mins, range = range, bits = bits }
end
end
for _, a in attrs do
if SIGNED[a.dataType] then
local mins = table.create(a.comps, 0)
for c = 1, a.comps do
local v = Reader.varint(d)
mins[c] = if v % 2 == 1 then -(v // 2) - 1 else v // 2
end
if d.bad then
return false, d.bad
end
a.signedMin = mins
end
end
-- back to the original values
local fround = Predict.fround
for _, a in attrs do
local vals = a.portable :: { number }
local comps = a.comps
if a.dataType == 9 then
local q = a.quant
local delta = fround(q.range / fround(2 ^ q.bits - 1))
local out = table.create(#vals, 0)
for i = 1, #vals do
local c = (i - 1) % comps + 1
local v = vals[i]
if v >= 2147483648 then
v -= 4294967296
end
out[i] = fround(fround(fround(v) * delta) + q.min[c])
end
a.values = out
elseif SIGNED[a.dataType] then
-- the C++ reads the stored (already narrowed) unsigned values back
local bits = SIGNED[a.dataType]
local mins = a.signedMin
local out = table.create(#vals, 0)
for i = 1, #vals do
local c = (i - 1) % comps + 1
local u = vals[i]
if u > 2147483647 then
return false, "kd-tree: signed value out of range"
end
local s = Predict.i32(u + mins[c])
local m = 2 ^ bits
out[i] = (s + m / 2) % m - m / 2
end
a.values = out
end
end
return true, nil
end
return KdTree
+977
View File
@@ -0,0 +1,977 @@
--!strict
-- codecs/model/Draco/Predict: Draco attribute prediction schemes and their decoding transforms. Schemes: difference
-- (delta), parallelogram, multi-parallelogram, constrained multi-parallelogram, tex coords (deprecated, float) and
-- portable tex coords, geometric normal; transforms: wrap, normal octahedron and canonicalized normal octahedron.
-- Integer semantics follow the C++ (int32 wrap, truncating division, exact 64-bit products where they can pass 2^53;
-- float math rounded to f32 at every step). Ported from Google's Draco 1.5.7
-- (compression/attributes/prediction_schemes/*, compression/attributes/normal_compression_utils.h; Apache-2.0,
-- licenses/draco-LICENSE.txt).
local Reader = require("@formats/codecs/model/Draco/Reader")
local Connectivity = require("@formats/codecs/model/Draco/Connectivity")
local Int64 = require("@formats/codecs/model/Draco/Int64")
local Predict = {}
type D = Reader.D
type CT = Connectivity.CT
local nextC, prevC = Connectivity.next, Connectivity.prev
local F32 = buffer.create(4)
local function fround(x: number): number
buffer.writef32(F32, 0, x)
return buffer.readf32(F32, 0)
end
Predict.fround = fround
local function i32(x: number): number
return (x + 2147483648) % 4294967296 - 2147483648
end
Predict.i32 = i32
local function tdiv(a: number, b: number): number
local q = a / b
return if q < 0 then math.ceil(q) else math.floor(q)
end
-- static_cast<int> of a float with the decoder's NaN / range guard (INT_MIN)
local function truncInt(x: number): number
if x ~= x or x > 2147483647 or x < -2147483648 then
return -2147483648
end
return tdiv(x, 1)
end
-- exact a * b = p + e (Dekker), for integers below 2^53
local SPLIT = 134217729
local function twoProd(a: number, b: number): (number, number)
local p = a * b
local t = SPLIT * a
local ah = t - (t - a)
local al = a - ah
t = SPLIT * b
local bh = t - (t - b)
local bl = b - bh
return p, ((ah * bh - p) + ah * bl + al * bh) + al * bl
end
-- trunc(a * b / c) for integers, exact while the true product is below 2^106 (c > 0)
local function mulDiv(a: number, b: number, c: number): number
local neg = (a < 0) ~= (b < 0)
a, b = math.abs(a), math.abs(b)
local p = a * b
local q
if p < 9007199254740992 then
q = p // c
else
q = math.floor(p / c)
local ph, pl = twoProd(a, b)
local qh, ql = twoProd(q, c)
local r = (ph - qh) + (pl - ql)
while r < 0 do
q -= 1
r += c
end
while r >= c do
q += 1
r -= c
end
end
return if neg then -q else q
end
-- floor(sqrt(a * b)) (IntSqrt of a 64-bit product), exact for a, b < 2^53
local function isqrtProd(a: number, b: number): number
if a == 0 or b == 0 then
return 0
end
local s = math.floor(math.sqrt(a) * math.sqrt(b))
local ph, pl = twoProd(a, b)
local function le(x: number): boolean -- x * x <= a * b
local xh, xl = twoProd(x, x)
if xh ~= ph then
return xh < ph
end
return xl <= pl
end
while s > 0 and not le(s) do
s -= 1
end
while le(s + 1) do
s += 1
end
return s
end
-- ------------------------------------------------------------------------------------------------ octahedron toolbox
export type Oct = { bits: number, maxQ: number, maxV: number, center: number, scale: number }
function Predict.octahedron(bits: number): Oct?
if bits < 2 or bits > 30 then
return nil
end
local maxQ = 2 ^ bits - 1
local maxV = maxQ - 1
return { bits = bits, maxQ = maxQ, maxV = maxV, center = maxV // 2, scale = fround(2 / fround(maxV)) }
end
local function canonicalizeCoords(o: Oct, s: number, t: number): (number, number)
local maxV, center = o.maxV, o.center
if (s == 0 and t == 0) or (s == 0 and t == maxV) or (s == maxV and t == 0) then
return maxV, maxV
elseif s == 0 and t > center then
t = center - (t - center)
elseif s == maxV and t < center then
t = center + (center - t)
elseif t == maxV and s < center then
s = center + (center - s)
elseif t == 0 and s > center then
s = center - (s - center)
end
return s, t
end
local function intVectorToOct(o: Oct, x: number, y: number, z: number): (number, number)
local s, t
local center, maxV = o.center, o.maxV
if x >= 0 then
s, t = y + center, z + center
else
s = if y < 0 then math.abs(z) else maxV - math.abs(z)
t = if z < 0 then math.abs(y) else maxV - math.abs(y)
end
return canonicalizeCoords(o, s, t)
end
local function canonicalizeVector(o: Oct, x: number, y: number, z: number): (number, number, number)
local sum = math.abs(x) + math.abs(y) + math.abs(z)
local center = o.center
if sum == 0 then
return center, y, z
end
x = mulDiv(x, center, sum)
y = mulDiv(y, center, sum)
if z >= 0 then
z = center - math.abs(x) - math.abs(y)
else
z = -(center - math.abs(x) - math.abs(y))
end
return x, y, z
end
local function invertDiamond(o: Oct, s: number, t: number): (number, number)
local signS, signT
if s >= 0 and t >= 0 then
signS, signT = 1, 1
elseif s <= 0 and t <= 0 then
signS, signT = -1, -1
else
signS = if s > 0 then 1 else -1
signT = if t > 0 then 1 else -1
end
local cs, ctv = signS * o.center, signT * o.center
local us, ut = s + s - cs, t + t - ctv
if signS * signT >= 0 then
us, ut = -ut, -us
else
us, ut = ut, us
end
return tdiv(i32(us + cs), 2), tdiv(i32(ut + ctv), 2)
end
local function modMax(o: Oct, x: number): number
if x > o.center then
return x - o.maxQ
elseif x < -o.center then
return x + o.maxQ
end
return x
end
-- quantized octahedral (s, t) -> unit vector, in f32 like the C++
function Predict.octToVector(o: Oct, s: number, t: number): (number, number, number)
local y = fround(fround(fround(s) * o.scale) - 1)
local z = fround(fround(fround(t) * o.scale) - 1)
local x = fround(fround(1 - math.abs(y)) - math.abs(z))
local xo = -x
if xo < 0 then
xo = 0
end
y = fround(if y < 0 then y + xo else y - xo)
z = fround(if z < 0 then z + xo else z - xo)
local n2 = fround(fround(fround(x * x) + fround(y * y)) + fround(z * z))
if n2 < 1e-6 then
return 0, 0, 0
end
local dd = fround(1 / fround(math.sqrt(n2)))
return fround(x * dd), fround(y * dd), fround(z * dd)
end
-- ------------------------------------------------------------------------------------------------ transforms
-- tr.apply(pred, data, off): data[off + 1 ..] holds the corrections and receives the original values
export type Transform = {
kind: number, -- 1 wrap, 2 octahedron, 3 octahedron canonicalized
positive: boolean, -- corrections are stored without the zig-zag sign mapping
min: number,
max: number,
maxDif: number,
oct: Oct?,
}
function Predict.transform(kind: number): Transform
return { kind = kind, positive = kind ~= 1, min = 0, max = 0, maxDif = 0, oct = nil }
end
function Predict.decodeTransform(tr: Transform, d: D): boolean
if tr.kind == 1 then
local mn, mx = Reader.i32(d), Reader.i32(d)
if d.bad or mn > mx then
return false
end
local dif = mx - mn
if dif >= 2147483647 then
return false
end
tr.min, tr.max, tr.maxDif = mn, mx, dif + 1
return true
end
local maxQ = Reader.i32(d)
if tr.kind == 3 or d.ver < 0x0202 then
Reader.i32(d) -- center value (unused)
end
if d.bad or maxQ <= 0 or maxQ % 2 == 0 then
return false
end
local bits = 0
while 2 ^ bits <= maxQ do
bits += 1
end
local o = Predict.octahedron(bits)
if not o then
return false
end
tr.oct = o
return true
end
-- the original values from a prediction (pred[1 .. comps]) and the corrections at data[off + 1 ..]
local function apply(tr: Transform, pred: { number }, data: { number }, off: number, comps: number)
if tr.kind == 1 then
local mn, mx, dif = tr.min, tr.max, tr.maxDif
for c = 1, comps do
local p = pred[c]
if p > mx then
p = mx
elseif p < mn then
p = mn
end
local v = i32(p + data[off + c])
if v > mx then
v -= dif
elseif v < mn then
v += dif
end
data[off + c] = v
end
return
end
local o = tr.oct :: Oct
local center = o.center
local ps, pt = pred[1] - center, pred[2] - center
local cs, ct = data[off + 1], data[off + 2]
local inDiamond = math.abs(ps) + math.abs(pt) <= center
if not inDiamond then
ps, pt = invertDiamond(o, ps, pt)
end
local os_: number, ot: number = 0, 0
if tr.kind == 2 then
os_ = modMax(o, i32(ps + cs))
ot = modMax(o, i32(pt + ct))
else
local bottomLeft = (ps == 0 and pt == 0) or (ps < 0 and pt <= 0)
local rot = 0
if ps == 0 then
rot = if pt == 0 then 0 elseif pt > 0 then 3 else 1
elseif ps > 0 then
rot = if pt >= 0 then 2 else 1
else
rot = if pt <= 0 then 0 else 3
end
local function rotate(x: number, y: number, r: number): (number, number)
if r == 1 then
return y, -x
elseif r == 2 then
return -x, -y
elseif r == 3 then
return -y, x
end
return x, y
end
if not bottomLeft then
ps, pt = rotate(ps, pt, rot)
end
os_ = modMax(o, i32(ps + cs))
ot = modMax(o, i32(pt + ct))
if not bottomLeft then
os_, ot = rotate(os_, ot, (4 - rot) % 4)
end
end
if not inDiamond then
os_, ot = invertDiamond(o, os_, ot)
end
data[off + 1] = os_ + center
data[off + 2] = ot + center
end
Predict.apply = apply
-- ------------------------------------------------------------------------------------------------ schemes
-- the mesh data of a scheme: corner table, value -> corner, vertex -> value
export type MeshData = { ct: CT, e2c: { number }, v2e: { number } }
-- the parent position attribute: pos(point) -> x, y, z (portable integers, or floats before 2.0)
export type Parent = (point: number) -> (number, number, number)
export type Scheme = {
method: number,
tr: Transform,
md: MeshData?,
parent: Parent?,
-- per-scheme decoded data
crease: { { boolean } }?,
orient: { boolean }?,
flips: Reader.Bits?,
areaMode: boolean,
ver: number,
}
local DELTA, PARALLELOGRAM, MULTI, TEXDEP, CONSTRAINED, TEXPORT, GEONORMAL = 0, 1, 2, 3, 4, 5, 6
Predict.GEOMETRIC_NORMAL = GEONORMAL
-- whether the scheme needs the position attribute
function Predict.needsParent(s: Scheme): boolean
return s.md ~= nil and (s.method == TEXDEP or s.method == TEXPORT or s.method == GEONORMAL)
end
-- CreatePredictionSchemeForDecoder: md = nil (no corner table: sequential connectivity, point clouds) gives delta
function Predict.new(method: number, tr: Transform, md: MeshData?): Scheme
local m = method
if not md then
m = DELTA
elseif tr.kind ~= 1 then
if m ~= GEONORMAL then
m = DELTA
md = nil
end
elseif m < PARALLELOGRAM or m > GEONORMAL then
m = DELTA
md = nil
end
return { method = m, tr = tr, md = if m == DELTA then nil else md, parent = nil, areaMode = true, ver = 0x0202 }
end
-- DecodePredictionData
function Predict.decodeData(s: Scheme, d: D): boolean
local m = s.method
s.ver = d.ver
if m == CONSTRAINED then
if d.ver < 0x0202 then
local mode = Reader.u8(d)
if d.bad or mode ~= 0 then
return false
end
end
local md = s.md :: MeshData
local crease = {}
for i = 1, 4 do
local n = Reader.varint(d)
if d.bad or n > md.ct.nf * 3 then
return false
end
local flags = table.create(n, false)
if n > 0 then
local bd = Reader.bitDecoder(d)
if not bd then
return false
end
for j = 1, n do
flags[j] = Reader.bit(bd)
end
end
crease[i] = flags
end
s.crease = crease
elseif m == TEXPORT then
local n = Reader.i32(d)
if d.bad or n < 0 or n > (s.md :: MeshData).ct.nf * 3 then
return false
end
local bd = Reader.bitDecoder(d)
if not bd then
return false
end
local orient = table.create(n, false)
local last = true
for i = 1, n do
if not Reader.bit(bd) then
last = not last
end
orient[i] = last
end
s.orient = orient
elseif m == TEXDEP then
local n = Reader.count(d, 0x0202)
local md = s.md :: MeshData
if d.bad or n == 0 or n > md.ct.nf * 3 then
return false
end
local bd = Reader.bitDecoder(d)
if not bd then
return false
end
local orient = table.create(n, false)
local last = true
for i = 1, n do
if not Reader.bit(bd) then
last = not last
end
orient[i] = last
end
s.orient = orient
elseif m == GEONORMAL then
if not Predict.decodeTransform(s.tr, d) then
return false
end
if d.ver < 0x0202 then
local mode = Reader.u8(d)
if d.bad or mode > 1 then
return false
end
s.areaMode = mode == 1
end
local bd = Reader.bitDecoder(d)
if not bd then
return false
end
s.flips = bd
return true
end
return Predict.decodeTransform(s.tr, d)
end
local function parallelogram(md: MeshData, p: number, ci: number, data: { number }, comps: number, out: { number }): boolean
local ct = md.ct
local oci = if ci < 0 then -1 else (ct.opp[ci + 1] or -1)
if oci == -1 then
return false
end
local c2v, v2e = ct.c2v, md.v2e
local vo, vn, vp = c2v[oci + 1] or -1, c2v[nextC(oci) + 1] or -1, c2v[prevC(oci) + 1] or -1
if vo < 0 or vn < 0 or vp < 0 then
return false
end
local eo, en, ep = v2e[vo + 1] or 0, v2e[vn + 1] or 0, v2e[vp + 1] or 0
if eo < p and en < p and ep < p then
for c = 1, comps do
out[c] = i32((data[en * comps + c] + data[ep * comps + c]) - data[eo * comps + c])
end
return true
end
return false
end
local function swingRight(ct: CT, c: number): number
local p = prevC(c)
local o = if p < 0 then -1 else (ct.opp[p + 1] or -1)
return prevC(o)
end
local function swingLeft(ct: CT, c: number): number
local n = nextC(c)
local o = if n < 0 then -1 else (ct.opp[n + 1] or -1)
return nextC(o)
end
-- the portable tex coord prediction when both neighbours are decoded (MeshPredictionSchemeTexCoordsPortablePredictor
-- ::ComputePredictedValue), in int64 / uint64 arithmetic like the C++. Returns "ok", u, v; "fallback" (degenerate
-- edge: predict from a neighbour); or "fail", message.
local function texPortable(nu: number, nv: number, pu: number, pv: number, tx: number, ty: number, tz: number, nx: number, ny: number, nz: number, qx: number, qy: number, qz: number, pop: () -> boolean?): (string, any, any)
local pnx, pny, pnz = qx - nx, qy - ny, qz - nz
local cnx, cny, cnz = tx - nx, ty - ny, tz - nz
local pnu, pnv = pu - nu, pv - nv
local B = 67108864 -- 2^26: below it every product and sum stays exact in a double
local small = math.abs(pnx) < B and math.abs(pny) < B and math.abs(pnz) < B and math.abs(cnx) < B and math.abs(cny) < B and math.abs(cnz) < B
if small then
local pn2 = pnx * pnx + pny * pny + pnz * pnz
local dot = pnx * cnx + pny * cny + pnz * cnz
if pn2 < B and math.abs(dot) < B and math.abs(nu) < B and math.abs(nv) < B and math.abs(pnu) < B and math.abs(pnv) < B then
if pn2 == 0 then
return "fallback"
end
local xu, xv = nu * pn2 + dot * pnu, nv * pn2 + dot * pnv
local dx = tx - (nx + tdiv(dot * pnx, pn2))
local dy = ty - (ny + tdiv(dot * pny, pn2))
local dz = tz - (nz + tdiv(dot * pnz, pn2))
local cx2 = dx * dx + dy * dy + dz * dz
if cx2 < B then
local norm = isqrtProd(cx2, pn2)
local cxu, cxv = pnv * norm, -pnu * norm
local o = pop()
if o == nil then
return "fail", "prediction: orientations run out"
end
if o then
return "ok", i32(tdiv(xu + cxu, pn2)), i32(tdiv(xv + cxv, pn2))
end
return "ok", i32(tdiv(xu - cxu, pn2)), i32(tdiv(xv - cxv, pn2))
end
end
end
-- the general case: int64
local from, add, sub, mul, div = Int64.from, Int64.add, Int64.sub, Int64.mul, Int64.div
local function dot3(ax: number, ay: number, az: number, bx: number, by: number, bz: number): (number, number)
local xh, xl = from(ax)
local yh, yl = from(ay)
local zh, zl = from(az)
local uh, ul = from(bx)
local vh, vl = from(by)
local wh, wl = from(bz)
local h1, l1 = mul(xh, xl, uh, ul)
local h2, l2 = mul(yh, yl, vh, vl)
local h3, l3 = mul(zh, zl, wh, wl)
h1, l1 = add(h1, l1, h2, l2)
return add(h1, l1, h3, l3)
end
local p2h, p2l = dot3(pnx, pny, pnz, pnx, pny, pnz)
if p2h == 0 and p2l == 0 then
return "fallback"
end
local dh, dl = dot3(pnx, pny, pnz, cnx, cny, cnz)
local MAXH, MAXL = 2147483647, 4294967295 -- INT64_MAX
local function absmax(...: number): (number, number)
local m = 0
for _, x in { ... } do
m = math.max(m, math.abs(x))
end
return from(m)
end
local function absI(h: number, l: number): (number, number)
if Int64.isNeg(h) then
return Int64.neg(h, l)
end
return h, l
end
-- the overflow guards (unsigned divisions as in the C++)
local nmh, nml = absmax(nu, nv)
local lh, ll = Int64.udivmod(MAXH, MAXL, p2h, p2l)
if Int64.ucmp(nmh, nml, lh, ll) > 0 then
return "fail", "prediction: tex coord overflow"
end
local adh, adl = absI(dh, dl)
local pmh, pml = absmax(pnu, pnv)
lh, ll = Int64.div(MAXH, MAXL, pmh, pml)
if Int64.cmp(adh, adl, lh, ll) > 0 then
return "fail", "prediction: tex coord overflow"
end
local nuh, nul = from(nu)
local nvh, nvl = from(nv)
local puh, pul = from(pnu)
local pvh, pvl = from(pnv)
local xuh, xul
do
local ah, al = mul(nuh, nul, p2h, p2l)
local bh, bl = mul(dh, dl, puh, pul)
xuh, xul = add(ah, al, bh, bl)
end
local xvh, xvl
do
local ah, al = mul(nvh, nvl, p2h, p2l)
local bh, bl = mul(dh, dl, pvh, pvl)
xvh, xvl = add(ah, al, bh, bl)
end
local pam = math.max(math.abs(pnx), math.abs(pny), math.abs(pnz))
local pah, pal = from(pam)
lh, ll = Int64.div(MAXH, MAXL, pah, pal)
if Int64.cmp(adh, adl, lh, ll) > 0 then
return "fail", "prediction: tex coord overflow"
end
-- x_pos = next + (dot * pn) / pn2; cx = tip - x_pos
local function proj(n: number, pc: number, t: number): (number, number)
local ph, pl = from(pc)
local mh, ml = mul(dh, dl, ph, pl)
local qh, ql = div(mh, ml, p2h, p2l)
local nh, nl = from(n)
local xh, xl = add(nh, nl, qh, ql)
local th, tl = from(t)
return sub(th, tl, xh, xl)
end
local ax, axl = proj(nx, pnx, tx)
local ay, ayl = proj(ny, pny, ty)
local az, azl = proj(nz, pnz, tz)
local c2h, c2l = mul(ax, axl, ax, axl)
do
local h, l = mul(ay, ayl, ay, ayl)
c2h, c2l = add(c2h, c2l, h, l)
h, l = mul(az, azl, az, azl)
c2h, c2l = add(c2h, c2l, h, l)
end
local prh, prl = mul(c2h, c2l, p2h, p2l)
local sh, sl = Int64.isqrt(prh, prl)
-- cx_uv = (pn_uv.v, -pn_uv.u) * norm
local cuh, cul = mul(pvh, pvl, sh, sl)
local nh, nl = Int64.neg(puh, pul)
local cvh, cvl = mul(nh, nl, sh, sl)
local o = pop()
if o == nil then
return "fail", "prediction: orientations run out"
end
local uh, ul, vh, vl
if o then
uh, ul = add(xuh, xul, cuh, cul)
vh, vl = add(xvh, xvl, cvh, cvl)
else
uh, ul = sub(xuh, xul, cuh, cul)
vh, vl = sub(xvh, xvl, cvh, cvl)
end
uh, ul = div(uh, ul, p2h, p2l)
vh, vl = div(vh, vl, p2h, p2l)
-- static_cast<int>: the low 32 bits
return "ok", i32(ul), i32(vl)
end
-- ComputeOriginalValues over data (corrections in, values out, in place); points = the entry -> point map
function Predict.compute(s: Scheme, data: { number }, numEntries: number, comps: number, points: { number }): (boolean, string?)
local tr = s.tr
local m = s.method
local pred = table.create(math.max(comps, 3), 0)
if m == DELTA then
if numEntries == 0 then
return true, nil
end
apply(tr, pred, data, 0, comps)
for e = 1, numEntries - 1 do
local off = e * comps
for c = 1, comps do
pred[c] = data[off - comps + c]
end
apply(tr, pred, data, off, comps)
end
return true, nil
end
local md = s.md :: MeshData
local e2c = md.e2c
local n = #e2c
if n ~= numEntries then
return false, "prediction: value count mismatch"
end
local ct = md.ct
local function previous(p: number)
local off = (p - 1) * comps
for c = 1, comps do
pred[c] = data[off + c]
end
end
if m == PARALLELOGRAM or m == MULTI or m == CONSTRAINED then
if n == 0 then
return true, nil
end
apply(tr, pred, data, 0, comps)
local para = table.create(comps, 0)
local preds: { { number } } = { table.create(comps, 0), table.create(comps, 0), table.create(comps, 0), table.create(comps, 0) }
local creasePos = { 0, 0, 0, 0 }
local nc = ct.nf * 3
for p = 1, n - 1 do
local start = e2c[p + 1]
local off = p * comps
if m == PARALLELOGRAM then
if parallelogram(md, p, start, data, comps, pred) then
apply(tr, pred, data, off, comps)
else
previous(p)
apply(tr, pred, data, off, comps)
end
elseif m == MULTI then
for c = 1, comps do
pred[c] = 0
end
local count = 0
local ci = start
local guard = 0
while ci ~= -1 do
if parallelogram(md, p, ci, data, comps, para) then
for c = 1, comps do
pred[c] = i32(pred[c] + para[c])
end
count += 1
end
ci = swingRight(ct, ci)
if ci == start then
ci = -1
end
guard += 1
if guard > nc then
return false, "prediction: bad vertex fan"
end
end
if count == 0 then
previous(p)
else
for c = 1, comps do
pred[c] = tdiv(pred[c], count)
end
end
apply(tr, pred, data, off, comps)
else
local count = 0
local ci = start
local first = true
local guard = 0
while ci ~= -1 do
if parallelogram(md, p, ci, data, comps, preds[count + 1]) then
count += 1
if count == 4 then
break
end
end
if first then
ci = swingLeft(ct, ci)
else
ci = swingRight(ct, ci)
end
if ci == start then
break
end
if ci == -1 and first then
first = false
ci = swingRight(ct, start)
end
guard += 1
if guard > nc then
return false, "prediction: bad vertex fan"
end
end
local used = 0
if count > 0 then
for c = 1, comps do
pred[c] = 0
end
local crease = s.crease :: { { boolean } }
for i = 1, count do
local pos = creasePos[count] + 1
creasePos[count] = pos
local flag = crease[count][pos]
if flag == nil then
return false, "prediction: crease flags run out"
end
if not flag then
used += 1
for c = 1, comps do
pred[c] = i32(pred[c] + preds[i][c])
end
end
end
end
if used == 0 then
previous(p)
else
for c = 1, comps do
pred[c] = tdiv(pred[c], used)
end
end
apply(tr, pred, data, off, comps)
end
end
return true, nil
end
local parent = s.parent
if not parent then
return false, "prediction: no position attribute"
end
local c2v, v2e = ct.c2v, md.v2e
local function entryOf(c: number): number
local v = if c < 0 then -1 else (c2v[c + 1] or -1)
if v < 0 then
return math.huge
end
return v2e[v + 1] or 0
end
local function posOf(e: number): (number, number, number)
local pt = points[e + 1]
if pt == nil then
return 0, 0, 0
end
return parent(pt)
end
if m == TEXPORT or m == TEXDEP then
if comps ~= 2 then
return false, "prediction: tex coords need 2 components"
end
local orient = s.orient :: { boolean }
local no = #orient
for p = 0, n - 1 do
local ci = e2c[p + 1]
local ne, pe = entryOf(nextC(ci)), entryOf(prevC(ci))
local done = false
if pe < p and ne < p then
local nu, nv = data[ne * 2 + 1], data[ne * 2 + 2]
local pu, pv = data[pe * 2 + 1], data[pe * 2 + 2]
if m == TEXPORT then
if pu == nu and pv == nv then
pred[1], pred[2] = pu, pv
done = true
else
local tx, ty, tz = posOf(p)
local nx, ny, nz = posOf(ne)
local qx, qy, qz = posOf(pe)
local status, u, v = texPortable(nu, nv, pu, pv, tx, ty, tz, nx, ny, nz, qx, qy, qz, function(): boolean?
if no == 0 then
return nil
end
local o = orient[no]
orient[no] = nil
no -= 1
return o
end)
if status == "fail" then
return false, u :: any
elseif status == "ok" then
pred[1], pred[2] = u, v
done = true
end
end
else
local fnu, fnv, fpu, fpv = fround(nu), fround(nv), fround(pu), fround(pv)
if fpu == fnu and fpv == fnv then
pred[1], pred[2] = truncInt(fpu), truncInt(fpv)
done = true
else
local tx: number, ty: number, tz: number = posOf(p)
local nx: number, ny: number, nz: number = posOf(ne)
local qx: number, qy: number, qz: number = posOf(pe)
tx, ty, tz, nx, ny, nz = fround(tx), fround(ty), fround(tz), fround(nx), fround(ny), fround(nz)
qx, qy, qz = fround(qx), fround(qy), fround(qz)
local pnx, pny, pnz = fround(qx - nx), fround(qy - ny), fround(qz - nz)
local cnx, cny, cnz = fround(tx - nx), fround(ty - ny), fround(tz - nz)
local pn2 = fround(fround(fround(pnx * pnx) + fround(pny * pny)) + fround(pnz * pnz))
local sv, tv = 0, 0
if s.ver < 0x0102 or pn2 > 0 then
local dot = fround(fround(fround(pnx * cnx) + fround(pny * cny)) + fround(pnz * cnz))
sv = fround(dot / pn2)
local ex, ey, ez = fround(cnx - fround(pnx * sv)), fround(cny - fround(pny * sv)), fround(cnz - fround(pnz * sv))
local e2 = fround(fround(fround(ex * ex) + fround(ey * ey)) + fround(ez * ez))
tv = fround(math.sqrt(fround(e2 / pn2)))
end
local pnu, pnv = fround(fpu - fnu), fround(fpv - fnv)
local pnus = fround(fround(pnu * sv) + fnu)
local pnut = fround(pnu * tv)
local pnvs = fround(fround(pnv * sv) + fnv)
local pnvt = fround(pnv * tv)
if no == 0 then
return false, "prediction: orientations run out"
end
local o = orient[no]
orient[no] = nil
no -= 1
local u: number, v: number = 0, 0
if o then
u = fround(pnus - pnvt)
v = fround(pnvs + pnut)
else
u = fround(pnus + pnvt)
v = fround(pnvs - pnut)
end
local function toInt(x: number): number
local r = math.floor(x + 0.5)
if r ~= r or r > 2147483647 or r < -2147483648 then
return -2147483648
end
return r
end
pred[1] = toInt(u)
pred[2] = toInt(v)
done = true
end
end
end
if not done then
local off = -1
if pe < p then
off = pe * 2
end
if ne < p then
off = ne * 2
elseif p > 0 then
off = (p - 1) * 2
else
off = -1
end
if off < 0 then
pred[1], pred[2] = 0, 0
else
pred[1], pred[2] = data[off + 1], data[off + 2]
end
end
apply(tr, pred, data, p * 2, 2)
end
return true, nil
end
-- geometric normal
local o = tr.oct
local flips = s.flips
if not o or not flips or comps ~= 2 then
return false, "prediction: bad geometric normal setup"
end
local nc = ct.nf * 3
for p = 0, n - 1 do
local ci = e2c[p + 1]
local cx, cy, cz = posOf(entryOf(ci))
local sx, sy, sz = 0, 0, 0
-- VertexCornersIterator from ci: swing left, then right from the start
local c = ci
local left = true
local guard = 0
while c ~= -1 do
local cn, cp
if s.areaMode then
cn, cp = nextC(c), prevC(c)
else
cn, cp = nextC(ci), prevC(ci)
end
local ax, ay, az = posOf(entryOf(cn))
local bx, by, bz = posOf(entryOf(cp))
ax, ay, az = ax - cx, ay - cy, az - cz
bx, by, bz = bx - cx, by - cy, bz - cz
sx += ay * bz - az * by
sy += az * bx - ax * bz
sz += ax * by - ay * bx
if left then
c = swingLeft(ct, c)
if c == -1 then
c = swingRight(ct, ci)
left = false
elseif c == ci then
c = -1
end
else
c = swingRight(ct, c)
end
guard += 1
if guard > nc then
return false, "prediction: bad vertex fan"
end
end
local upper = 2 ^ 29
local sum = math.abs(sx) + math.abs(sy) + math.abs(sz)
if sum > upper then
local q = sum // upper
sx, sy, sz = tdiv(sx, q), tdiv(sy, q), tdiv(sz, q)
end
sx, sy, sz = i32(sx), i32(sy), i32(sz)
sx, sy, sz = canonicalizeVector(o, sx, sy, sz)
if Reader.bit(flips) then
sx, sy, sz = -sx, -sy, -sz
end
pred[1], pred[2] = intVectorToOct(o, sx, sy, sz)
apply(tr, pred, data, p * 2, 2)
end
return true, nil
end
return Predict
+480
View File
@@ -0,0 +1,480 @@
--!strict
-- codecs/model/Draco/Reader: the Draco decoder buffer (little-endian fields, LEB128 varints, LSB-first bit runs) and
-- its entropy decoders: rANS symbol coding (tagged and raw schemes, DecodeSymbols) and the binary rANS / rABS bit
-- decoder. Ported from Google's Draco 1.5.7 (core/decoder_buffer, core/varint_decoding, compression/entropy/ans.h,
-- rans_symbol_decoder.h, symbol_decoding.cc, compression/bit_coders/rans_bit_decoder.cc; Apache-2.0,
-- licenses/draco-LICENSE.txt). Bitstream versions 1.0 - 2.2 (fixed-width counts before 2.0 / 2.2).
-- A failed read sets the sticky d.bad message and returns 0; callers check d.bad at their boundaries.
local Reader = {}
local readu8, readu16, readu32, readi32, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi32, buffer.readf32
local band, rshift = bit32.band, bit32.rshift
export type D = {
b: buffer,
pos: number, -- absolute offset in b
limit: number, -- absolute end
ver: number, -- major * 256 + minor
bad: string?,
bitMode: boolean,
bitStart: number, -- absolute byte where the bit run starts
bitOff: number, -- bits consumed
}
function Reader.new(b: buffer, pos: number, limit: number, ver: number): D
return { b = b, pos = pos, limit = limit, ver = ver, bad = nil, bitMode = false, bitStart = pos, bitOff = 0 }
end
-- a copy (C++ DecoderBuffer is copied by value: positions are independent afterwards)
function Reader.copy(d: D): D
return { b = d.b, pos = d.pos, limit = d.limit, ver = d.ver, bad = d.bad, bitMode = d.bitMode, bitStart = d.bitStart, bitOff = d.bitOff }
end
function Reader.fail(d: D, msg: string): number
if not d.bad then
d.bad = msg
end
return 0
end
function Reader.remaining(d: D): number
return d.limit - d.pos
end
function Reader.u8(d: D): number
local p = d.pos
if p + 1 > d.limit then
return Reader.fail(d, "truncated")
end
d.pos = p + 1
return readu8(d.b, p)
end
function Reader.i8(d: D): number
local v = Reader.u8(d)
return if v >= 128 then v - 256 else v
end
function Reader.u16(d: D): number
local p = d.pos
if p + 2 > d.limit then
return Reader.fail(d, "truncated")
end
d.pos = p + 2
return readu16(d.b, p)
end
function Reader.u32(d: D): number
local p = d.pos
if p + 4 > d.limit then
return Reader.fail(d, "truncated")
end
d.pos = p + 4
return readu32(d.b, p)
end
function Reader.i32(d: D): number
local p = d.pos
if p + 4 > d.limit then
return Reader.fail(d, "truncated")
end
d.pos = p + 4
return readi32(d.b, p)
end
-- u64 as a number (exact below 2^53; sizes beyond that fail the bounds checks anyway)
function Reader.u64(d: D): number
local p = d.pos
if p + 8 > d.limit then
return Reader.fail(d, "truncated")
end
d.pos = p + 8
return readu32(d.b, p) + readu32(d.b, p + 4) * 4294967296
end
function Reader.f32(d: D): number
local p = d.pos
if p + 4 > d.limit then
return Reader.fail(d, "truncated")
end
d.pos = p + 4
return readf32(d.b, p)
end
-- LEB128 (at most 5 bytes for 32-bit values, 10 for 64-bit); 32-bit values wrap like the C++ shifts
function Reader.varint(d: D, wide: boolean?): number
local maxBytes = if wide then 10 else 5
local v, mul = 0, 1
for _ = 1, maxBytes do
local p = d.pos
if p + 1 > d.limit then
return Reader.fail(d, "truncated varint")
end
local c = readu8(d.b, p)
d.pos = p + 1
v += band(c, 127) * mul
if c < 128 then
if not wide then
v %= 4294967296
end
return v
end
mul *= 128
end
return Reader.fail(d, "varint too long")
end
-- a count stored as u32 before `fixedBefore` (a version number) and as a varint from then on
function Reader.count(d: D, fixedBefore: number): number
if d.ver < fixedBefore then
return Reader.u32(d)
end
return Reader.varint(d)
end
-- ------------------------------------------------------------------------------------------------ bit runs
-- StartBitDecoding(decodeSize): an optional size (u64 before 2.2, varint64 after), then LSB-first bits up to the end
-- of the buffer; EndBitDecoding moves pos past the whole bytes consumed.
function Reader.startBits(d: D, decodeSize: boolean): number
local size = 0
if decodeSize then
if d.ver < 0x0202 then
size = Reader.u64(d)
else
size = Reader.varint(d, true)
end
end
d.bitMode = true
d.bitStart = d.pos
d.bitOff = 0
return size
end
function Reader.bits(d: D, n: number): number
if not d.bitMode then
return Reader.fail(d, "bit decoder not active")
end
if n > 32 then
return Reader.fail(d, "bit run over 32 bits")
end
local b, start, limit = d.b, d.bitStart, d.limit
local off = d.bitOff
local v, mul = 0, 1
for _ = 1, n do
local byte = start + rshift(off, 3)
if byte < limit then
if band(rshift(readu8(b, byte), band(off, 7)), 1) == 1 then
v += mul
end
off += 1
end
mul *= 2
end
d.bitOff = off
return v
end
function Reader.endBits(d: D)
d.bitMode = false
d.pos = d.bitStart + (d.bitOff + 7) // 8
end
-- ------------------------------------------------------------------------------------------------ rANS symbols
-- the precision for a symbol alphabet of `bitLength`-bit symbols: (3 * bits) / 2 clamped to 12..20
local function precisionBits(bitLength: number): number
local p = (3 * bitLength) // 2
return if p < 12 then 12 elseif p > 20 then 20 else p
end
export type Rans = {
b: buffer,
base: number, -- absolute start of the coded bytes
off: number, -- bytes left (read backwards from base + off)
state: number,
lBase: number,
precBits: number,
lut: { number }, -- rem + 1 -> symbol + 1
prob: { number },
cum: { number },
numSymbols: number,
}
-- RAnsSymbolDecoder::Create: the probability table
local function ransCreate(d: D, precBits: number): Rans?
local numSymbols = Reader.count(d, 0x0200)
if d.bad then
return nil
end
if numSymbols // 64 > Reader.remaining(d) then
Reader.fail(d, "rans: too many symbols")
return nil
end
local prec = 2 ^ precBits
local prob = table.create(numSymbols, 0)
local i = 0
while i < numSymbols do
local data = Reader.u8(d)
if d.bad then
return nil
end
local token = band(data, 3)
if token == 3 then
local offset = rshift(data, 2)
if i + offset >= numSymbols then
Reader.fail(d, "rans: bad zero run")
return nil
end
for j = 0, offset do
prob[i + j + 1] = 0
end
i += offset + 1
else
local p = rshift(data, 2)
for k = 1, token do
p += Reader.u8(d) * 2 ^ (8 * k - 2)
end
if d.bad then
return nil
end
prob[i + 1] = p
i += 1
end
end
local lut: { number } = {}
local cum = table.create(numSymbols, 0)
if numSymbols > 0 then
lut = table.create(prec, 0)
local c, act = 0, 0
for s = 1, numSymbols do
cum[s] = c
c += prob[s]
if c > prec then
Reader.fail(d, "rans: probabilities over the precision")
return nil
end
for j = act + 1, c do
lut[j] = s
end
act = c
end
if c ~= prec then
Reader.fail(d, "rans: probabilities do not sum to the precision")
return nil
end
end
return {
b = d.b,
base = 0,
off = 0,
state = 0,
lBase = prec * 4,
precBits = precBits,
lut = lut,
prob = prob,
cum = cum,
numSymbols = numSymbols,
}
end
-- read_init over [base, base + size): the final state is stored in the last 1-4 bytes
local function ansInit(b: buffer, base: number, size: number, lBase: number, allow4: boolean): (number?, number?)
if size < 1 then
return nil, nil
end
local x = rshift(readu8(b, base + size - 1), 6)
local off: number, state: number = 0, 0
if x == 0 then
off = size - 1
state = band(readu8(b, base + size - 1), 0x3F)
elseif x == 1 then
if size < 2 then
return nil, nil
end
off = size - 2
state = band(readu16(b, base + size - 2), 0x3FFF)
elseif x == 2 then
if size < 3 then
return nil, nil
end
off = size - 3
state = readu16(b, base + size - 3) + band(readu8(b, base + size - 1), 0x3F) * 65536
else
if not allow4 or size < 4 then
return nil, nil
end
off = size - 4
state = band(readu32(b, base + size - 4), 0x3FFFFFFF)
end
state += lBase
if state >= lBase * 256 then
return nil, nil
end
return off, state
end
-- RAnsSymbolDecoder::StartDecoding: the coded size, then the bytes
local function ransStart(d: D, r: Rans): boolean
local size
if d.ver < 0x0200 then
size = Reader.u64(d)
else
size = Reader.varint(d, true)
end
if d.bad then
return false
end
if size > Reader.remaining(d) then
Reader.fail(d, "rans: data past the end")
return false
end
local off, state = ansInit(d.b, d.pos, size, r.lBase, true)
if not off then
Reader.fail(d, "rans: bad initial state")
return false
end
r.base, r.off, r.state = d.pos, off, state :: number
d.pos += size
return true
end
-- decodes n symbols into out[first .. first + n - 1] (0-based symbol values)
local function ransRead(r: Rans, n: number, out: { number }, first: number)
local b, base, off, state = r.b, r.base, r.off, r.state
local lBase, bits = r.lBase, r.precBits
local mask = 2 ^ bits - 1
local lut, prob, cum = r.lut, r.prob, r.cum
for i = first, first + n - 1 do
while state < lBase and off > 0 do
off -= 1
state = state * 256 + readu8(b, base + off)
end
local quo, rem = rshift(state, bits), band(state, mask)
local s = lut[rem + 1]
state = quo * prob[s] + rem - cum[s]
out[i] = s - 1
end
r.off, r.state = off, state
end
local function decodeTagged(d: D, n: number, comps: number, out: { number }): boolean
local tag = ransCreate(d, precisionBits(5))
if not tag or not ransStart(d, tag) then
return false
end
if n > 0 and tag.numSymbols == 0 then
Reader.fail(d, "rans: no symbols")
return false
end
Reader.startBits(d, false)
local len = { 0 }
local k = 1
local i = 0
while i < n do
ransRead(tag, 1, len, 1)
local bitLength = len[1]
for _ = 1, comps do
if k > n then
break
end
out[k] = Reader.bits(d, bitLength)
k += 1
end
if d.bad then
return false
end
i += comps
end
Reader.endBits(d)
return true
end
local function decodeRaw(d: D, n: number, out: { number }): boolean
local maxBitLength = Reader.u8(d)
if d.bad then
return false
end
if maxBitLength < 1 or maxBitLength > 18 then
Reader.fail(d, "rans: bad symbol bit length")
return false
end
local r = ransCreate(d, precisionBits(maxBitLength))
if not r then
return false
end
if n > 0 and r.numSymbols == 0 then
Reader.fail(d, "rans: no symbols")
return false
end
if not ransStart(d, r) then
return false
end
ransRead(r, n, out, 1)
return true
end
-- DecodeSymbols(n, components) -> { u32 } (1-based) | nil (d.bad set)
function Reader.symbols(d: D, n: number, comps: number): { number }?
local out = table.create(n, 0)
if n == 0 then
return out
end
local scheme = Reader.u8(d)
if d.bad then
return nil
end
local ok
if scheme == 0 then
ok = decodeTagged(d, n, math.max(comps, 1), out)
elseif scheme == 1 then
ok = decodeRaw(d, n, out)
else
Reader.fail(d, "rans: unknown symbol coding scheme")
ok = false
end
return if ok then out else nil
end
-- ------------------------------------------------------------------------------------------------ binary rANS
export type Bits = { b: buffer, base: number, off: number, state: number, p0: number, p: number }
-- RAnsBitDecoder::StartDecoding: prob_zero, the size (u32 before 2.2), the bytes
function Reader.bitDecoder(d: D): Bits?
local p0 = Reader.u8(d)
local size = Reader.count(d, 0x0202)
if d.bad then
return nil
end
if size > Reader.remaining(d) then
Reader.fail(d, "rabs: data past the end")
return nil
end
local off, state = ansInit(d.b, d.pos, size, 4096, false)
if not off then
Reader.fail(d, "rabs: bad initial state")
return nil
end
local bd = { b = d.b, base = d.pos, off = off, state = state :: number, p0 = p0, p = 256 - p0 }
d.pos += size
return bd
end
-- rabs_desc_read: one bit (true / false)
function Reader.bit(bd: Bits): boolean
local state, off = bd.state, bd.off
if state < 4096 and off > 0 then
off -= 1
state = state * 256 + readu8(bd.b, bd.base + off)
bd.off = off
end
local quot, rem = rshift(state, 8), band(state, 255)
local p = bd.p
local xn = quot * p
if rem < p then
bd.state = xn + rem
return true
end
bd.state = state - xn - p
return false
end
return Reader
+353
View File
@@ -0,0 +1,353 @@
--!strict
-- codecs/model/Draco: Google Draco geometry decompression (.drc; glTF KHR_draco_mesh_compression; Roblox mesh v6 / v7).
-- A codec, not a format: model/gltf (and any format carrying Draco data) calls it on a byte range.
-- Ported from Google's Draco 1.5.7 (Apache-2.0, licenses/draco-LICENSE.txt): the decoder only, bitstream versions
-- 1.0 - 2.2 for meshes (sequential and Edgebreaker connectivity: standard, predictive and valence traversals; topology
-- splits, attribute seams), sequential point clouds and kd-tree point clouds (2.3); attribute decoders generic /
-- integer / quantization / octahedral normals; prediction schemes difference, parallelogram, multi-parallelogram,
-- constrained multi-parallelogram, tex coords (deprecated and portable), geometric normal, with the wrap and normal
-- octahedron transforms; metadata. Values match draco_decoder bit for bit (f32 rounding at every step of the
-- dequantization).
-- Not supported: the pre-2.3 kd-tree point cloud layouts (Err.UNSUPPORTED).
--
-- local Draco = require("@formats/codecs/model/Draco")
-- local g, err = Draco.decode(buf, off?, len?, opts?) -- buffer | string
-- g.kind ("mesh" | "points"), g.numPoints, g.numFaces, g.indices (u32 x 3 per face, or nil for points)
-- g.attributes[i] = { name = "POSITION" | "NORMAL" | "COLOR" | "TEX_COORD" | "GENERIC" | ..., uniqueId,
-- components, type = "f32" | "u8" | "i16" | ..., normalized, data (per point, packed) }
-- Draco.attribute(g, uniqueId) -> the attribute with that unique id (glTF's attribute map)
-- g.metadata = { entries = { [name] = buffer }, children = { [name] = Metadata }, attributes = { [uniqueId] = Metadata } }
--
-- Options: maxPoints (default 2^24), maxFaces (default 2^24): larger geometry returns Err.LIMIT.
-- Never throws: bad data returns nil, Err (TRUNCATED / CORRUPT / UNSUPPORTED / LIMIT).
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Reader = require("@formats/codecs/model/Draco/Reader")
local Connectivity = require("@formats/codecs/model/Draco/Connectivity")
local Attributes = require("@formats/codecs/model/Draco/Attributes")
local Draco = {}
local NAMES = { [0] = "POSITION", "NORMAL", "COLOR", "TEX_COORD", "GENERIC", "TANGENT", "MATERIAL", "JOINTS", "WEIGHTS" }
local TYPES = { "i8", "u8", "i16", "u16", "i32", "u32", "i64", "u64", "f32", "f64", "bool" }
Draco.ATTRIBUTE_NAMES = NAMES
Draco.DATA_TYPES = TYPES
export type Attribute = {
name: string,
typeId: number,
uniqueId: number,
components: number,
type: string,
normalized: boolean,
data: buffer,
}
export type Metadata = { entries: { [string]: buffer }, children: { [string]: Metadata }, attributes: { [number]: Metadata }? }
export type Geometry = {
kind: "mesh" | "points",
version: string,
method: string,
numPoints: number,
numFaces: number,
indices: buffer?,
attributes: { Attribute },
metadata: Metadata?,
}
export type Header = { major: number, minor: number, kind: "mesh" | "points", method: number, flags: number }
-- sniff(buf, off?) -> whether the bytes start with "DRACO"
function Draco.sniff(buf: buffer, off: number?): boolean
local o = off or 0
return buffer.len(buf) >= o + 5 and buffer.readstring(buf, o, 5) == "DRACO"
end
local function header(d: Reader.D): (Header?, string?)
if Reader.remaining(d) < 11 then
return nil, "truncated header"
end
if buffer.readstring(d.b, d.pos, 5) ~= "DRACO" then
return nil, "not Draco data"
end
d.pos += 5
local major, minor, kind, method = Reader.u8(d), Reader.u8(d), Reader.u8(d), Reader.u8(d)
local flags = Reader.u16(d)
if kind > 1 then
return nil, "unsupported: geometry type " .. kind
end
return { major = major, minor = minor, kind = if kind == 0 then "points" else "mesh", method = method, flags = flags }, nil
end
-- info(buf, off?, len?) -> the header
function Draco.info(src: buffer | string, off: number?, len: number?): (Header?, Err.Err?)
local buf, o, l, aerr = Bytes.span("draco", src, off, len)
if not buf then
return nil, aerr
end
local d = Reader.new(buf, o, o + l, 0)
local h, err = header(d)
if not h then
return nil, Err.from(err, 0)
end
return h, nil
end
local function metadataElement(d: Reader.D, depth: number): Metadata?
if depth > 1000 then
return nil
end
local m: Metadata = { entries = {}, children = {} }
local n = Reader.varint(d)
if d.bad or n > Reader.remaining(d) then
return nil
end
for _ = 1, n do
local nameLen = Reader.u8(d)
if d.bad or Reader.remaining(d) < nameLen then
return nil
end
local name = buffer.readstring(d.b, d.pos, nameLen)
d.pos += nameLen
local size = Reader.varint(d)
if d.bad or size == 0 or size > Reader.remaining(d) then
return nil
end
local v = buffer.create(size)
buffer.copy(v, 0, d.b, d.pos, size)
d.pos += size
m.entries[name] = v
end
local subs = Reader.varint(d)
if d.bad or subs > Reader.remaining(d) then
return nil
end
for _ = 1, subs do
local nameLen = Reader.u8(d)
if d.bad or Reader.remaining(d) < nameLen then
return nil
end
local name = buffer.readstring(d.b, d.pos, nameLen)
d.pos += nameLen
local child = metadataElement(d, depth + 1)
if not child then
return nil
end
m.children[name] = child
end
return m
end
local function metadata(d: Reader.D): Metadata?
local n = Reader.varint(d)
if d.bad or n > Reader.remaining(d) then
return nil
end
local atts: { [number]: Metadata } = {}
for _ = 1, n do
local id = Reader.varint(d)
local m = metadataElement(d, 0)
if not m then
return nil
end
atts[id] = m
end
local m = metadataElement(d, 0)
if not m then
return nil
end
m.attributes = atts
return m
end
local WRITE: { [number]: (buffer, number, number) -> () } = {
[1] = buffer.writei8,
[2] = buffer.writeu8,
[3] = buffer.writei16,
[4] = buffer.writeu16,
[5] = buffer.writei32,
[6] = buffer.writeu32,
[9] = buffer.writef32,
[11] = buffer.writeu8,
}
-- per point output buffer of an attribute
local function expand(a: Attributes.Attr, numPoints: number): (buffer?, string?)
local size = Attributes.DT_LENGTH[a.dataType]
local comps = a.comps
local stride = size * comps
local out = buffer.create(numPoints * stride)
local map = a.map
local n = a.numValues
if a.raw then
local raw = a.raw :: buffer
for p = 0, numPoints - 1 do
local e = if map then map[p + 1] else p
if e >= n then
return nil, "attribute value out of range"
end
buffer.copy(out, p * stride, raw, e * stride, stride)
end
return out, nil
end
local vals = a.values :: { number }
local w = WRITE[a.dataType]
if not w then
return nil, "unsupported: data type " .. a.dataType
end
for p = 0, numPoints - 1 do
local e = if map then map[p + 1] else p
if e >= n then
return nil, "attribute value out of range"
end
local o = p * stride
local k = e * comps
for c = 1, comps do
w(out, o, vals[k + c])
o += size
end
end
return out, nil
end
local function decode(buf: buffer, o: number, l: number, opts: any): (Geometry?, string?, string?)
local d = Reader.new(buf, o, o + l, 0)
local h, herr = header(d)
if not h then
return nil, herr, nil
end
local ver = h.major * 256 + h.minor
local maxVer = if h.kind == "points" then 0x0203 else 0x0202
if h.major < 1 or ver > maxVer then
return nil, string.format("unsupported: bitstream version %d.%d", h.major, h.minor), nil
end
d.ver = ver
local maxPoints = (opts and opts.maxPoints) or 2 ^ 24
local maxFaces = (opts and opts.maxFaces) or 2 ^ 24
local meta: Metadata? = nil
if ver >= 0x0103 and bit32.band(h.flags, 0x8000) ~= 0 then
meta = metadata(d)
if not meta then
return nil, d.bad or "bad metadata", nil
end
end
local mesh: Connectivity.Mesh? = nil
local numPoints = 0
local method
if h.kind == "mesh" then
if h.method == 0 then
method = "sequential"
local m, err = Connectivity.sequential(d)
if not m then
return nil, err, nil
end
mesh = m
elseif h.method == 1 then
method = "edgebreaker"
local kind = Reader.u8(d)
if d.bad then
return nil, d.bad, nil
end
if kind > 2 then
return nil, "unknown edgebreaker traversal " .. kind, nil
end
local m, err = Connectivity.edgebreaker(d, kind)
if not m then
return nil, err, nil
end
mesh = m
else
return nil, "unsupported: mesh encoding method " .. h.method, nil
end
local m = mesh :: Connectivity.Mesh
if m.numFaces > maxFaces then
return nil, "too many faces", "limit"
end
numPoints = m.numPoints
else
if h.method > 1 then
return nil, "unsupported: point cloud encoding method " .. h.method, nil
end
method = if h.method == 1 then "kdtree" else "sequential"
numPoints = Reader.i32(d)
if d.bad then
return nil, d.bad, nil
end
if numPoints < 0 then
return nil, "bad point count", nil
end
end
if numPoints > maxPoints then
return nil, "too many points", "limit"
end
local attrs, aerr = Attributes.decode(d, { numPoints = numPoints, mesh = mesh, edgebreaker = method == "edgebreaker", kdTree = method == "kdtree" })
if not attrs then
return nil, aerr, nil
end
local g: Geometry = {
kind = h.kind,
version = h.major .. "." .. h.minor,
method = method,
numPoints = numPoints,
numFaces = 0,
indices = nil,
attributes = {},
metadata = meta,
}
if mesh then
local nf = mesh.numFaces
local idx = buffer.create(nf * 12)
local faces = mesh.faces
for i = 1, nf * 3 do
local v = faces[i]
if v < 0 or v >= numPoints then
return nil, "face index out of range", nil
end
buffer.writeu32(idx, (i - 1) * 4, v)
end
g.numFaces = nf
g.indices = idx
end
for _, a in attrs do
local data, err = expand(a, numPoints)
if not data then
return nil, err, nil
end
table.insert(g.attributes, {
name = NAMES[a.type] or "GENERIC",
typeId = a.type,
uniqueId = a.uniqueId,
components = a.comps,
type = TYPES[a.dataType],
normalized = a.normalized,
data = data,
})
end
return g, nil, nil
end
-- decode(src, off?, len?, opts?) -> Geometry | nil, Err
function Draco.decode(src: buffer | string, off: number?, len: number?, opts: any?): (Geometry?, Err.Err?)
local buf, o, l, aerr = Bytes.span("draco", src, off, len)
if not buf then
return nil, aerr
end
local ok, g, msg, kind = pcall(decode, buf, o, l, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "draco: internal error: " .. tostring(g))
end
if not g then
return nil, Err.from("draco: " .. tostring(msg), nil, kind or (if string.find(tostring(msg), "^unsupported") then "unsupported" elseif string.find(tostring(msg), "truncated") then "truncated" else nil))
end
return g, nil
end
-- attribute(g, uniqueId) -> the attribute with that unique id
function Draco.attribute(g: Geometry, uniqueId: number): Attribute?
for _, a in g.attributes do
if a.uniqueId == uniqueId then
return a
end
end
return nil
end
return Draco
+223
View File
@@ -0,0 +1,223 @@
--!strict
-- codecs/model/Rig: the Scene mapping shared by game model formats (MD2 / MD3 / MDL / MD5 / SMD / ...), so each
-- format only parses its file: vertex-animation frames as morph targets plus "weights" animations, joint hierarchies
-- as Scene nodes plus a Skin (inverse bind matrices), per-vertex joint influences as JOINTS_0 / WEIGHTS_0, and
-- keyframed joint TRS tracks as animation channels. New in formats-luau.
--
-- Rig.morph(prim, frames) -- frames[k] = f32 x3 positions: targets[k] = frame k - base
-- Rig.morphAnimation(scene, node, #frames, { { name = "run", first = 41, last = 46, fps = 10 } }, "LINEAR")
-- local nodes, skin = Rig.skeleton(scene, joints, "world") -- joints = { { name, parent (0 = root), t, r, s? } }
-- prim.attributes.JOINTS_0, prim.attributes.WEIGHTS_0 = Rig.influences(lists) -- lists[v] = { j1, w1, j2, w2, ... }
-- Rig.animation(scene, "idle", nodes, times, tracks) -- tracks[j] = { translation = {...}, rotation = {...} }
--
-- Frames, joints and tracks come from parsed files: the helpers check every count they rely on and never throw.
local Types = require("@formats/Types")
local Mat4 = require("@formats/codecs/model/Mat4")
local Rig = {}
local Scene = Types.Scene
local readf32, writef32, writeu16 = buffer.readf32, buffer.writef32, buffer.writeu16
export type Joint = {
name: string?,
parent: number, -- 1-based index into the joint list, 0 for a root (parents come before their children)
translation: { number },
rotation: { number }, -- quaternion x, y, z, w
scale: { number }?,
}
export type Range = { name: string?, first: number, last: number, fps: number? } -- frames first..last (1-based)
export type Track = { translation: { number }?, rotation: { number }?, scale: { number }? } -- flat, one key per time
-- ------------------------------------------------------------------------------------------------ morph targets
-- morph(prim, frames, normals?, base?) -> (): prim.targets[k] = { POSITION = frames[k] - base positions } (and NORMAL
-- deltas when normals[k] is given), base = prim.attributes.POSITION (and NORMAL). Every frame buffer must hold as
-- many f32 x3 as the base; shorter ones are skipped (false is returned).
function Rig.morph(prim: Types.Primitive, frames: { buffer }, normals: { buffer }?): boolean
local pos = prim.attributes.POSITION
if not pos or pos.type ~= "f32" or pos.components ~= 3 then
return false
end
local nrm = prim.attributes.NORMAL
local n = pos.count * 3
local targets: { { [string]: Types.Accessor } } = {}
local ok = true
for k, f in frames do
if buffer.len(f) < n * 4 then
ok = false
break
end
local t: { [string]: Types.Accessor } = {}
local d = buffer.create(n * 4)
local base = pos.data
for i = 0, n - 1 do
writef32(d, i * 4, readf32(f, i * 4) - readf32(base, i * 4))
end
t.POSITION = Scene.accessor(d, "f32", 3, pos.count)
local fn = normals and normals[k]
if nrm and fn and nrm.type == "f32" and buffer.len(fn) >= n * 4 then
local dn = buffer.create(n * 4)
for i = 0, n - 1 do
writef32(dn, i * 4, readf32(fn, i * 4) - readf32(nrm.data, i * 4))
end
t.NORMAL = Scene.accessor(dn, "f32", 3, pos.count)
end
targets[k] = t
end
if ok then
prim.targets = targets
end
return ok
end
-- morphAnimation(scene, node, targets, ranges, interpolation?) -> (): one animation per range, a "weights" channel on
-- scene.nodes[node] whose key k (at (k - first) / fps seconds) sets target k to 1 and the others to 0 (LINEAR
-- blends neighbouring frames, as the games do; default "LINEAR"). Ranges out of 1..targets are clamped / skipped.
function Rig.morphAnimation(scene: Types.Scene, node: number, targets: number, ranges: { Range }, interpolation: string?)
for _, rg in ranges do
local first, last = math.max(1, math.floor(rg.first)), math.min(targets, math.floor(rg.last))
if last >= first then
local keys = last - first + 1
local fps = if rg.fps and rg.fps > 0 then rg.fps else 10
local times = buffer.create(keys * 4)
local weights = buffer.create(keys * targets * 4)
for k = 0, keys - 1 do
writef32(times, k * 4, k / fps)
writef32(weights, (k * targets + first - 1 + k) * 4, 1)
end
table.insert(scene.animations, {
name = rg.name,
channels = {
{
node = node,
path = "weights" :: any,
input = Scene.accessor(times, "f32", 1, keys),
output = Scene.accessor(weights, "f32", 1, keys * targets),
interpolation = (if interpolation == "STEP" then "STEP" else "LINEAR") :: any,
},
},
})
end
end
end
-- ------------------------------------------------------------------------------------------------ skeletons
local function trs(j: Joint): { number }
return Mat4.compose(j.translation, j.rotation, j.scale)
end
-- skeleton(scene, joints, space, root?) -> (joint node indices, skin index): one node per joint (TRS relative to its
-- parent), parented as listed, roots added to scene.roots (or as children of node `root`); a Skin with the inverse
-- bind matrices. space "local": joint TRS are relative to the parent (SMD, MDL); "world": in model space (MD5's
-- bind pose), converted to local here. A parent index that does not come earlier makes the joint a root.
function Rig.skeleton(scene: Types.Scene, joints: { Joint }, space: "local" | "world", root: number?): ({ number }, number)
local n = #joints
local world: { { number } } = {}
local nodes: { number } = {}
for i, j in joints do
local p = if j.parent >= 1 and j.parent < i then j.parent else 0
local m = trs(j)
local lt, lr, ls = j.translation, j.rotation, j.scale
if space == "world" then
world[i] = m
if p > 0 then
local inv = Mat4.inverse(world[p])
if inv then
local t, r, s = Mat4.decompose(Mat4.mul(inv, m))
lt, lr, ls = t, r, s
end
end
else
world[i] = if p > 0 then Mat4.mul(world[p], m) else m
end
local node: Types.Node = { name = j.name, children = {}, translation = table.clone(lt), rotation = table.clone(lr), scale = if ls then table.clone(ls) else nil }
table.insert(scene.nodes, node)
local idx = #scene.nodes
nodes[i] = idx
if p > 0 then
table.insert(scene.nodes[nodes[p]].children, idx)
elseif root and scene.nodes[root] then
table.insert(scene.nodes[root].children, idx)
else
table.insert(scene.roots, idx)
end
end
local ibm = buffer.create(n * 64)
for i = 1, n do
local inv = Mat4.inverseFull(world[i]) or Mat4.identity()
for k = 1, 16 do
writef32(ibm, ((i - 1) * 16 + k - 1) * 4, inv[k])
end
end
local acc = Scene.accessor(ibm, "f32", 16, n)
acc.matrix = true
table.insert(scene.skins, { joints = nodes, inverseBindMatrices = acc, skeleton = if n > 0 then nodes[1] else nil })
return nodes, #scene.skins
end
-- influences(lists) -> JOINTS_0 (u16 x4), WEIGHTS_0 (f32 x4): lists[v] = { joint, weight, joint, weight, ... } with
-- 0-based joint indices (into the skin's joints); the four largest weights are kept and normalised to sum 1.
function Rig.influences(lists: { { number } }): (Types.Accessor, Types.Accessor)
local n = #lists
local jb, wb = buffer.create(n * 8), buffer.create(n * 16)
for v, l in lists do
local pairs_: { { number } } = {}
for k = 1, #l - 1, 2 do
if l[k + 1] > 0 then
table.insert(pairs_, { l[k], l[k + 1] })
end
end
table.sort(pairs_, function(a: { number }, b: { number }): boolean
return a[2] > b[2]
end)
local sum = 0
for k = 1, math.min(4, #pairs_) do
sum += pairs_[k][2]
end
for k = 1, math.min(4, #pairs_) do
writeu16(jb, ((v - 1) * 4 + k - 1) * 2, math.clamp(pairs_[k][1], 0, 65535))
writef32(wb, ((v - 1) * 4 + k - 1) * 4, pairs_[k][2] / sum)
end
end
return Scene.accessor(jb, "u16", 4, n), Scene.accessor(wb, "f32", 4, n)
end
-- ------------------------------------------------------------------------------------------------ animations
local function floats(t: { number }, count: number, comps: number): Types.Accessor?
if #t < count * comps then
return nil
end
local b = buffer.create(count * comps * 4)
for i = 1, count * comps do
writef32(b, (i - 1) * 4, t[i])
end
return Scene.accessor(b, "f32", comps, count)
end
-- animation(scene, name, nodes, times, tracks, interpolation?) -> the animation index: tracks[j] (j = index into
-- nodes) holds flat translation (x3) / rotation (quaternion x4) / scale (x3) keys, one per time (seconds); tracks
-- with too few keys are skipped. Default interpolation "LINEAR".
function Rig.animation(scene: Types.Scene, name: string?, nodes: { number }, times: { number }, tracks: { [number]: Track }, interpolation: string?): number
local count = #times
local input = floats(times, count, 1)
local channels: { Types.Channel } = {}
local interp: any = if interpolation == "STEP" then "STEP" else "LINEAR"
if input then
for j, tr in tracks do
local node = nodes[j]
if node then
for _, path in { "translation", "rotation", "scale" } do
local keys = (tr :: any)[path]
local acc = keys and floats(keys, count, if path == "rotation" then 4 else 3)
if acc then
table.insert(channels, { node = node, path = path :: any, input = input, output = acc, interpolation = interp })
end
end
end
end
end
table.insert(scene.animations, { name = name, channels = channels })
return #scene.animations
end
return Rig
+173
View File
@@ -0,0 +1,173 @@
--!strict
-- codecs/model/Sampler: evaluates Scene animation channels at any time (STEP, LINEAR with quaternion slerp for
-- rotations, CUBICSPLINE Hermite splines as glTF 2.0 defines them; times before the first / after the last key hold
-- the end values), and the node poses of an animation at a time, for writers of formats that store sampled frames
-- (IQM, MD5, BVH, ...). New in formats-luau.
--
-- local sample = Sampler.channel(ch) -- nil for an unreadable channel
-- local v = sample(0.5) -- { x, y, z } / { x, y, z, w } / the morph weights
-- local times = Sampler.times(anim) -- every key time of the animation, sorted, unique
-- local pose = Sampler.pose(scene, anim, 0.5) -- pose[node] = { translation?, rotation?, scale?, weights? }
--
-- Never throws on bad data: unreadable channels are skipped.
local Types = require("@formats/Types")
local Sampler = {}
export type Sample = (t: number) -> { number }
export type Pose = { [number]: { [string]: { number } } }
local function normalize(q: { number }): { number }
local l = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4])
if l <= 0 then
return { 0, 0, 0, 1 }
end
return { q[1] / l, q[2] / l, q[3] / l, q[4] / l }
end
local function slerp(a: { number }, b: { number }, s: number): { number }
local d = a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4]
local bx, by, bz, bw = b[1], b[2], b[3], b[4]
if d < 0 then
d, bx, by, bz, bw = -d, -bx, -by, -bz, -bw
end
local wa, wb
if d > 0.9995 then
wa, wb = 1 - s, s
else
local th = math.acos(math.min(d, 1))
local sn = math.sin(th)
wa, wb = math.sin((1 - s) * th) / sn, math.sin(s * th) / sn
end
return normalize({ a[1] * wa + bx * wb, a[2] * wa + by * wb, a[3] * wa + bz * wb, a[4] * wa + bw * wb })
end
-- channel(ch) -> sample(t) | nil
function Sampler.channel(ch: Types.Channel): Sample?
local inp, out = ch.input, ch.output
if type(inp) ~= "table" or type(out) ~= "table" then
return nil
end
local IN, OUT = Types.Scene.reader(inp), Types.Scene.reader(out)
local n = inp.count
if not IN or not OUT or n < 1 then
return nil
end
local cubic = ch.interpolation == "CUBICSPLINE"
local per = if cubic then 3 else 1
local comps: number
if ch.path == "weights" then
comps = (out.count * out.components) // (n * per)
else
comps = if ch.path == "rotation" then 4 else 3
end
if comps < 1 or out.count * out.components < n * per * comps then
return nil
end
local times = table.create(n) :: { number }
for k = 1, n do
times[k] = IN(k - 1, 0)
end
local oc = out.components
-- element e (0-based, of comps values) of the flat output
local function get(e: number): { number }
local v = table.create(comps) :: { number }
for c = 0, comps - 1 do
local flat = e * comps + c
v[c + 1] = OUT(flat // oc, flat % oc)
end
return v
end
local function value(k: number): { number } -- key k (1-based)
return get(if cubic then (k - 1) * 3 + 1 else k - 1)
end
local rot = ch.path == "rotation"
local step = ch.interpolation == "STEP"
return function(t: number): { number }
if t <= times[1] or n == 1 then
return if rot then normalize(value(1)) else value(1)
end
if t >= times[n] then
return if rot then normalize(value(n)) else value(n)
end
local lo, hi = 1, n
while hi - lo > 1 do
local mid = (lo + hi) // 2
if times[mid] <= t then
lo = mid
else
hi = mid
end
end
local dt = times[hi] - times[lo]
local s = if dt > 0 then (t - times[lo]) / dt else 0
if step then
return if rot then normalize(value(lo)) else value(lo)
end
if cubic then
local p0, m0 = value(lo), get((lo - 1) * 3 + 2)
local p1, m1 = value(hi), get((hi - 1) * 3)
local s2, s3 = s * s, s * s * s
local h00, h10, h01, h11 = 2 * s3 - 3 * s2 + 1, s3 - 2 * s2 + s, -2 * s3 + 3 * s2, s3 - s2
local v = table.create(comps) :: { number }
for c = 1, comps do
v[c] = h00 * p0[c] + h10 * dt * m0[c] + h01 * p1[c] + h11 * dt * m1[c]
end
return if rot then normalize(v) else v
end
local a, b = value(lo), value(hi)
if rot then
return slerp(normalize(a), normalize(b), s)
end
local v = table.create(comps) :: { number }
for c = 1, comps do
v[c] = a[c] + (b[c] - a[c]) * s
end
return v
end
end
-- times(anim) -> every key time, sorted and unique
function Sampler.times(anim: Types.Animation): { number }
local seen: { [number]: boolean } = {}
local out: { number } = {}
for _, ch in anim.channels do
local inp = ch.input
local IN = type(inp) == "table" and Types.Scene.reader(inp)
if IN then
for k = 0, inp.count - 1 do
local t = IN(k, 0)
if not seen[t] and t == t then
seen[t] = true
table.insert(out, t)
end
end
end
end
table.sort(out)
return out
end
-- pose(scene, anim, t, samplers?) -> pose[node] = { [path] = values } for the animated nodes. samplers: a cache table
-- (reuse it across calls for the same animation)
function Sampler.pose(_scene: Types.Scene, anim: Types.Animation, t: number, samplers: { [any]: any }?): Pose
local cache: { [any]: any } = samplers or {}
local pose: Pose = {}
for _, ch in anim.channels do
if cache[ch] == nil then
cache[ch] = Sampler.channel(ch) or false
end
local s: Sample? = cache[ch] or nil
if s then
local p = pose[ch.node]
if not p then
p = {}
pose[ch.node] = p
end
p[ch.path] = s(t)
end
end
return pose
end
return Sampler
+590
View File
@@ -0,0 +1,590 @@
--!strict
-- codecs/model/Vrml/Build: the VRML97 / X3D node graph (codecs/model/Vrml/Parse, codecs/model/Vrml/Xml) to a Scene.
-- Written from the specifications; no third-party code. Grouping nodes (Group, Transform with center / scaleOrientation,
-- Anchor, Billboard, Collision, StaticGroup, Switch whichChoice, LOD first level, CAD and HAnim groups, Inline through
-- the fetch callback) become nodes; a Transform is one TRS node (translation T + C, rotation R * SR, scale S) and, when
-- it has a center or scale orientation, an inner node (rotation SR^-1, translation SR^-1 * -C) holding the children.
-- Shapes become meshes (shared by USE), Appearance / Material / PhysicalMaterial / UnlitMaterial / TwoSidedMaterial
-- materials (Phong terms in material.extras.vrml; solid FALSE -> doubleSided), ImageTexture / MovieTexture
-- (uri, data through fetch, repeatS / repeatT), PixelTexture (texture.image), TextureTransform (KHR transform:
-- translation / scale / rotation; the center in extras); Viewpoint / OrthoViewpoint -> cameras, DirectionalLight /
-- PointLight / SpotLight -> lights; ROUTEs from a TimeSensor through Position- / OrientationInterpolators to a
-- Transform's translation / rotation / scale -> animations (key times x cycleInterval). Other nodes are counted in
-- meta.source.skipped. Never throws: bad data returns nil, message.
local Types = require("@formats/Types")
local Mat4 = require("@formats/codecs/model/Mat4")
local Fields = require("@formats/codecs/model/Vrml/Fields")
local Geometry = require("@formats/codecs/model/Vrml/Geometry")
local Build = {}
local S = Types.Scene
local nums, num, vec, bool, str, strs, node, nodes = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.str, Fields.strs, Fields.node, Fields.nodes
local deg = math.deg
export type Options = Geometry.Options & {
fetch: ((uri: string) -> buffer?)?, -- reads textures and Inline files
load: ((data: buffer) -> (any, string?))?, -- an Inline file's bytes -> its graph
format: string?, -- meta.source.format
maxInline: number?, -- Inline nesting (default 8)
}
local GROUP = { Group = true, Anchor = true, Billboard = true, Collision = true, StaticGroup = true, CADAssembly = true, CADLayer = true, LayerSet = true, Layer = true, HAnimSegment = true, HAnimSite = true, LOD = true, Switch = true }
local TRANSFORM = { Transform = true, CADPart = true, HAnimHumanoid = true, HAnimJoint = true }
local CHILDREN = { "children", "skeleton", "segments", "sites", "layers" }
-- nodes with nothing to show (not counted as skipped)
local QUIET = {
WorldInfo = true, NavigationInfo = true, Background = true, TextureBackground = true, Fog = true, TimeSensor = true,
PositionInterpolator = true, OrientationInterpolator = true, ScalarInterpolator = true, ColorInterpolator = true,
CoordinateInterpolator = true, NormalInterpolator = true, TouchSensor = true, ProximitySensor = true,
VisibilitySensor = true, PlaneSensor = true, CylinderSensor = true, SphereSensor = true, Script = true, Sound = true,
AudioClip = true, MetadataString = true, MetadataFloat = true, MetadataInteger = true, MetadataDouble = true,
MetadataSet = true, MetadataBoolean = true, BooleanFilter = true, BooleanToggle = true, BooleanTrigger = true,
BooleanSequencer = true, IntegerSequencer = true, IntegerTrigger = true, TimeTrigger = true, KeySensor = true,
StringSensor = true, LoadSensor = true,
}
local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", gif = "image/gif", bmp = "image/bmp", webp = "image/webp", ktx2 = "image/ktx2", dds = "image/vnd-ms.dds", tga = "image/x-tga" }
local function quat(r: { number }): { number }
return Mat4.axisAngle(r[1], r[2], r[3], deg(r[4]))
end
local function qmul(a: { number }, b: { number }): { number }
return {
a[4] * b[1] + a[1] * b[4] + a[2] * b[3] - a[3] * b[2],
a[4] * b[2] - a[1] * b[3] + a[2] * b[4] + a[3] * b[1],
a[4] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[4],
a[4] * b[4] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3],
}
end
local function qrot(q: { number }, v: { number }): { number }
local m = Mat4.fromQuat(q)
local x, y, z = Mat4.point(m, v[1], v[2], v[3])
return { x, y, z }
end
local function isZero(v: { number }): boolean
return v[1] == 0 and v[2] == 0 and v[3] == 0
end
local function isIdentityQ(q: { number }): boolean
return q[1] == 0 and q[2] == 0 and q[3] == 0
end
-- the rotation taking unit vector a onto b
local function between(a: { number }, b: { number }): { number }
local l = math.sqrt(b[1] * b[1] + b[2] * b[2] + b[3] * b[3])
if l < 1e-12 then
return { 0, 0, 0, 1 }
end
local bx, by, bz = b[1] / l, b[2] / l, b[3] / l
local d = a[1] * bx + a[2] * by + a[3] * bz
if d < -0.999999 then
-- opposite: half a turn about any perpendicular axis
return if math.abs(a[1]) < 0.9 then { 0, a[3], -a[2], 0 } else { -a[3], 0, a[1], 0 }
end
local cx, cy, cz = a[2] * bz - a[3] * by, a[3] * bx - a[1] * bz, a[1] * by - a[2] * bx
local w = 1 + d
local n = math.sqrt(cx * cx + cy * cy + cz * cz + w * w)
return { cx / n, cy / n, cz / n, w / n }
end
type Ctx = {
scene: Types.Scene,
opts: Options,
meshes: { [any]: any },
materials: { [any]: any },
textures: { [any]: number },
instances: { [any]: { { node: number, center: { number }, so: { number } } } },
skipped: { [string]: number },
depth: number,
inline: number,
failure: string?,
}
local function addNode(ctx: Ctx, n: Types.Node, parent: number?): number
local nodes_ = ctx.scene.nodes
table.insert(nodes_, n)
local i = #nodes_
if parent then
table.insert(nodes_[parent].children, i)
else
table.insert(ctx.scene.roots, i)
end
return i
end
-- ------------------------------------------------------------------------------------------------ materials
local function texture(ctx: Ctx, t: any): number?
if not t then
return nil
end
if t.type == "MultiTexture" then
return texture(ctx, nodes(t, "texture")[1])
end
local cached = ctx.textures[t]
if cached then
return cached
end
local tex: Types.Texture = { name = t.def }
if t.type == "ImageTexture" or t.type == "MovieTexture" then
local urls = strs(t, "url")
local fetch = ctx.opts.fetch
for _, u in urls do
local clean = string.match(u, "^([^#?]*)") or u
if not tex.uri and not string.find(clean, "^%a[%w+.-]*://") then
tex.uri = clean
end
local data = fetch and fetch(clean)
if data then
tex.uri, tex.data = clean, data
break
end
end
tex.uri = tex.uri or urls[1]
local ext = tex.uri and string.match(tex.uri, "%.(%w+)$")
tex.mime = if ext then MIME[string.lower(ext)] else nil
elseif t.type == "PixelTexture" then
-- SFImage: width height components pixels (0xRRGGBBAA style integers, MSB first)
local v = nums(t, "image") or {}
local w, h, c = math.floor(v[1] or 0), math.floor(v[2] or 0), math.floor(v[3] or 0)
if w > 0 and h > 0 and c >= 1 and c <= 4 and w * h <= 2 ^ 24 and #v >= 3 + w * h then
local img = Types.Image.new(w, h)
for i = 0, w * h - 1 do
local px = math.floor(v[4 + i]) % 2 ^ (8 * c)
local b = table.create(4, 0)
for k = c, 1, -1 do
b[k] = px % 256
px //= 256
end
local r, g, bl, a
if c <= 2 then
r, g, bl, a = b[1], b[1], b[1], if c == 2 then b[2] else 255
else
r, g, bl, a = b[1], b[2], b[3], if c == 4 then b[4] else 255
end
-- the image's first row is the bottom one
local row = h - 1 - i // w
local o = (row * w + i % w) * 4
buffer.writeu8(img.pixels, o, r)
buffer.writeu8(img.pixels, o + 1, g)
buffer.writeu8(img.pixels, o + 2, bl)
buffer.writeu8(img.pixels, o + 3, a)
end
tex.image = img
end
else
ctx.skipped[t.type] = (ctx.skipped[t.type] or 0) + 1
return nil
end
local rs, rt = bool(t, "repeatS", true), bool(t, "repeatT", true)
if not rs or not rt then
tex.sampler = { wrapS = if rs then "repeat" else "clamp", wrapT = if rt then "repeat" else "clamp" }
end
table.insert(ctx.scene.textures, tex)
ctx.textures[t] = #ctx.scene.textures
return #ctx.scene.textures
end
local function textureRef(ctx: Ctx, t: any, xf: any): Types.TextureRef?
local i = texture(ctx, t)
if not i then
return nil
end
local ref: Types.TextureRef = { texture = i }
if xf and xf.type == "TextureTransform" then
local tr, sc, rot = vec(xf, "translation", { 0, 0 }), vec(xf, "scale", { 1, 1 }), num(xf, "rotation", 0)
if tr[1] ~= 0 or tr[2] ~= 0 or sc[1] ~= 1 or sc[2] ~= 1 or rot ~= 0 then
ref.transform = { offset = tr, scale = sc, rotation = rot }
end
end
return ref
end
local function material(ctx: Ctx, app: any, solid: boolean): number?
if not app and solid then
return nil
end
local key = app or "default"
local cache = ctx.materials[key]
if type(cache) ~= "table" then
cache = {}
ctx.materials[key] = cache
end
local hit = (cache :: any)[solid]
if hit then
return hit
end
local m = S.material(app and app.def)
m.metallic = 0
local x: { [string]: any } = {}
local mat = app and node(app, "material")
local tex = app and node(app, "texture")
local xf = app and node(app, "textureTransform")
if mat and mat.type == "TwoSidedMaterial" then
m.doubleSided = true
x.twoSided = true
end
if mat and (mat.type == "Material" or mat.type == "TwoSidedMaterial") then
local d, e, sp = vec(mat, "diffuseColor", { 0.8, 0.8, 0.8 }), vec(mat, "emissiveColor", { 0, 0, 0 }), vec(mat, "specularColor", { 0, 0, 0 })
local sh, tr, amb = num(mat, "shininess", 0.2), num(mat, "transparency", 0), num(mat, "ambientIntensity", 0.2)
m.name = mat.def or m.name
m.baseColor = { d[1], d[2], d[3], 1 - tr }
m.emissive = e
m.roughness = math.clamp(math.sqrt(2 / (math.max(sh, 0) * 128 + 2)), 0, 1)
x.diffuseColor, x.emissiveColor, x.specularColor, x.shininess, x.transparency, x.ambientIntensity = d, e, sp, sh, tr, amb
if tr > 0 then
m.alphaMode = "blend"
end
-- X3D 4 texture fields
local dt = node(mat, "diffuseTexture")
if dt then
m.baseColorTexture = textureRef(ctx, dt, nil)
end
local nt = node(mat, "normalTexture")
if nt then
m.normalTexture = textureRef(ctx, nt, nil)
end
elseif mat and mat.type == "PhysicalMaterial" then
local b, e = vec(mat, "baseColor", { 1, 1, 1 }), vec(mat, "emissiveColor", { 0, 0, 0 })
local tr = num(mat, "transparency", 0)
m.name = mat.def or m.name
m.baseColor = { b[1], b[2], b[3], 1 - tr }
m.emissive, m.metallic, m.roughness = e, num(mat, "metallic", 1), num(mat, "roughness", 1)
if tr > 0 then
m.alphaMode = "blend"
end
local slots: { [string]: string } = { baseTexture = "baseColorTexture", metallicRoughnessTexture = "metallicRoughnessTexture", normalTexture = "normalTexture", occlusionTexture = "occlusionTexture", emissiveTexture = "emissiveTexture" }
for field, slot in slots do
local t = node(mat, field)
if t then
(m :: any)[slot] = textureRef(ctx, t, nil)
end
end
elseif mat and mat.type == "UnlitMaterial" then
local e = vec(mat, "emissiveColor", { 1, 1, 1 })
m.name = mat.def or m.name
m.baseColor = { e[1], e[2], e[3], 1 - num(mat, "transparency", 0) }
m.extensions = { KHR_materials_unlit = {} }
else
-- no material: unlit white (the specifications' default)
m.extensions = { KHR_materials_unlit = {} }
end
if tex and not m.baseColorTexture then
m.baseColorTexture = textureRef(ctx, tex, xf)
if m.baseColorTexture and xf then
x.textureCenter = vec(xf, "center", { 0, 0 })
end
end
if not solid then
m.doubleSided = true
end
m.extras = { vrml = x }
table.insert(ctx.scene.materials, m)
local idx = #ctx.scene.materials
;(cache :: any)[solid] = idx
return idx
end
-- ------------------------------------------------------------------------------------------------ nodes
local walk: (ctx: Ctx, n: any, parent: number?) -> ()
local function shape(ctx: Ctx, n: any, parent: number?)
local geo = node(n, "geometry")
if not geo then
return
end
local mi = ctx.meshes[n]
if mi == nil then
local prim, solidOrErr = Geometry.primitive(geo, ctx.opts)
if not prim then
if solidOrErr then
ctx.failure = ctx.failure or solidOrErr
else
ctx.skipped[geo.type] = (ctx.skipped[geo.type] or 0) + 1
end
ctx.meshes[n] = false :: any
return
end
local count = if prim.indices then prim.indices.count else prim.attributes.POSITION.count
if count == 0 then
-- nothing to draw (no valid faces / points)
ctx.meshes[n] = false
return
end
prim.material = material(ctx, node(n, "appearance"), solidOrErr == true)
table.insert(ctx.scene.meshes, { name = n.def or geo.def, primitives = { prim } })
mi = #ctx.scene.meshes
ctx.meshes[n] = mi
elseif mi == false then
return
end
addNode(ctx, { name = n.def, children = {}, mesh = mi }, parent)
end
local function viewpoint(ctx: Ctx, n: any, parent: number?)
local cam: any
if n.type == "OrthoViewpoint" then
local f = vec(n, "fieldOfView", { -1, -1, 1, 1 })
cam = { type = "orthographic", xmag = (f[3] - f[1]) / 2, ymag = (f[4] - f[2]) / 2, znear = 0.125, zfar = 1e4 }
else
cam = { type = "perspective", yfov = num(n, "fieldOfView", 0.785398), znear = 0.125 }
end
cam.name = n.def or str(n, "description")
table.insert(ctx.scene.cameras, cam)
local o = vec(n, "orientation", { 0, 0, 1, 0 })
local nd: Types.Node = { name = cam.name, children = {}, camera = #ctx.scene.cameras, translation = vec(n, "position", { 0, 0, 10 }) }
if o[4] ~= 0 then
nd.rotation = quat(o)
end
addNode(ctx, nd, parent)
end
local function light(ctx: Ctx, n: any, parent: number?)
local t = n.type
local l: Types.Light = { name = n.def, type = "point", color = vec(n, "color", { 1, 1, 1 }), intensity = num(n, "intensity", 1) }
local nd: Types.Node = { name = n.def, children = {} }
local x: { [string]: any } = { ambientIntensity = num(n, "ambientIntensity", 0), on = bool(n, "on", true), global = bool(n, "global", t == "DirectionalLight") }
if t == "DirectionalLight" then
l.type = "directional"
nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 }))
else
nd.translation = vec(n, "location", { 0, 0, 0 })
l.range = num(n, "radius", 100)
x.attenuation = vec(n, "attenuation", { 1, 0, 0 })
if t == "SpotLight" then
l.type = "spot"
nd.rotation = between({ 0, 0, -1 }, vec(n, "direction", { 0, 0, -1 }))
local cut = num(n, "cutOffAngle", 0.785398)
l.outerCone = cut
l.innerCone = math.min(num(n, "beamWidth", 1.570796), cut)
end
end
;(l :: any).extras = { vrml = x }
table.insert(ctx.scene.lights, l)
nd.light = #ctx.scene.lights
addNode(ctx, nd, parent)
end
local function children(ctx: Ctx, n: any, parent: number?)
if n.type == "Switch" then
local which = math.floor(num(n, "whichChoice", -1))
local list = nodes(n, "choice")
if #list == 0 then
list = nodes(n, "children")
end
local c = list[which + 1]
if which >= 0 and c then
walk(ctx, c, parent)
end
return
elseif n.type == "LOD" then
local list = nodes(n, "level")
if #list == 0 then
list = nodes(n, "children")
end
if list[1] then
walk(ctx, list[1], parent)
end
return
end
for _, f in CHILDREN do
for _, c in nodes(n, f) do
walk(ctx, c, parent)
end
end
end
local function transform(ctx: Ctx, n: any, parent: number?)
local t, c = vec(n, "translation", { 0, 0, 0 }), vec(n, "center", { 0, 0, 0 })
local r, s, so = vec(n, "rotation", { 0, 0, 1, 0 }), vec(n, "scale", { 1, 1, 1 }), vec(n, "scaleOrientation", { 0, 0, 1, 0 })
local qr, qs = quat(r), quat(so)
local outer: Types.Node = { name = n.def, children = {} }
local tt = { t[1] + c[1], t[2] + c[2], t[3] + c[3] }
if not isZero(tt) then
outer.translation = tt
end
local q = if isIdentityQ(qs) then qr else qmul(qr, qs)
if not isIdentityQ(q) then
outer.rotation = q
end
if s[1] ~= 1 or s[2] ~= 1 or s[3] ~= 1 then
outer.scale = s
end
local oi = addNode(ctx, outer, parent)
local list = ctx.instances[n]
if not list then
list = {}
ctx.instances[n] = list
end
table.insert(list, { node = oi, center = c, so = qs })
local holder = oi
if not isZero(c) or not isIdentityQ(qs) then
local inv = { -qs[1], -qs[2], -qs[3], qs[4] }
local inner: Types.Node = { children = {}, translation = qrot(inv, { -c[1], -c[2], -c[3] }) }
if not isIdentityQ(inv) then
inner.rotation = inv
end
holder = addNode(ctx, inner, oi)
end
children(ctx, n, holder)
end
local function inline(ctx: Ctx, n: any, parent: number?)
local fetch, load = ctx.opts.fetch, ctx.opts.load
if not fetch or not load or ctx.inline >= (ctx.opts.maxInline or 8) or not bool(n, "load", true) then
ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1
return
end
for _, u in strs(n, "url") do
local data = fetch(string.match(u, "^([^#?]*)") or u)
if data then
local g = load(data)
if g then
local holder = addNode(ctx, { name = n.def, children = {} }, parent)
ctx.inline += 1
for _, root in g.roots do
walk(ctx, root, holder)
end
ctx.inline -= 1
return
end
end
end
ctx.skipped.Inline = (ctx.skipped.Inline or 0) + 1
end
function walk(ctx: Ctx, n: any, parent: number?)
if ctx.failure or type(n) ~= "table" then
return
end
ctx.depth += 1
if ctx.depth > 200 then
ctx.failure = "limit: scene nested deeper than 200"
return
end
local t = n.type
if TRANSFORM[t] then
transform(ctx, n, parent)
elseif GROUP[t] then
local holder = parent
if n.def or parent == nil then
holder = addNode(ctx, { name = n.def, children = {} }, parent)
end
children(ctx, n, holder)
elseif t == "Shape" then
shape(ctx, n, parent)
elseif t == "CADFace" then
for _, s in nodes(n, "shape") do
walk(ctx, s, parent)
end
elseif t == "Viewpoint" or t == "OrthoViewpoint" then
viewpoint(ctx, n, parent)
elseif t == "DirectionalLight" or t == "PointLight" or t == "SpotLight" then
light(ctx, n, parent)
elseif t == "Inline" then
inline(ctx, n, parent)
elseif t == "WorldInfo" then
local src = ctx.scene.meta.source :: any
src.title = str(n, "title")
local info = strs(n, "info")
src.info = if #info > 0 then info else nil
elseif not QUIET[t] then
ctx.skipped[t] = (ctx.skipped[t] or 0) + 1
end
ctx.depth -= 1
end
-- ------------------------------------------------------------------------------------------------ animation
local TARGET = { set_translation = "translation", translation = "translation", set_rotation = "rotation", rotation = "rotation", set_scale = "scale", scale = "scale" }
local function animations(ctx: Ctx, routes: { any })
-- interpolator -> its TimeSensor
local timer: { [any]: any } = {}
for _, r in routes do
if (r.toField == "set_fraction" or r.toField == "fraction") and r.from.type == "TimeSensor" then
timer[r.to] = r.from
end
end
local anims: { [any]: Types.Animation } = {}
local order: { any } = {}
for _, r in routes do
local path = TARGET[r.toField]
local it = r.from
local inst = ctx.instances[r.to]
if not (path and inst and (it.type == "PositionInterpolator" or it.type == "OrientationInterpolator")) then
continue
end
if (path == "rotation") ~= (it.type == "OrientationInterpolator") then
continue
end
local key: { number }, kv: { number } = nums(it, "key") or {}, nums(it, "keyValue") or {}
local comps = if path == "rotation" then 4 else 3
local n = math.min(#key, #kv // comps)
if n == 0 then
continue
end
local ts = timer[it]
local cycle = if ts then num(ts, "cycleInterval", 1) else 1
local input = S.accessor(nil, "f32", 1, n)
for i = 0, n - 1 do
buffer.writef32(input.data, i * 4, key[i + 1] * cycle)
end
local id = ts or "routes"
local anim = anims[id]
if not anim then
anim = { name = if ts then ts.def else nil, channels = {} }
anims[id] = anim
table.insert(order, id)
end
for _, at in inst do
local out = S.accessor(nil, "f32", if path == "rotation" then 4 else 3, n)
local prev: { number }? = nil
for i = 0, n - 1 do
local v: { number }
if path == "rotation" then
v = quat({ kv[i * 4 + 1], kv[i * 4 + 2], kv[i * 4 + 3], kv[i * 4 + 4] })
if not isIdentityQ(at.so) then
v = qmul(v, at.so)
end
if prev and prev[1] * v[1] + prev[2] * v[2] + prev[3] * v[3] + prev[4] * v[4] < 0 then
v = { -v[1], -v[2], -v[3], -v[4] }
end
prev = v
elseif path == "translation" then
v = { kv[i * 3 + 1] + at.center[1], kv[i * 3 + 2] + at.center[2], kv[i * 3 + 3] + at.center[3] }
else
v = { kv[i * 3 + 1], kv[i * 3 + 2], kv[i * 3 + 3] }
end
for c = 1, #v do
buffer.writef32(out.data, (i * #v + c - 1) * 4, v[c])
end
end
table.insert(anim.channels, { node = at.node, path = path :: any, input = input, output = out, interpolation = "LINEAR" :: any })
end
end
for _, id in order do
table.insert(ctx.scene.animations, anims[id])
end
end
-- ------------------------------------------------------------------------------------------------ scene
function Build.scene(graph: any, opts: Options): (Types.Scene?, string?)
local scene = S.new()
scene.meta.up = "y"
local units = graph.units or {}
scene.meta.unit = if units.length and units.length.factor > 0 then units.length.factor else 1
local h = graph.header or {}
local skipped: { [string]: number } = {}
scene.meta.source = {
format = opts.format or "vrml", version = h.version, encoding = h.encoding, profile = h.profile, x3d = h.x3d,
xml = h.xml, meta = graph.meta, components = graph.components, skipped = skipped,
}
local ctx: Ctx = { scene = scene, opts = opts, meshes = {}, materials = {}, textures = {}, instances = {}, skipped = skipped, depth = 0, inline = 0, failure = nil }
for _, n in graph.roots do
walk(ctx, n, nil)
end
if ctx.failure then
return nil, ctx.failure
end
animations(ctx, graph.routes or {})
return scene, nil
end
return Build
+168
View File
@@ -0,0 +1,168 @@
--!strict
-- codecs/model/Vrml/Fields: typed reads of node fields for codecs/model/Vrml/Build and Geometry. A classic-encoding
-- value is a flat array (numbers, strings, booleans, nodes); an X3D XML value is the raw attribute string, parsed here
-- on first use (numbers split on blanks / commas, MFString as quoted strings or one unquoted string, booleans
-- true / false). Never throws.
local Fields = {}
local gmatch, find, sub, byte = string.gmatch, string.find, string.sub, string.byte
-- quoted strings of an MFString attribute ("a" "b \"c\""), or the text itself when it is not quoted
local function mfString(s: string): { string }
local out = {}
local p = find(s, "[^%s,]")
if not p or byte(s, p) ~= 34 then
return if p then { (string.match(s, "^%s*(.-)%s*$") :: string) } else {}
end
local n = #s
while p and p <= n do
if byte(s, p) ~= 34 then
break
end
local q = p + 1
local parts = {}
while true do
local e = find(s, '["\\]', q)
if not e then
table.insert(parts, sub(s, q))
table.insert(out, table.concat(parts))
return out
end
table.insert(parts, sub(s, q, e - 1))
if byte(s, e) == 92 then
table.insert(parts, sub(s, e + 1, e + 1))
q = e + 2
else
p = e + 1
break
end
end
table.insert(out, table.concat(parts))
p = find(s, "[^%s,]", p)
end
return out
end
-- nums(node, name) -> the numbers of a field (booleans as 1 / 0), or nil when absent
function Fields.nums(node: any, name: string): { number }?
local v = node.fields[name]
if v == nil then
return nil
end
if type(v) == "string" then
local out = {}
for w in gmatch(v, "[^%s,]+") do
local x = tonumber(w)
if x then
table.insert(out, x)
elseif w == "true" or w == "TRUE" then
table.insert(out, 1)
elseif w == "false" or w == "FALSE" then
table.insert(out, 0)
end
end
node.fields[name] = out
return out
end
if type(v) ~= "table" then
return nil
end
local ok = true
for _, x in v do
if type(x) ~= "number" then
ok = false
break
end
end
if ok then
return v
end
local out = {}
for _, x in v do
if type(x) == "number" then
table.insert(out, x)
elseif type(x) == "boolean" then
table.insert(out, if x then 1 else 0)
end
end
return out
end
function Fields.num(node: any, name: string, default: number): number
local v = Fields.nums(node, name)
return if v and type(v[1]) == "number" then v[1] else default
end
-- vec(node, name, default) -> the first #default numbers of a field (the default when the field is shorter)
function Fields.vec(node: any, name: string, default: { number }): { number }
local v = Fields.nums(node, name)
if not v or #v < #default then
return default
end
local out: { number } = {}
for i = 1, #default do
out[i] = v[i]
end
return out
end
function Fields.bool(node: any, name: string, default: boolean): boolean
local v = node.fields[name]
if type(v) == "string" then
local w = string.lower(string.match(v, "^%s*(%S*)") :: string)
return if w == "true" then true elseif w == "false" then false else default
end
if type(v) == "table" and type(v[1]) == "boolean" then
return v[1]
end
return default
end
function Fields.strs(node: any, name: string): { string }
local v = node.fields[name]
if type(v) == "string" then
local out = mfString(v)
node.fields[name] = out
return out
end
local out = {}
if type(v) == "table" then
for _, x in v do
if type(x) == "string" then
table.insert(out, x)
end
end
end
return out
end
function Fields.str(node: any, name: string, default: string?): string?
local v = node.fields[name]
if type(v) == "string" then
return v
end
if type(v) == "table" and type(v[1]) == "string" then
return v[1]
end
return default
end
-- nodes(node, name) -> the nodes of an SFNode / MFNode field
function Fields.nodes(node: any, name: string): { any }
local v = node.fields[name]
local out = {}
if type(v) == "table" then
for _, x in v do
if type(x) == "table" and type(x.type) == "string" then
table.insert(out, x)
end
end
end
return out
end
function Fields.node(node: any, name: string): any
return Fields.nodes(node, name)[1]
end
return Fields
+770
View File
@@ -0,0 +1,770 @@
--!strict
-- codecs/model/Vrml/Geometry: VRML97 / X3D geometry nodes to Scene primitives. Written from the specifications; no
-- third-party code. IndexedFaceSet (coord / normal / color / texCoord with their own indices, per-vertex or per-face
-- normals and colours, ccw, convex polygons fan-triangulated or kept as "polygons"), the X3D triangle / quad sets
-- (IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet, TriangleFanSet, IndexedTriangleStripSet,
-- TriangleStripSet, IndexedQuadSet, QuadSet), ElevationGrid, Extrusion (spine-aligned cross sections, scale,
-- orientation, caps), IndexedLineSet / LineSet ("lines"), PointSet ("points"), and the primitives Box, Sphere, Cone,
-- Cylinder tessellated with normals and the specification's texture mapping. Texture coordinates get t flipped to
-- glTF's top-left origin unless flipV = false. Never throws: returns nil, message for bad data.
local Types = require("@formats/Types")
local Fields = require("@formats/codecs/model/Vrml/Fields")
local Geometry = {}
local S = Types.Scene
local nums, num, vec, bool, node = Fields.nums, Fields.num, Fields.vec, Fields.bool, Fields.node
local sqrt, sin, cos, pi = math.sqrt, math.sin, math.cos, math.pi
export type Options = { flipV: boolean?, triangulate: boolean?, segments: number?, maxVertices: number? }
local function f32(list: { number }, comps: number, count: number): Types.Accessor
local a = S.accessor(nil, "f32", comps, count)
local d = a.data
for i = 1, math.min(#list, comps * count) do
buffer.writef32(d, (i - 1) * 4, list[i])
end
return a
end
local function u32(list: { number }): Types.Accessor
local a = S.accessor(nil, "u32", 1, #list)
for i, v in list do
buffer.writeu32(a.data, (i - 1) * 4, v)
end
return a
end
-- the colour node's values and component count (Color: 3, ColorRGBA: 4)
local function colors(n: any): ({ number }?, number)
local c = node(n, "color")
if not c then
return nil, 3
end
local comps = if c.type == "ColorRGBA" then 4 else 3
return nums(c, "color") or {}, comps
end
local function points(n: any, field: string, sub: string): { number }?
local c = node(n, field)
return if c then nums(c, sub) or {} else nil
end
-- ------------------------------------------------------------------------------------------------ polygon meshes
-- Mesh input: faces as corner lists of coordinate indices (0-based) plus, per attribute, a per-corner index list (nil:
-- the coordinate index) or per-face indices.
type PolyIn = {
P: { number }, -- coordinates, 3 per point
corners: { number }, -- coordinate index per corner, face after face
sizes: { number }, -- corners per face
N: { number }?, nIdx: { number }?, nFace: boolean?, -- normals; per-corner or per-face indices (nil: identity)
C: { number }?, cComps: number?, cIdx: { number }?, cFace: boolean?,
T: { number }?, tIdx: { number }?,
ccw: boolean,
}
local function polyMesh(m: PolyIn, o: Options, maxV: number): (any, string?)
local P, corners, sizes = m.P, m.corners, m.sizes
local np = #P // 3
local N, C, T = m.N, m.C, m.T
local cc = m.cComps or 3
-- the attribute index of corner k (1-based) in face f (1-based)
local function idx(list: { number }?, perFace: boolean?, f: number, k: number, c: number): number
if perFace then
return if list and #list > 0 then (list[f] or 0) else f - 1
end
return if list and #list > 0 then (list[k] or c) else c
end
local simple = (N == nil or (not m.nFace and (m.nIdx == nil or #m.nIdx == 0))) and (C == nil or (not m.cFace and (m.cIdx == nil or #m.cIdx == 0))) and (T == nil or m.tIdx == nil or #m.tIdx == 0)
local vkey: { [string]: number } = {}
local vsrc: { { number } } = {} -- per output vertex: coord, normal, colour, texcoord indices
local out: { number } = {}
local outSizes: { number } = {}
local k = 0
for f, size in sizes do
local face: { number } = {}
local valid = size >= 3
for q = 1, size do
k += 1
local c = corners[k]
if c == nil or c < 0 or c >= np then
valid = false
end
face[q] = k
end
if valid then
local verts: { number } = {}
for q, kk in face do
local c = corners[kk]
if simple then
verts[q] = c
else
local ni = if N then idx(m.nIdx, m.nFace, f, kk, c) else -1
local ci = if C then idx(m.cIdx, m.cFace, f, kk, c) else -1
local ti = if T then idx(m.tIdx, false, f, kk, c) else -1
local key = c .. ":" .. ni .. ":" .. ci .. ":" .. ti
local v = vkey[key]
if not v then
v = #vsrc
vsrc[v + 1] = { c, ni, ci, ti }
vkey[key] = v
if v >= maxV then
return nil, "limit: more than " .. maxV .. " vertices"
end
end
verts[q] = v
end
end
if not m.ccw then
for a = 2, (size + 1) // 2 do
verts[a], verts[size + 2 - a] = verts[size + 2 - a], verts[a]
end
end
if o.triangulate == false then
table.insert(outSizes, size)
for _, v in verts do
table.insert(out, v)
end
else
for a = 2, size - 1 do
table.insert(out, verts[1])
table.insert(out, verts[a])
table.insert(out, verts[a + 1])
end
end
end
end
local nv = if simple then np else #vsrc
if nv > maxV then
return nil, "limit: more than " .. maxV .. " vertices"
end
local flipV = o.flipV ~= false
local pos = S.accessor(nil, "f32", 3, nv)
local nrm = if N then S.accessor(nil, "f32", 3, nv) else nil
local col = if C then S.accessor(nil, "f32", cc, nv) else nil
local tex = if T then S.accessor(nil, "f32", 2, nv) else nil
local wf = buffer.writef32
for v = 0, nv - 1 do
local s = if simple then nil else vsrc[v + 1]
local c = if s then s[1] else v
for q = 0, 2 do
wf(pos.data, (v * 3 + q) * 4, P[c * 3 + q + 1] or 0)
end
if nrm and N then
local ni = if s then s[2] else v
for q = 0, 2 do
wf(nrm.data, (v * 3 + q) * 4, N[ni * 3 + q + 1] or 0)
end
end
if col and C then
local ci = if s then s[3] else v
for q = 0, cc - 1 do
wf(col.data, (v * cc + q) * 4, C[ci * cc + q + 1] or 1)
end
end
if tex and T then
local ti = if s then s[4] else v
local tt = T[ti * 2 + 2] or 0
wf(tex.data, v * 8, T[ti * 2 + 1] or 0)
wf(tex.data, v * 8 + 4, if flipV then 1 - tt else tt)
end
end
local attrs: { [string]: Types.Accessor } = { POSITION = pos }
attrs.NORMAL, attrs.COLOR_0, attrs.TEXCOORD_0 = nrm, col, tex
local prim: Types.Primitive = { attributes = attrs, indices = u32(out), mode = "triangles" }
if o.triangulate == false then
prim.mode = "polygons"
prim.faces = u32(outSizes)
end
return prim
end
-- split a -1 separated index list into corners + sizes
local function split(list: { number }): ({ number }, { number })
local corners, sizes = {}, {}
local run = 0
for _, x in list do
if x < 0 then
if run > 0 then
table.insert(sizes, run)
end
run = 0
else
table.insert(corners, x)
run += 1
end
end
if run > 0 then
table.insert(sizes, run)
end
return corners, sizes
end
-- per-face index lists keep only the entries of faces (the -1 separators of per-corner lists match the corners)
local function cornerList(list: { number }?): { number }?
if not list or #list == 0 then
return nil
end
local out = {}
for _, x in list do
if x >= 0 then
table.insert(out, x)
end
end
return out
end
local function faceSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?)
local P = points(n, "coord", "point") or {}
local corners, sizes = split(nums(n, "coordIndex") or {})
local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true)
local C, cc = colors(n)
local tc = node(n, "texCoord")
local m: PolyIn = {
P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true),
N = points(n, "normal", "vector"), nFace = not nPer, nIdx = if nPer then cornerList(nums(n, "normalIndex")) else nums(n, "normalIndex"),
C = C, cComps = cc, cFace = not cPer, cIdx = if cPer then cornerList(nums(n, "colorIndex")) else nums(n, "colorIndex"),
T = if tc and tc.type ~= "TextureCoordinateGenerator" then (nums(if tc.type == "MultiTextureCoordinate" then (node(tc, "texCoord") or tc) else tc, "point") or {}) else nil,
tIdx = cornerList(nums(n, "texCoordIndex")),
}
return polyMesh(m, o, maxV)
end
-- the X3D triangle / quad sets: faces from index (or vertex order) and fan / strip counts
local function triSet(n: any, o: Options, maxV: number): (Types.Primitive?, string?)
local t = n.type
local P = points(n, "coord", "point") or {}
local np = #P // 3
local index = nums(n, "index")
local seq: { number }
if string.sub(t, 1, 7) == "Indexed" then
seq = index or {}
else
seq = {}
for i = 0, np - 1 do
seq[i + 1] = i
end
end
local corners, sizes = {}, {}
local function tri(a: number, b: number, c: number)
table.insert(corners, a)
table.insert(corners, b)
table.insert(corners, c)
table.insert(sizes, 3)
end
-- runs: -1 separated (indexed fans / strips) or fanCount / stripCount (plain fans / strips)
local function runs(): { { number } }
local out = {}
local counts = nums(n, if string.find(t, "Fan", 1, true) then "fanCount" else "stripCount")
if string.sub(t, 1, 7) == "Indexed" or not counts then
local cur = {}
for _, x in seq do
if x < 0 then
table.insert(out, cur)
cur = {}
else
table.insert(cur, x)
end
end
table.insert(out, cur)
else
local at = 1
for _, c in counts do
local cur = {}
for q = 0, c - 1 do
cur[q + 1] = seq[at + q]
end
at += c
table.insert(out, cur)
end
end
return out
end
if t == "IndexedTriangleSet" or t == "TriangleSet" then
for i = 1, #seq - 2, 3 do
tri(seq[i], seq[i + 1], seq[i + 2])
end
elseif t == "IndexedQuadSet" or t == "QuadSet" then
for i = 1, #seq - 3, 4 do
for q = 0, 3 do
table.insert(corners, seq[i + q])
end
table.insert(sizes, 4)
end
elseif string.find(t, "Fan", 1, true) then
for _, r in runs() do
for i = 2, #r - 1 do
tri(r[1], r[i], r[i + 1])
end
end
else
for _, r in runs() do
for i = 1, #r - 2 do
if i % 2 == 1 then
tri(r[i], r[i + 1], r[i + 2])
else
tri(r[i + 1], r[i], r[i + 2])
end
end
end
end
local nPer, cPer = bool(n, "normalPerVertex", true), bool(n, "colorPerVertex", true)
local C, cc = colors(n)
local tc = node(n, "texCoord")
local m: PolyIn = {
P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true),
N = points(n, "normal", "vector"), nFace = not nPer, C = C, cComps = cc, cFace = not cPer,
T = if tc and tc.type == "TextureCoordinate" then nums(tc, "point") or {} else nil,
}
return polyMesh(m, o, maxV)
end
local function elevationGrid(n: any, o: Options, maxV: number): (Types.Primitive?, string?)
local nx, nz = math.floor(num(n, "xDimension", 0)), math.floor(num(n, "zDimension", 0))
local dx, dz = num(n, "xSpacing", 1), num(n, "zSpacing", 1)
local h: { number } = nums(n, "height") or {}
if nx < 2 or nz < 2 then
return nil, nil
end
if nx * nz > maxV then
return nil, "limit: elevation grid of " .. nx .. " x " .. nz
end
local P: { number }, T: { number }, corners: { number }, sizes: { number } = {}, {}, {}, {}
for z = 0, nz - 1 do
for x = 0, nx - 1 do
table.insert(P, x * dx)
table.insert(P, h[z * nx + x + 1] or 0)
table.insert(P, z * dz)
table.insert(T, x / (nx - 1))
table.insert(T, z / (nz - 1))
end
end
for z = 0, nz - 2 do
for x = 0, nx - 2 do
local a = z * nx + x
-- counter-clockwise seen from +y: a, a + nx, a + nx + 1, a + 1
for _, c in { a, a + nx, a + nx + 1, a + 1 } do
table.insert(corners, c)
end
table.insert(sizes, 4)
end
end
local C, cc = colors(n)
local tc = node(n, "texCoord")
local m: PolyIn = {
P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true),
N = points(n, "normal", "vector"), nFace = not bool(n, "normalPerVertex", true), C = C, cComps = cc,
cFace = not bool(n, "colorPerVertex", true), T = if tc then nums(tc, "point") or {} else T,
}
return polyMesh(m, o, maxV)
end
-- ------------------------------------------------------------------------------------------------ Extrusion
local function cross(a: { number }, b: { number }): { number }
return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] }
end
local function sub3(a: { number }, b: { number }): { number }
return { a[1] - b[1], a[2] - b[2], a[3] - b[3] }
end
local function norm(a: { number }): ({ number }, number)
local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3])
return if l > 1e-12 then { a[1] / l, a[2] / l, a[3] / l } else { 0, 0, 0 }, l
end
-- rotate v about the unit axis k by angle a (Rodrigues)
local function rotate(v: { number }, k: { number }, a: number): { number }
local c, s = cos(a), sin(a)
local d = (k[1] * v[1] + k[2] * v[2] + k[3] * v[3]) * (1 - c)
local kv = cross(k, v)
return { v[1] * c + kv[1] * s + k[1] * d, v[2] * c + kv[2] * s + k[2] * d, v[3] * c + kv[3] * s + k[3] * d }
end
local function extrusion(n: any, o: Options, maxV: number): (Types.Primitive?, string?)
local sp = nums(n, "spine") or { 0, 0, 0, 0, 1, 0 }
local cs = nums(n, "crossSection") or { 1, 1, 1, -1, -1, -1, -1, 1, 1, 1 }
local sc = nums(n, "scale") or { 1, 1 }
local ori = nums(n, "orientation") or { 0, 0, 1, 0 }
local ns, nc = #sp // 3, #cs // 2
if ns < 2 or nc < 2 then
return nil, nil
end
if ns * nc > maxV then
return nil, "limit: extrusion of " .. ns .. " x " .. nc
end
local spine = {}
for i = 1, ns do
spine[i] = { sp[i * 3 - 2], sp[i * 3 - 1], sp[i * 3] }
end
local function same(a: { number }, b: { number }): boolean
return math.abs(a[1] - b[1]) < 1e-9 and math.abs(a[2] - b[2]) < 1e-9 and math.abs(a[3] - b[3]) < 1e-9
end
local closedSpine = same(spine[1], spine[ns])
local closedCs = math.abs(cs[1] - cs[nc * 2 - 1]) < 1e-9 and math.abs(cs[2] - cs[nc * 2]) < 1e-9
-- spine-aligned cross-section planes: Y along the spine, Z from the bend, X = Y x Z
local Ys: { { number } }, Zs: { [number]: { number } } = {}, {}
for i = 1, ns do
local prev = if i > 1 then spine[i - 1] elseif closedSpine then spine[ns - 1] else nil
local nxt = if i < ns then spine[i + 1] elseif closedSpine then spine[2] else nil
local y = sub3(nxt or spine[i], prev or spine[i])
Ys[i] = norm(y)
if prev and nxt then
local z, l = norm(cross(sub3(nxt, spine[i]), sub3(prev, spine[i])))
Zs[i] = if l > 1e-12 then z else nil
end
end
-- missing Z: copy a neighbour's; a straight spine rotates (0, 0, 1) like (0, 1, 0) onto the spine direction
local firstZ = nil
for i = 1, ns do
if Zs[i] then
firstZ = Zs[i]
break
end
end
for i = 1, ns do
if not Ys[i] or (Ys[i][1] == 0 and Ys[i][2] == 0 and Ys[i][3] == 0) then
Ys[i] = Ys[i - 1] or { 0, 1, 0 }
end
end
for i = 1, ns do
if not Zs[i] then
if firstZ then
Zs[i] = Zs[i - 1] or firstZ
else
local y = Ys[i]
local axis, l = norm(cross({ 0, 1, 0 }, y))
local ang = math.acos(math.clamp(y[2], -1, 1))
Zs[i] = if l > 1e-12 then rotate({ 0, 0, 1 }, axis, ang) elseif y[2] < 0 then { 0, 0, -1 } else { 0, 0, 1 }
end
end
if i > 1 and Zs[i][1] * Zs[i - 1][1] + Zs[i][2] * Zs[i - 1][2] + Zs[i][3] * Zs[i - 1][3] < 0 then
Zs[i] = { -Zs[i][1], -Zs[i][2], -Zs[i][3] }
end
end
local nr = if closedSpine then ns - 1 else ns
local nring = if closedCs then nc - 1 else nc
local P = {}
for i = 1, nr do
local y, z = Ys[i], Zs[i]
local x = cross(y, z)
local si = if #sc >= i * 2 then i else 1
local sx, sz = sc[si * 2 - 1] or 1, sc[si * 2] or 1
local oi = if #ori >= i * 4 then i else 1
local ax, ang = norm({ ori[oi * 4 - 3] or 0, ori[oi * 4 - 2] or 0, ori[oi * 4 - 1] or 1 }), ori[oi * 4] or 0
for j = 1, nring do
local v = { cs[j * 2 - 1] * sx, 0, cs[j * 2] * sz }
if ang ~= 0 then
v = rotate(v, ax, ang)
end
local s = spine[i]
table.insert(P, s[1] + x[1] * v[1] + y[1] * v[2] + z[1] * v[3])
table.insert(P, s[2] + x[2] * v[1] + y[2] * v[2] + z[2] * v[3])
table.insert(P, s[3] + x[3] * v[1] + y[3] * v[2] + z[3] * v[3])
end
end
local corners, sizes = {}, {}
local function at(i: number, j: number): number
return ((i - 1) % nr) * nring + (j - 1) % nring
end
for i = 1, ns - 1 do
for j = 1, nc - 1 do
for _, c in { at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1) } do
table.insert(corners, c)
end
table.insert(sizes, 4)
end
end
if not closedSpine then
if bool(n, "beginCap", true) then
for j = 1, nring do
table.insert(corners, at(1, j))
end
table.insert(sizes, nring)
end
if bool(n, "endCap", true) then
for j = nring, 1, -1 do
table.insert(corners, at(ns, j))
end
table.insert(sizes, nring)
end
end
return polyMesh({ P = P, corners = corners, sizes = sizes, ccw = bool(n, "ccw", true) }, o, maxV)
end
-- ------------------------------------------------------------------------------------------------ lines, points
local function lines(n: any, maxV: number): (any, string?)
local P = points(n, "coord", "point") or {}
local np = #P // 3
local C, cc = colors(n)
local perVertex = bool(n, "colorPerVertex", true)
local runs: { { number } } = {}
if n.type == "LineSet" then
local at = 0
for _, c in nums(n, "vertexCount") or {} do
local r = {}
for q = 0, c - 1 do
r[q + 1] = at + q
end
at += c
table.insert(runs, r)
end
else
local corners, sizes = split(nums(n, "coordIndex") or {})
local k = 0
for _, s in sizes do
local r = {}
for q = 1, s do
r[q] = corners[k + q]
end
k += s
table.insert(runs, r)
end
end
local cIdx = nums(n, "colorIndex") or {}
local cList = if perVertex then cornerList(cIdx) else nil
local vkey: { [string]: number } = {}
local src: { { number } } = {}
local out: { number } = {}
local k = 0
for li, r in runs do
local prev: number? = nil
for _, c in r do
k += 1
if c == nil or c < 0 or c >= np then
prev = nil
continue
end
local ci = if not C then -1 elseif perVertex then (if cList then cList[k] or c else c) else (cIdx[li] or li - 1)
local key = c .. ":" .. ci
local v = vkey[key]
if not v then
v = #src
src[v + 1] = { c, ci }
vkey[key] = v
end
if prev then
table.insert(out, prev)
table.insert(out, v)
end
prev = v
end
end
if #src > maxV then
return nil, "limit: more than " .. maxV .. " vertices"
end
local pos = S.accessor(nil, "f32", 3, #src)
local col = if C then S.accessor(nil, "f32", cc, #src) else nil
for v, s in src do
for q = 0, 2 do
buffer.writef32(pos.data, ((v - 1) * 3 + q) * 4, P[s[1] * 3 + q + 1])
end
if col and C then
for q = 0, cc - 1 do
buffer.writef32(col.data, ((v - 1) * cc + q) * 4, C[s[2] * cc + q + 1] or 1)
end
end
end
return { attributes = { POSITION = pos, COLOR_0 = col } :: any, indices = u32(out), mode = "lines" }
end
local function pointSet(n: any, maxV: number): (any, string?)
local P = points(n, "coord", "point") or {}
local np = #P // 3
if np > maxV then
return nil, "limit: more than " .. maxV .. " points"
end
local C, cc = colors(n)
local attrs: { [string]: Types.Accessor } = { POSITION = f32(P, 3, np) }
if C then
local col = S.accessor(nil, "f32", cc, np)
for i = 0, np * cc - 1 do
buffer.writef32(col.data, i * 4, C[i + 1] or 1)
end
attrs.COLOR_0 = col
end
return { attributes = attrs, mode = "points" }
end
-- ------------------------------------------------------------------------------------------------ primitives
-- a primitive from flat arrays (positions, normals, uvs with the specification's bottom-left origin, triangles)
local function direct(P: { number }, N: { number }, T: { number }, I: { number }, o: Options): Types.Primitive
local nv = #P // 3
if o.flipV ~= false then
for i = 2, #T, 2 do
T[i] = 1 - T[i]
end
end
return {
attributes = { POSITION = f32(P, 3, nv), NORMAL = f32(N, 3, nv), TEXCOORD_0 = f32(T, 2, nv) },
indices = u32(I),
mode = "triangles",
}
end
local function box(n: any, o: Options): Types.Primitive
local s = vec(n, "size", { 2, 2, 2 })
local hx, hy, hz = s[1] / 2, s[2] / 2, s[3] / 2
local P, N, T, I = {}, {}, {}, {}
-- faces: normal, u axis, v axis (the specification's texture orientation)
local FACES = {
{ { 0, 0, 1 }, { 1, 0, 0 }, { 0, 1, 0 } }, { { 0, 0, -1 }, { -1, 0, 0 }, { 0, 1, 0 } },
{ { 1, 0, 0 }, { 0, 0, -1 }, { 0, 1, 0 } }, { { -1, 0, 0 }, { 0, 0, 1 }, { 0, 1, 0 } },
{ { 0, 1, 0 }, { 1, 0, 0 }, { 0, 0, -1 } }, { { 0, -1, 0 }, { 1, 0, 0 }, { 0, 0, 1 } },
}
for f, face in FACES do
local nn, u, v = face[1], face[2], face[3]
for _, c in { { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 } } do
for q = 1, 3 do
local h = if q == 1 then hx elseif q == 2 then hy else hz
table.insert(P, (nn[q] + u[q] * c[1] + v[q] * c[2]) * h)
table.insert(N, nn[q])
end
table.insert(T, (c[1] + 1) / 2)
table.insert(T, (c[2] + 1) / 2)
end
local b = (f - 1) * 4
for _, x in { 0, 1, 2, 0, 2, 3 } do
table.insert(I, b + x)
end
end
return direct(P, N, T, I, o)
end
-- a ring of segs + 1 vertices (the seam doubled for the texture) at height y, radius r; s starts at the back (-z)
-- and runs counter-clockwise seen from +y
local function ring(P: { number }, N: { number }?, T: { number }?, segs: number, y: number, r: number, t: number, ny: number?, nr: number?)
for i = 0, segs do
local a = 2 * pi * i / segs
local x, z = -sin(a), -cos(a)
table.insert(P, x * r)
table.insert(P, y)
table.insert(P, z * r)
if N then
table.insert(N, x * (nr or 1))
table.insert(N, ny or 0)
table.insert(N, z * (nr or 1))
end
if T then
table.insert(T, i / segs)
table.insert(T, t)
end
end
end
-- a cap disc at height y facing ny (+1 / -1)
local function cap(P: { number }, N: { number }, T: { number }, I: { number }, segs: number, y: number, r: number, ny: number)
local b = #P // 3
for i = 0, segs - 1 do
local a = 2 * pi * i / segs
local x, z = -sin(a), -cos(a)
table.insert(P, x * r)
table.insert(P, y)
table.insert(P, z * r)
table.insert(N, 0)
table.insert(N, ny)
table.insert(N, 0)
-- the specification maps the cap like a top view: s = x, t = -z (top) or z (bottom)
table.insert(T, x / 2 + 0.5)
table.insert(T, (if ny > 0 then -z else z) / 2 + 0.5)
end
for i = 1, segs - 2 do
-- the ring runs counter-clockwise seen from +y: in order for the top, reversed for the bottom
if ny > 0 then
table.insert(I, b)
table.insert(I, b + i)
table.insert(I, b + i + 1)
else
table.insert(I, b)
table.insert(I, b + i + 1)
table.insert(I, b + i)
end
end
end
-- quads between two rings of segs + 1 vertices starting at a (lower) and b (upper)
local function band(I: { number }, a: number, b: number, segs: number)
for i = 0, segs - 1 do
table.insert(I, a + i)
table.insert(I, a + i + 1)
table.insert(I, b + i + 1)
table.insert(I, a + i)
table.insert(I, b + i + 1)
table.insert(I, b + i)
end
end
local function sphere(n: any, o: Options, segs: number): Types.Primitive
local r = num(n, "radius", 1)
local rings = math.max(2, segs // 2)
local P, N, T, I = {}, {}, {}, {}
for j = 0, rings do
local phi = pi * j / rings -- from the bottom
local y, rr = -cos(phi), sin(phi)
ring(P, N, T, segs, y * r, rr * r, j / rings, y, rr)
end
for j = 0, rings - 1 do
band(I, j * (segs + 1), (j + 1) * (segs + 1), segs)
end
return direct(P, N, T, I, o)
end
local function cylinder(n: any, o: Options, segs: number, cone: boolean): Types.Primitive
local r = num(n, if cone then "bottomRadius" else "radius", 1)
local h = num(n, "height", 2)
local P, N, T, I = {}, {}, {}, {}
if bool(n, "side", true) then
-- side normals: a cone's lean outwards by its slope
local l = sqrt(r * r + h * h)
local ny, nr = if cone and l > 0 then r / l else 0, if cone and l > 0 then h / l else 1
ring(P, N, T, segs, -h / 2, r, 0, ny, nr)
ring(P, N, T, segs, h / 2, if cone then 0 else r, 1, ny, nr)
band(I, 0, segs + 1, segs)
end
if not cone and bool(n, "top", true) then
cap(P, N, T, I, segs, h / 2, r, 1)
end
if bool(n, "bottom", true) then
cap(P, N, T, I, segs, -h / 2, r, -1)
end
return direct(P, N, T, I, o)
end
-- ------------------------------------------------------------------------------------------------ dispatch
-- primitive(geometryNode, opts) -> Primitive | nil, message | nil, nil (a node type without geometry here);
-- the second value of a success is the node's solid flag
function Geometry.primitive(n: any, o: Options): (Types.Primitive?, any)
local t = n.type
local maxV = o.maxVertices or 2 ^ 24
local segs = math.clamp(math.floor(o.segments or 32), 3, 1024)
local solid = bool(n, "solid", true)
local prim: Types.Primitive?, err: string? = nil, nil
if t == "IndexedFaceSet" then
prim, err = faceSet(n, o, maxV)
elseif t == "IndexedTriangleSet" or t == "TriangleSet" or t == "IndexedTriangleFanSet" or t == "TriangleFanSet" or t == "IndexedTriangleStripSet" or t == "TriangleStripSet" or t == "IndexedQuadSet" or t == "QuadSet" then
prim, err = triSet(n, o, maxV)
elseif t == "ElevationGrid" then
prim, err = elevationGrid(n, o, maxV)
elseif t == "Extrusion" then
prim, err = extrusion(n, o, maxV)
elseif t == "IndexedLineSet" or t == "LineSet" then
prim, err = lines(n, maxV)
solid = false
elseif t == "PointSet" then
prim, err = pointSet(n, maxV)
solid = false
elseif t == "Box" then
prim = box(n, o)
elseif t == "Sphere" then
prim = sphere(n, o, segs)
elseif t == "Cylinder" then
prim = cylinder(n, o, segs, false)
elseif t == "Cone" then
prim = cylinder(n, o, segs, true)
else
return nil, nil
end
if not prim then
return nil, err
end
return prim, solid
end
return Geometry
+536
View File
@@ -0,0 +1,536 @@
--!strict
-- codecs/model/Vrml/Parse: the VRML97 (ISO/IEC 14772-1) / X3D classic VRML encoding (ISO/IEC 19776-2) parser, into
-- the node graph codecs/model/Vrml/Build reads. Written from the specifications; no third-party code. Field types are
-- not known without the node schemas, so a field value is kept as a flat array of what the file wrote (numbers,
-- strings, booleans, nodes) and the builder reads it as the type it expects. Handles comments, DEF / USE, PROTO
-- (instances are expanded: IS fields take the instance's values or the declared defaults; nested PROTOs, ROUTEs inside
-- bodies), EXTERNPROTO (instances stay nodes of that type, without a body), Script / shader interface declarations,
-- ROUTE, and the X3D header statements (PROFILE, COMPONENT, META, UNIT, IMPORT, EXPORT). Never throws: errors are
-- returned as nil, message ("line N: ...").
local Parse = {}
export type Node = { type: string, def: string?, fields: { [string]: any } }
export type Route = { from: Node, fromField: string, to: Node, toField: string }
export type Proto = { name: string, fields: { [string]: any }, body: { Node }, routes: { Route }, extern: boolean? }
export type Graph = {
roots: { Node },
routes: { Route },
header: { [string]: any }, -- version ("2.0" / "3.3" ...), encoding, x3d (boolean), profile
meta: { [string]: string }, -- META / WorldInfo statements
components: { string },
units: { [string]: { name: string, factor: number } },
protos: { [string]: Proto },
}
-- an IS reference in a PROTO body: fields[name] = { is = "protoField" }
export type IsRef = { is: string }
local find, sub, byte, match, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch
local ID1 = "^[^%c%s%d\"#',%+%-%.%[\\%]{}][^%c%s\"#',%.%[\\%]{}]*"
local MAX_DEPTH = 200
local DECL = { field = true, exposedField = true, eventIn = true, eventOut = true, initializeOnly = true, inputOutput = true, inputOnly = true, outputOnly = true }
local HAS_VALUE = { field = true, exposedField = true, initializeOnly = true, inputOutput = true }
-- copy(node, values, defaults, memo) -> a PROTO body node with its IS fields replaced (shared nodes stay shared)
local function copy(node: Node, values: { [string]: any }, defaults: { [string]: any }, memo: { [any]: any }): Node
local done = memo[node]
if done then
return done
end
local out: Node = { type = node.type, def = node.def, fields = {} }
memo[node] = out
for k, v in node.fields do
if type(v) == "table" and type((v :: any).is) == "string" then
local name = (v :: any).is
local val = values[name]
if val == nil then
val = defaults[name]
end
out.fields[k] = val
elseif type(v) == "table" then
local arr = table.create(#v)
for i, x in v do
arr[i] = if type(x) == "table" and x.type then copy(x, values, defaults, memo) else x
end
out.fields[k] = arr
else
out.fields[k] = v
end
end
return out
end
-- expand(proto, values, def, routes) -> the instance's node (the body's first node), or nil for an EXTERNPROTO
function Parse.expand(proto: Proto, values: { [string]: any }, def: string?, routes: { Route }?): Node?
if proto.extern or #proto.body == 0 then
return nil
end
local memo = {}
local first: Node? = nil
for _, n in proto.body do
local c = copy(n, values, proto.fields, memo)
first = first or c
end
if routes then
for _, r in proto.routes do
local from, to = memo[r.from], memo[r.to]
if from and to then
table.insert(routes, { from = from, fromField = r.fromField, to = to, toField = r.toField })
end
end
end
local f = first :: Node
if def then
-- the instance gets its own copy of the node so its DEF name is its own
local out: Node = { type = f.type, def = def, fields = f.fields }
return out
end
return f
end
function Parse.parse(text: string): (Graph?, string?)
local n = #text
local p = 1
local graph: Graph = { roots = {}, routes = {}, header = {}, meta = {}, components = {}, units = {}, protos = {} }
local defs: { [string]: Node } = {}
local protos: { [string]: Proto } = graph.protos
local routes: { Route } = graph.routes
local failure: string? = nil
local depth = 0
local function line(at: number): number
local l = 1
for _ in gmatch(sub(text, 1, at), "\n") do
l += 1
end
return l
end
local function fail(msg: string)
if not failure then
failure = "line " .. line(p) .. ": " .. msg
end
end
-- header line: #VRML V2.0 utf8 / #X3D V3.3 utf8
local v, enc = match(text, "^#VRML V(%S+) (%S+)")
if v then
graph.header.version, graph.header.encoding = v, enc
if v ~= "2.0" then
return nil, "unsupported: VRML " .. v .. " (only VRML97 / X3D)"
end
else
v, enc = match(text, "^#X3D V(%S+) (%S+)")
if v then
graph.header.version, graph.header.encoding, graph.header.x3d = v, enc, true
end
end
-- the lexer: skip blanks, commas and comments; returns the next token kind and value
-- kinds: "num", "str", "id", "{", "}", "[", "]", ".", "eof"
local function skip()
while true do
local q = find(text, "[^%s,]", p)
if not q then
p = n + 1
return
end
p = q
if byte(text, p) == 35 then -- '#'
local e = find(text, "[\r\n]", p)
p = if e then e else n + 1
else
return
end
end
end
local function token(): (string, any)
skip()
if p > n then
return "eof", nil
end
local c = byte(text, p)
if c == 123 or c == 125 or c == 91 or c == 93 then -- { } [ ]
p += 1
return string.char(c), nil
elseif c == 34 then -- a string: \" and \\ escapes
local q = p + 1
local parts = {}
while true do
local e = find(text, '["\\]', q)
if not e then
fail("unterminated string")
p = n + 1
return "eof", nil
end
table.insert(parts, sub(text, q, e - 1))
if byte(text, e) == 92 then
table.insert(parts, sub(text, e + 1, e + 1))
q = e + 2
else
p = e + 1
return "str", table.concat(parts)
end
end
end
if (c >= 48 and c <= 57) or c == 43 or c == 45 or c == 46 then
local s, e = find(text, "^[+-]?0[xX]%x+", p)
if not s then
s, e = find(text, "^[+-]?%d*%.?%d*[eE][+-]?%d+", p)
end
if not s then
s, e = find(text, "^[+-]?%d*%.?%d*", p)
end
local num = tonumber(sub(text, p, e))
if num then
p = (e :: number) + 1
return "num", num
end
if c == 46 then
p += 1
return ".", nil
end
-- +inf / -nan style words: read the word
local _, we = find(text, "^[^%s,%[%]{}#\"]+", p)
local w = sub(text, p, we)
p = (we :: number) + 1
local wl = string.lower(w)
local val = if find(wl, "inf", 1, true) then (if c == 45 then -math.huge else math.huge) elseif find(wl, "nan", 1, true) then 0 else nil
if val == nil then
fail("bad number " .. w)
return "eof", nil
end
return "num", val
end
local s, e = find(text, ID1, p)
if s then
p = (e :: number) + 1
return "id", sub(text, s, e)
end
fail("unexpected character " .. sub(text, p, p))
p = n + 1
return "eof", nil
end
local function peek(): (string, any)
local save = p
local k, val = token()
p = save
return k, val
end
local parseNode: (first: string) -> (Node?, boolean)
local parseProto: (extern: boolean) -> ()
local parseRoute: () -> ()
-- a field value (after its name): an array of numbers / strings / booleans / nodes
local function value(): any
local k, val = token()
if k == "[" then
local out = {}
-- fast path: a bracket of plain numbers (big coordinate arrays)
local close = find(text, "]", p, true)
if close then
local seg = sub(text, p, close - 1)
if not find(seg, "[{}\"#]") then
local ok = true
for w in gmatch(seg, "[^%s,]+") do
local x = tonumber(w)
if x then
table.insert(out, x)
elseif w == "TRUE" or w == "FALSE" then
table.insert(out, w == "TRUE")
else
ok = false
break
end
end
if ok then
p = close + 1
return out
end
table.clear(out)
end
end
while not failure do
k, val = token()
if k == "]" then
return out
elseif k == "num" or k == "str" then
table.insert(out, val)
elseif k == "id" and (val == "TRUE" or val == "FALSE") then
table.insert(out, val == "TRUE")
elseif k == "id" and val == "NULL" then
continue
elseif k == "id" then
local node = parseNode(val)
if node then
table.insert(out, node)
end
else
fail("unexpected " .. k .. " in a [ ] value")
return out
end
end
return out
elseif k == "num" then
local out = { val }
while true do
local save = p
local k2, v2 = token()
if k2 ~= "num" then
p = save
break
end
table.insert(out, v2)
end
return out
elseif k == "str" then
return { val }
elseif k == "id" then
if val == "TRUE" or val == "FALSE" then
return { val == "TRUE" }
elseif val == "NULL" then
return {}
end
local node = parseNode(val)
return if node then { node } else {}
end
fail("missing field value")
return {}
end
-- the fields of a node body, up to its "}"
local function body(node: Node)
while not failure do
local k, name = token()
if k == "}" then
return
elseif k ~= "id" then
fail("expected a field name in " .. node.type .. ", got " .. k)
return
end
if name == "ROUTE" then
parseRoute()
elseif name == "PROTO" or name == "EXTERNPROTO" then
parseProto(name == "EXTERNPROTO")
elseif DECL[name] then
-- Script / shader interface: <access> <type> <name> [<value> | IS <name>]
local _, _t = token()
local fk, fname = token()
if fk ~= "id" then
fail("bad interface declaration in " .. node.type)
return
end
local pk, pv = peek()
if pk == "id" and pv == "IS" then
token()
local _, ref = token()
node.fields[fname] = { is = ref }
elseif HAS_VALUE[name] then
node.fields[fname] = value()
end
else
local pk, pv = peek()
if pk == "id" and pv == "IS" then
token()
local _, ref = token()
node.fields[name] = { is = ref }
else
node.fields[name] = value()
end
end
end
end
-- a node statement starting with the id `first` (DEF name Type { }, USE name, Type { })
function parseNode(first: string): (Node?, boolean)
if first == "USE" then
local k, name = token()
if k ~= "id" then
fail("USE without a name")
return nil, false
end
local node = defs[name]
if not node then
fail("USE of an undefined name " .. tostring(name))
end
return node, true
end
local def: string? = nil
local typ = first
if first == "DEF" then
local k, name = token()
local k2, t2 = token()
if k ~= "id" or k2 ~= "id" then
fail("bad DEF")
return nil, false
end
def, typ = name, t2
end
local k = token()
if k ~= "{" then
fail("expected { after " .. typ)
return nil, false
end
depth += 1
if depth > MAX_DEPTH then
fail("limit: nodes nested deeper than " .. MAX_DEPTH)
return nil, false
end
local node: Node = { type = typ, def = def, fields = {} }
body(node)
depth -= 1
local proto = protos[typ]
if proto and not proto.extern then
local inst = Parse.expand(proto, node.fields, def, routes)
if inst then
node = inst
end
elseif proto then
(node :: any).extern = true
end
if def then
defs[def] = node
end
return node, false
end
-- ROUTE from.field TO to.field
function parseRoute()
local function path(): (string?, string?)
local k1, a = token()
local k2 = token()
local k3, b = token()
if k1 ~= "id" or k2 ~= "." or k3 ~= "id" then
return nil, nil
end
return a, b
end
local a, af = path()
local k, to = token()
local b, bf = path()
if not (a and af and b and bf) or k ~= "id" or to ~= "TO" then
fail("bad ROUTE")
return
end
local from, dst = defs[a :: string], defs[b :: string]
if from and dst then
table.insert(routes, { from = from, fromField = af :: string, to = dst, toField = bf :: string })
end
end
-- PROTO name [ interface ] { body } / EXTERNPROTO name [ interface ] url
function parseProto(extern: boolean)
local k, name = token()
if k ~= "id" or token() ~= "[" then
fail("bad PROTO")
return
end
local proto: Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil }
while not failure do
local k2, access = token()
if k2 == "]" then
break
elseif k2 ~= "id" or not DECL[access] then
fail("bad PROTO interface")
return
end
local _, _t = token()
local fk, fname = token()
if fk ~= "id" then
fail("bad PROTO interface")
return
end
if HAS_VALUE[access] and not extern then
proto.fields[fname] = value()
end
end
if extern then
value() -- the url list
protos[name] = proto
return
end
if token() ~= "{" then
fail("PROTO " .. tostring(name) .. " without a body")
return
end
-- the body has its own DEF names and its own routes
local outerDefs, outerRoutes = defs, routes
defs, routes = {}, proto.routes
while not failure do
local k3, w = token()
if k3 == "}" then
break
elseif k3 ~= "id" then
fail("bad PROTO body")
break
elseif w == "ROUTE" then
parseRoute()
elseif w == "PROTO" or w == "EXTERNPROTO" then
parseProto(w == "EXTERNPROTO")
else
local node = parseNode(w)
if node then
table.insert(proto.body, node)
end
end
end
defs, routes = outerDefs, outerRoutes
protos[name] = proto
end
-- statements
while not failure do
local k, w = token()
if k == "eof" then
break
elseif k ~= "id" then
fail("unexpected " .. k)
break
end
if w == "ROUTE" then
parseRoute()
elseif w == "PROTO" or w == "EXTERNPROTO" then
parseProto(w == "EXTERNPROTO")
elseif w == "PROFILE" then
local _, prof = token()
graph.header.profile = prof
elseif w == "COMPONENT" then
local _, comp = token() -- name:level is one id
table.insert(graph.components, tostring(comp))
elseif w == "META" then
local _, key = token()
local _, val = token()
graph.meta[tostring(key)] = tostring(val)
elseif w == "UNIT" then
local _, cat = token()
local _, uname = token()
local _, factor = token()
if type(cat) == "string" and type(factor) == "number" then
graph.units[cat] = { name = tostring(uname), factor = factor }
end
elseif w == "IMPORT" or w == "EXPORT" then
-- IMPORT inline.name AS name / EXPORT name AS name: no effect on the scene
local _, _a = token()
if peek() == "." then
token()
token()
end
local pk, pv = peek()
if pk == "id" and pv == "AS" then
token()
token()
end
else
local node = parseNode(w)
if node then
table.insert(graph.roots, node)
end
end
end
if failure then
return nil, failure
end
return graph, nil
end
return Parse
+750
View File
@@ -0,0 +1,750 @@
--!strict
-- codecs/model/Vrml/Write: a Scene to VRML97 (`#VRML V2.0 utf8`), X3D classic (`#X3D V3.3 utf8`) or X3D XML text,
-- for model/vrml and model/x3d. New code. Every node becomes a DEF'd Transform (a matrix is decomposed into TRS;
-- shear is lost), each primitive a Shape: triangles / polygons / strips / fans -> IndexedFaceSet (coord, normal,
-- texCoord with t flipped back unless flipV = false, color; per-vertex, ccw, solid = not doubleSided), lines ->
-- IndexedLineSet, points -> PointSet; a mesh used twice is written once and USE'd. Materials -> Appearance / Material
-- (diffuse = baseColor, transparency = 1 - alpha, emissive, shininess from roughness, the Phong terms of
-- material.extras.vrml when present) with an ImageTexture (the texture bytes go into opts.files named after the uri or
-- opts.name, else url = texture.uri). Cameras -> Viewpoint (X3D: OrthoViewpoint for orthographic ones), lights ->
-- Directional / Point / SpotLight, animations (translation / rotation / scale channels) -> a TimeSensor and
-- Position / OrientationInterpolators with ROUTEs (cubic splines keep their values, weights channels are dropped).
-- Never throws: returns nil, message.
local Types = require("@formats/Types")
local Mat4 = require("@formats/codecs/model/Mat4")
local Flatten = require("@formats/codecs/model/MeshFlatten")
local Xml = require("@formats/codecs/text/Xml")
local Write = {}
export type Options = { encoding: ("vrml97" | "x3dv" | "xml")?, files: { [string]: any }?, name: string?, flipV: boolean? }
-- a written node: fields in order, each { name, kind, value }; kinds: "sf" / "mf" (numbers; mf groups `per` numbers
-- per line), "bool", "str", "mstr" (MFString), "node", "nodes"
type WNode = { type: string, def: string?, use: string?, fields: { { any } } }
local format, concat = string.format, table.concat
local function fmt(v: number): string
if v ~= v then
return "0"
elseif v == math.huge then
return "1e38"
elseif v == -math.huge then
return "-1e38"
elseif v == math.floor(v) and math.abs(v) < 2 ^ 53 then
return format("%d", v)
end
return format("%.9g", v)
end
local function W(t: string, def: string?): WNode
return { type = t, def = def, fields = {} }
end
local function F(n: WNode, name: string, kind: string, value: any, per: number?)
table.insert(n.fields, { name, kind, value, per })
end
-- names: valid, unique DEF names
local function namer(): (string?, string) -> string
local used: { [string]: boolean } = {}
return function(name: string?, fallback: string): string
local s = string.gsub(name or "", "[^%w_]", "_")
if s == "" or string.find(s, "^%d") then
s = fallback .. (if s ~= "" then "_" .. s else "")
end
local base, k = s, 1
while used[s] do
k += 1
s = base .. "_" .. k
end
used[s] = true
return s
end
end
-- axis-angle of a quaternion (x, y, z, w)
local function axisAngle(q: { number }): { number }
local x, y, z, w = q[1], q[2], q[3], q[4]
local l = math.sqrt(x * x + y * y + z * z + w * w)
if l > 0 then
x, y, z, w = x / l, y / l, z / l, w / l
end
local s = math.sqrt(math.max(0, 1 - w * w))
if s < 1e-9 then
return { 0, 0, 1, 0 }
end
return { x / s, y / s, z / s, 2 * math.acos(math.clamp(w, -1, 1)) }
end
-- ------------------------------------------------------------------------------------------------ geometry
local function values(acc: any): { number }?
return (Flatten.numbers(acc))
end
local function faceSet(prim: any, doubleSided: boolean, o: Options, x3d: boolean): (WNode?, string?)
local tmp = { kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } }
local keep = function(n: string): boolean
return n == "NORMAL" or n == "TEXCOORD_0" or n == "COLOR_0"
end
local m, err = Flatten.merge(tmp, keep, { triangulate = false })
if not m then
return nil, err
end
if not m.sizes or #m.sizes == 0 then
return nil, nil
end
local g = W("IndexedFaceSet")
local coord = W("Coordinate")
F(coord, "point", "mf", m.attrs.POSITION.values, 3)
F(g, "coord", "node", coord)
local idx = {}
local p = 0
for _, s in m.sizes do
for k = 1, s do
table.insert(idx, m.corners[p + k])
end
table.insert(idx, -1)
p += s
end
F(g, "coordIndex", "mf", idx, 0)
local nrm = m.attrs.NORMAL
if nrm then
local nn = W("Normal")
F(nn, "vector", "mf", nrm.values, 3)
F(g, "normal", "node", nn)
end
local tc = m.attrs.TEXCOORD_0
if tc then
local t = W("TextureCoordinate")
local vals, c = {}, tc.components
for i = 0, m.count - 1 do
local s, tt = tc.values[i * c + 1], tc.values[i * c + 2]
table.insert(vals, s)
table.insert(vals, if o.flipV ~= false then 1 - tt else tt)
end
F(t, "point", "mf", vals, 2)
F(g, "texCoord", "node", t)
end
local col = m.attrs.COLOR_0
if col then
local c = col.components
local rgba = c >= 4 and x3d
local cn = W(if rgba then "ColorRGBA" else "Color")
local vals = {}
local scale = if col.raw then (if col.type == "unorm8" then 255 elseif col.type == "unorm16" then 65535 else 1) else 1
for i = 0, m.count - 1 do
for k = 1, if rgba then 4 else 3 do
table.insert(vals, (col.values[i * c + k] or 1) / scale)
end
end
F(cn, "color", "mf", vals, if rgba then 4 else 3)
F(g, "color", "node", cn)
end
F(g, "solid", "bool", not doubleSided)
return g, nil
end
-- Coordinate from POSITION, Color / ColorRGBA from COLOR_0 (lines and points)
local function coordNode(prim: any): (WNode?, number)
local pos = values(prim.attributes.POSITION)
if not pos then
return nil, 0
end
local nv, pc = prim.attributes.POSITION.count, prim.attributes.POSITION.components
local p3 = {}
for i = 0, nv - 1 do
for k = 1, 3 do
table.insert(p3, pos[i * pc + k] or 0)
end
end
local coord = W("Coordinate")
F(coord, "point", "mf", p3, 3)
return coord, nv
end
local function colorNode(prim: any, nv: number, x3d: boolean): WNode?
local acc = prim.attributes.COLOR_0
local col = acc and values(acc)
if not col then
return nil
end
local c = acc.components
local rgba = c >= 4 and x3d
local vals = {}
for i = 0, nv - 1 do
for k = 1, if rgba then 4 else 3 do
table.insert(vals, col[i * c + k] or 1)
end
end
local cn = W(if rgba then "ColorRGBA" else "Color")
F(cn, "color", "mf", vals, if rgba then 4 else 3)
return cn
end
local function lineSet(prim: any, x3d: boolean): (WNode?, string?)
local coord, nv = coordNode(prim)
if not coord then
return nil, "lines without POSITION"
end
local ind: { number }
if prim.indices then
ind = values(prim.indices) or {}
else
ind = {}
for i = 0, nv - 1 do
ind[i + 1] = i
end
end
local idx = {}
local mode = prim.mode
if mode == "lines" then
for i = 1, #ind - 1, 2 do
table.insert(idx, ind[i])
table.insert(idx, ind[i + 1])
table.insert(idx, -1)
end
else
for _, v in ind do
table.insert(idx, v)
end
if mode == "line_loop" and #ind > 0 then
table.insert(idx, ind[1])
end
table.insert(idx, -1)
end
for _, v in idx do
if v >= nv then
return nil, "line index out of range"
end
end
local g = W("IndexedLineSet")
F(g, "coord", "node", coord)
local cn = colorNode(prim, nv, x3d)
if cn then
F(g, "color", "node", cn)
end
F(g, "coordIndex", "mf", idx, 0)
return g, nil
end
local function pointSet(prim: any, x3d: boolean): (WNode?, string?)
local coord, nv = coordNode(prim)
if not coord then
return nil, "points without POSITION"
end
local g = W("PointSet")
F(g, "coord", "node", coord)
local cn = colorNode(prim, nv, x3d)
if cn then
F(g, "color", "node", cn)
end
return g, nil
end
-- ------------------------------------------------------------------------------------------------ materials
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/gif"] = "gif", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2" }
local function textureUrl(scene: any, i: number, o: Options, written: { [number]: string }): string?
if written[i] then
return written[i]
end
local tex = scene.textures[i]
if not tex then
return nil
end
local url = tex.uri
if tex.data and type(o.files) == "table" then
local base = string.match(o.name or "model", "([^/\\]+)$") or "model"
base = string.gsub(base, "%.[^.]*$", "")
local ext = EXT[tex.mime or ""] or (url and string.match(url, "%.(%w+)$")) or "png"
local file = if url and not string.find(url, "^data:") and not string.find(url, "[/\\]") then url else format("%s_%d.%s", base, i, ext)
o.files[file] = tex.data
url = file
end
if url then
written[i] = url
end
return url
end
local function appearance(scene: any, mi: number, o: Options, written: { [number]: string }): WNode
local m = scene.materials[mi]
local app = W("Appearance")
local mat = W("Material")
local x = m.extras and m.extras.vrml or {}
local c = m.baseColor or { 1, 1, 1, 1 }
F(mat, "diffuseColor", "sf", { c[1], c[2], c[3] })
local e = m.emissive or { 0, 0, 0 }
if e[1] ~= 0 or e[2] ~= 0 or e[3] ~= 0 then
F(mat, "emissiveColor", "sf", { e[1], e[2], e[3] })
end
if type(x.specularColor) == "table" then
F(mat, "specularColor", "sf", x.specularColor)
end
local sh = x.shininess
if type(sh) ~= "number" then
local r = math.max(m.roughness or 1, 1e-3)
sh = math.clamp((2 / (r * r) - 2) / 128, 0, 1)
end
F(mat, "shininess", "sf", { sh })
if type(x.ambientIntensity) == "number" then
F(mat, "ambientIntensity", "sf", { x.ambientIntensity })
end
if (c[4] or 1) < 1 then
F(mat, "transparency", "sf", { 1 - c[4] })
end
F(app, "material", "node", mat)
local ref = m.baseColorTexture
if ref and type(ref.texture) == "number" then
local url = textureUrl(scene, ref.texture, o, written)
local img = scene.textures[ref.texture] and scene.textures[ref.texture].image
if url or (img and img.format == "rgba8" and img.width * img.height <= 2 ^ 20) then
local it
if url then
it = W("ImageTexture")
F(it, "url", "mstr", { url })
else
-- a decoded image only: PixelTexture (SFImage: width height 4, then 0xRRGGBBAA from the bottom row up)
it = W("PixelTexture")
local w, h = img.width, img.height
local v = { w, h, 4 }
for row = h - 1, 0, -1 do
for x = 0, w - 1 do
table.insert(v, buffer.readu32(img.pixels, (row * w + x) * 4))
end
end
-- the pixels are little-endian RGBA bytes: swap to 0xRRGGBBAA
for i = 4, #v do
local p = v[i]
v[i] = (p % 256) * 16777216 + (p // 256 % 256) * 65536 + (p // 65536 % 256) * 256 + p // 16777216
end
F(it, "image", "sf", v)
end
local s = scene.textures[ref.texture].sampler
if s and s.wrapS == "clamp" then
F(it, "repeatS", "bool", false)
end
if s and s.wrapT == "clamp" then
F(it, "repeatT", "bool", false)
end
F(app, "texture", "node", it)
local tf = ref.transform
if tf then
local tt = W("TextureTransform")
if tf.offset then
F(tt, "translation", "sf", tf.offset)
end
if tf.scale then
F(tt, "scale", "sf", tf.scale)
end
if tf.rotation then
F(tt, "rotation", "sf", { tf.rotation })
end
F(app, "textureTransform", "node", tt)
end
end
end
return app
end
-- ------------------------------------------------------------------------------------------------ the tree
function Write.graph(scene: any, o: Options): ({ WNode }?, { { string } }?, string?)
local x3d = o.encoding == "x3dv" or o.encoding == "xml"
local name = namer()
local nodeDef: { [number]: string } = {}
local meshShapes: { [number]: { WNode } } = {}
local appDef: { [any]: string } = {}
local written: { [number]: string } = {}
local failure: string? = nil
local function shapes(mi: number): { WNode }
local done = meshShapes[mi]
if done then
-- USE the shapes written before
local out = {}
for _, s in done do
table.insert(out, { type = "Shape", use = s.def, fields = {} })
end
return out
end
local mesh = scene.meshes[mi]
local out = {}
for pi, prim in (if mesh then mesh.primitives else {}) :: { any } do
local mode = prim.mode or "triangles"
local mat = if type(prim.material) == "number" then scene.materials[prim.material] else nil
local geo, err
if mode == "lines" or mode == "line_strip" or mode == "line_loop" then
geo, err = lineSet(prim, x3d)
elseif mode == "points" then
geo, err = pointSet(prim, x3d)
else
geo, err = faceSet(prim, mat ~= nil and mat.doubleSided == true, o, x3d)
end
if err then
failure = failure or err
end
if geo then
local sh = W("Shape", name((mesh.name or "mesh") .. (if #mesh.primitives > 1 then "_" .. pi else ""), "Shape"))
if mat then
local key = prim.material
if appDef[key] then
F(sh, "appearance", "node", { type = "Appearance", use = appDef[key], fields = {} })
else
local app = appearance(scene, prim.material, o, written)
app.def = name(mat.name, "Material")
appDef[key] = app.def
F(sh, "appearance", "node", app)
end
end
F(sh, "geometry", "node", geo)
table.insert(out, sh)
end
end
meshShapes[mi] = out
return out
end
local visiting: { [number]: boolean } = {}
local function transform(ni: number): WNode?
local n = scene.nodes[ni]
if type(n) ~= "table" or visiting[ni] then
return nil
end
visiting[ni] = true
local def = name(n.name, "Node")
nodeDef[ni] = def
local t = W("Transform", def)
local tr, rot, sc = n.translation, n.rotation, n.scale
if n.matrix then
tr, rot, sc = Mat4.decompose(n.matrix)
end
if tr and (tr[1] ~= 0 or tr[2] ~= 0 or tr[3] ~= 0) then
F(t, "translation", "sf", { tr[1], tr[2], tr[3] })
end
if rot then
local aa = axisAngle(rot)
if aa[4] ~= 0 then
F(t, "rotation", "sf", aa)
end
end
if sc and (sc[1] ~= 1 or sc[2] ~= 1 or sc[3] ~= 1) then
F(t, "scale", "sf", { sc[1], sc[2], sc[3] })
end
local kids: { WNode } = {}
if type(n.mesh) == "number" then
for _, s in shapes(n.mesh) do
table.insert(kids, s)
end
end
local cam = if type(n.camera) == "number" then scene.cameras[n.camera] else nil
if cam then
local v
if cam.type == "orthographic" and x3d then
v = W("OrthoViewpoint")
local xm, ym = cam.xmag or 1, cam.ymag or 1
F(v, "fieldOfView", "sf", { -xm, -ym, xm, ym })
else
v = W("Viewpoint")
F(v, "fieldOfView", "sf", { cam.yfov or 0.785398 })
end
F(v, "position", "sf", { 0, 0, 0 })
if cam.name then
F(v, "description", "str", cam.name)
end
table.insert(kids, v)
end
local l = if type(n.light) == "number" then scene.lights[n.light] else nil
if l then
local typ = if l.type == "directional" then "DirectionalLight" elseif l.type == "spot" then "SpotLight" else "PointLight"
local ln = W(typ)
local c = l.color or { 1, 1, 1 }
F(ln, "color", "sf", { c[1], c[2], c[3] })
F(ln, "intensity", "sf", { math.clamp(l.intensity or 1, 0, 1) })
if typ ~= "PointLight" then
F(ln, "direction", "sf", { 0, 0, -1 })
end
if typ ~= "DirectionalLight" then
F(ln, "location", "sf", { 0, 0, 0 })
F(ln, "radius", "sf", { l.range or 100 })
end
if typ == "SpotLight" then
F(ln, "cutOffAngle", "sf", { l.outerCone or 0.785398 })
F(ln, "beamWidth", "sf", { l.innerCone or 0 })
end
table.insert(kids, ln)
end
for _, c in n.children or {} do
local ct = transform(c)
if ct then
table.insert(kids, ct)
end
end
if #kids > 0 then
F(t, "children", "nodes", kids)
end
visiting[ni] = nil
return t
end
local roots: { WNode } = {}
local list = scene.roots
if type(list) ~= "table" or #list == 0 then
-- no roots: every node without a parent
local child = {}
for _, n in scene.nodes do
for _, c in n.children or {} do
child[c] = true
end
end
list = {}
for i = 1, #scene.nodes do
if not child[i] then
table.insert(list, i)
end
end
end
for _, ri in list do
local t = transform(ri)
if t then
table.insert(roots, t)
end
end
if #scene.nodes == 0 then
for mi = 1, #scene.meshes do
for _, s in shapes(mi) do
table.insert(roots, s)
end
end
end
-- animations: a TimeSensor per animation, an interpolator per channel
local routes: { { string } } = {}
for ai, anim in scene.animations or {} do
local tmax = 0
local chans = {}
for _, ch in anim.channels or {} do
local target = nodeDef[ch.node]
if target and (ch.path == "translation" or ch.path == "rotation" or ch.path == "scale") then
local input, output = values(ch.input), values(ch.output)
if input and output and #input > 0 then
tmax = math.max(tmax, input[#input])
table.insert(chans, { ch, target, input, output })
end
end
end
if #chans > 0 then
local cycle = if tmax > 0 then tmax else 1
local ts = W("TimeSensor", name(anim.name, "Animation" .. ai))
F(ts, "cycleInterval", "sf", { cycle })
F(ts, "loop", "bool", true)
table.insert(roots, ts)
for k, c in chans do
local ch, target, input, output = c[1], c[2], c[3], c[4]
local rot = ch.path == "rotation"
local it = W(if rot then "OrientationInterpolator" else "PositionInterpolator", name(ts.def .. "_" .. k, "Interpolator"))
local keys = {}
for i, tv in input do
keys[i] = tv / cycle
end
local comps = if rot then 4 else 3
local stride = #output // #input
-- CUBICSPLINE stores in-tangent, value, out-tangent per key
local off = if ch.interpolation == "CUBICSPLINE" and stride == comps * 3 then comps else 0
local kv = {}
for i = 0, #input - 1 do
local v = {}
for q = 1, comps do
v[q] = output[i * stride + off + q] or 0
end
if rot then
v = axisAngle(v)
end
for _, x in v do
table.insert(kv, x)
end
end
F(it, "key", "mf", keys, 0)
F(it, "keyValue", "mf", kv, comps)
table.insert(roots, it)
table.insert(routes, { ts.def :: string, "fraction_changed", it.def :: string, "set_fraction" })
table.insert(routes, { it.def :: string, "value_changed", target, "set_" .. ch.path })
end
end
end
if failure then
return nil, nil, failure
end
return roots, routes, nil
end
-- ------------------------------------------------------------------------------------------------ serializers
local function numbers(vals: { number }, per: number?, indent: string): string
local out = table.create(#vals)
for i, v in vals do
out[i] = fmt(v)
end
if per == 0 then
-- index lists: one face per line
local lines, cur = {}, {}
for i, v in vals do
table.insert(cur, out[i])
if v == -1 then
table.insert(lines, concat(cur, " "))
cur = {}
end
end
if #cur > 0 then
table.insert(lines, concat(cur, " "))
end
return concat(lines, "\n" .. indent)
end
if per and per > 0 then
local lines = {}
for i = 1, #out, per do
table.insert(lines, concat(out, " ", i, math.min(i + per - 1, #out)))
end
return concat(lines, ",\n" .. indent)
end
return concat(out, " ")
end
local function quote(s: string): string
return '"' .. string.gsub(s, '(["\\])', "\\%1") .. '"'
end
local function classic(roots: { WNode }, routes: { { string } }, x3d: boolean): string
local out = {}
if x3d then
table.insert(out, "#X3D V3.3 utf8\nPROFILE Interchange\n# written by formats-luau\n")
else
table.insert(out, "#VRML V2.0 utf8\n# written by formats-luau\n")
end
local function emit(n: WNode, ind: string): string
if n.use then
return "USE " .. n.use
end
local parts = { (if n.def then "DEF " .. n.def .. " " else "") .. n.type .. " {" }
local ind2 = ind .. " "
for _, f in n.fields do
local fname, kind, v, per = f[1], f[2], f[3], f[4]
local s
if kind == "sf" then
s = numbers(v, nil, ind2)
elseif kind == "mf" then
s = "[\n" .. ind2 .. " " .. numbers(v, per, ind2 .. " ") .. "\n" .. ind2 .. "]"
elseif kind == "bool" then
s = if v then "TRUE" else "FALSE"
elseif kind == "str" then
s = quote(v)
elseif kind == "mstr" then
local q = {}
for i, x in v do
q[i] = quote(x)
end
s = "[ " .. concat(q, " ") .. " ]"
elseif kind == "node" then
s = emit(v, ind2)
else
local q = {}
for i, x in v do
q[i] = ind2 .. " " .. emit(x, ind2 .. " ")
end
s = "[\n" .. concat(q, "\n") .. "\n" .. ind2 .. "]"
end
table.insert(parts, ind2 .. fname .. " " .. s)
end
table.insert(parts, ind .. "}")
return concat(parts, "\n")
end
for _, r in roots do
table.insert(out, emit(r, ""))
end
for _, r in routes do
table.insert(out, format("ROUTE %s.%s TO %s.%s", r[1], r[2], r[3], r[4]))
end
return concat(out, "\n") .. "\n"
end
-- the containerField a child element needs when it is not its type's default
local DEFAULT = { Appearance = "appearance", Material = "material", ImageTexture = "texture", TextureTransform = "textureTransform", Coordinate = "coord", Normal = "normal", Color = "color", ColorRGBA = "color", TextureCoordinate = "texCoord", IndexedFaceSet = "geometry", IndexedLineSet = "geometry", PointSet = "geometry" }
local function xml(roots: { WNode }, routes: { { string } }): (string?, string?)
local function element(n: WNode, field: string): any
local attrs = Types.object()
local kids = {}
if (DEFAULT[n.type] or "children") ~= field then
Types.set(attrs, "containerField", field)
end
if n.use then
Types.set(attrs, "USE", n.use)
return Xml.element(n.type, attrs :: any)
end
if n.def then
Types.set(attrs, "DEF", n.def)
end
for _, f in n.fields do
local fname, kind, v, per = f[1], f[2], f[3], f[4]
if kind == "sf" then
Types.set(attrs, fname, numbers(v, nil, ""))
elseif kind == "mf" then
local s = numbers(v, per, "")
Types.set(attrs, fname, (string.gsub(s, "\n", " ")))
elseif kind == "bool" then
Types.set(attrs, fname, if v then "true" else "false")
elseif kind == "str" then
Types.set(attrs, fname, v)
elseif kind == "mstr" then
local q = {}
for i, x in v do
q[i] = quote(x)
end
Types.set(attrs, fname, concat(q, " "))
elseif kind == "node" then
table.insert(kids, element(v, fname))
else
for _, x in v do
table.insert(kids, element(x, fname))
end
end
end
return Xml.element(n.type, attrs :: any, kids)
end
local sceneKids = {}
for _, r in roots do
table.insert(sceneKids, element(r, "children"))
end
for _, r in routes do
local a = Types.object()
Types.set(a, "fromNode", r[1])
Types.set(a, "fromField", r[2])
Types.set(a, "toNode", r[3])
Types.set(a, "toField", r[4])
table.insert(sceneKids, Xml.element("ROUTE", a :: any))
end
local ra = Types.object()
Types.set(ra, "profile", "Interchange")
Types.set(ra, "version", "3.3")
local meta = Types.object()
Types.set(meta, "name", "generator")
Types.set(meta, "content", "formats-luau")
local root = Xml.element("X3D", ra :: any, { Xml.element("head", nil, { Xml.element("meta", meta :: any) }), Xml.element("Scene", nil, sceneKids) })
local s, err = Xml.encode(Xml.document(root, { version = "1.0", encoding = "UTF-8" }), { indent = 2 })
if not s then
return nil, if err then err.message else "xml"
end
return s, nil
end
-- text(scene, opts) -> the file text
function Write.text(scene: any, o: Options): (string?, string?)
local roots, routes, err = Write.graph(scene, o)
if not roots or not routes then
return nil, err
end
if o.encoding == "xml" then
return xml(roots, routes)
end
return classic(roots, routes, o.encoding == "x3dv"), nil
end
return Write
+238
View File
@@ -0,0 +1,238 @@
--!strict
-- codecs/model/Vrml/Xml: the X3D XML encoding (ISO/IEC 19776-1) to the node graph of codecs/model/Vrml/Parse, so one
-- builder serves .wrl, .x3dv and .x3d. Written from the specification; no third-party code. Elements are nodes;
-- attributes stay raw strings (the builder parses them as the type it expects); child nodes go into their
-- containerField (or the default field of their type: geometry, appearance, material, coord, ...); DEF / USE; ROUTE;
-- ProtoDeclare (ProtoInterface fields with value attributes or child nodes, ProtoBody, IS / connect) and
-- ProtoInstance (fieldValue) are expanded through Parse.expand; ExternProtoDeclare instances stay plain nodes; head /
-- meta, UNIT, component and the profile go into the graph header. Never throws.
local Xml = require("@formats/codecs/text/Xml")
local Parse = require("@formats/codecs/model/Vrml/Parse")
local VXml = {}
local GEOMETRY = {
"Box", "Sphere", "Cone", "Cylinder", "IndexedFaceSet", "IndexedLineSet", "LineSet", "PointSet", "ElevationGrid",
"Extrusion", "Text", "IndexedTriangleSet", "TriangleSet", "IndexedTriangleFanSet", "TriangleFanSet",
"IndexedTriangleStripSet", "TriangleStripSet", "IndexedQuadSet", "QuadSet", "Arc2D", "ArcClose2D", "Circle2D",
"Disk2D", "Polyline2D", "Polypoint2D", "Rectangle2D", "TriangleSet2D", "GeoElevationGrid", "NurbsPatchSurface",
}
local CONTAINER: { [string]: string } = {
Appearance = "appearance", Material = "material", PhysicalMaterial = "material", TwoSidedMaterial = "material",
UnlitMaterial = "material", ImageTexture = "texture", PixelTexture = "texture", MovieTexture = "texture",
MultiTexture = "texture", ImageCubeMapTexture = "texture", TextureTransform = "textureTransform",
Coordinate = "coord", CoordinateDouble = "coord", Normal = "normal", Color = "color", ColorRGBA = "color",
TextureCoordinate = "texCoord", MultiTextureCoordinate = "texCoord", TextureCoordinateGenerator = "texCoord",
FontStyle = "fontStyle", TextureProperties = "textureProperties", FillProperties = "fillProperties",
LineProperties = "lineProperties",
}
for _, g in GEOMETRY do
CONTAINER[g] = "geometry"
end
local function container(el: Xml.Node, typ: string): string
local c = el.attrs.containerField
if type(c) == "string" and c ~= "" then
return c
end
if string.sub(typ, 1, 8) == "Metadata" then
return "metadata"
end
return CONTAINER[typ] or "children"
end
function VXml.graph(doc: Xml.Node): (Parse.Graph?, string?)
local root = doc.root or doc
if type(root) ~= "table" or Xml.localName(root.name) ~= "X3D" then
return nil, "no <X3D> root element"
end
local graph: Parse.Graph = { roots = {}, routes = {}, header = { x3d = true, xml = true }, meta = {}, components = {}, units = {}, protos = {} }
graph.header.version, graph.header.profile = root.attrs.version, root.attrs.profile
local defs: { [string]: Parse.Node } = {}
local protos = graph.protos
local routes = graph.routes
local depth = 0
local failure: string? = nil
local convert: (el: Xml.Node) -> Parse.Node?
local function route(el: Xml.Node)
local a = el.attrs
local from, to = defs[a.fromNode or ""], defs[a.toNode or ""]
local ff, tf = a.fromField, a.toField
if from and to and type(ff) == "string" and type(tf) == "string" then
table.insert(routes, { from = from, fromField = ff, to = to, toField = tf })
end
end
local declare: (el: Xml.Node, extern: boolean) -> ()
-- the child elements of a node into its fields
local function children(el: Xml.Node, node: Parse.Node)
for _, ch in el.children do
if type(ch) ~= "table" or string.sub(ch.name, 1, 1) == "#" then
continue
end
local name = Xml.localName(ch.name)
if name == "ROUTE" then
route(ch)
elseif name == "IS" then
for _, c in Xml.children(ch, "connect") do
local nf, pf = c.attrs.nodeField, c.attrs.protoField
if nf and pf then
node.fields[nf] = { is = pf }
end
end
elseif name == "ProtoDeclare" or name == "ExternProtoDeclare" then
declare(ch, name == "ExternProtoDeclare")
elseif name == "field" or name == "fieldValue" then
continue -- Script / shader interfaces
else
local c = convert(ch)
if c then
local f = container(ch, if name == "ProtoInstance" then "" else name)
local list = node.fields[f]
if type(list) ~= "table" or (list :: any).is then
list = {}
node.fields[f] = list
end
table.insert(list, c)
end
end
end
end
-- a field value of ProtoInterface / fieldValue: the value attribute, or the child nodes
local function fieldValue(el: Xml.Node): any
if el.attrs.value ~= nil then
return el.attrs.value
end
local list = {}
for _, ch in el.children do
if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then
local c = convert(ch)
if c then
table.insert(list, c)
end
end
end
return list
end
function declare(el: Xml.Node, extern: boolean)
local name = el.attrs.name
if not name then
return
end
local proto: Parse.Proto = { name = name, fields = {}, body = {}, routes = {}, extern = extern or nil }
local iface = if extern then el else Xml.child(el, "ProtoInterface")
if iface then
for _, f in Xml.children(iface, "field") do
if f.attrs.name then
proto.fields[f.attrs.name] = fieldValue(f)
end
end
end
local bodyEl = Xml.child(el, "ProtoBody")
if bodyEl and not extern then
local outerDefs, outerRoutes = defs, routes
defs, routes = {}, proto.routes
for _, ch in bodyEl.children do
if type(ch) == "table" and string.sub(ch.name, 1, 1) ~= "#" then
local nm = Xml.localName(ch.name)
if nm == "ROUTE" then
route(ch)
elseif nm == "ProtoDeclare" or nm == "ExternProtoDeclare" then
declare(ch, nm == "ExternProtoDeclare")
else
local c = convert(ch)
if c then
table.insert(proto.body, c)
end
end
end
end
defs, routes = outerDefs, outerRoutes
end
protos[name] = proto
end
function convert(el: Xml.Node): Parse.Node?
local a = el.attrs
if a.USE then
return defs[a.USE]
end
depth += 1
if depth > 200 then
failure = failure or "limit: nodes nested deeper than 200"
depth -= 1
return nil
end
local typ = Xml.localName(el.name)
local node: any
if typ == "ProtoInstance" then
local proto = protos[a.name or ""]
local values = {}
for _, fv in Xml.children(el, "fieldValue") do
if fv.attrs.name then
values[fv.attrs.name] = fieldValue(fv)
end
end
local inst = proto and Parse.expand(proto, values, a.DEF, routes)
node = inst or { type = a.name or "ProtoInstance", def = a.DEF, fields = values }
else
node = { type = typ, def = a.DEF, fields = {} }
for k, v in a do
if k ~= "DEF" and k ~= "USE" and k ~= "containerField" and k ~= "class" and not string.find(k, ":", 1, true) then
node.fields[k] = v
end
end
children(el, node)
end
depth -= 1
if a.DEF then
defs[a.DEF] = node
end
return node
end
for _, ch in root.children do
if type(ch) ~= "table" then
continue
end
local name = Xml.localName(ch.name)
if name == "head" then
for _, h in ch.children do
if type(h) == "table" then
local hn = Xml.localName(h.name)
if hn == "meta" and h.attrs.name then
graph.meta[h.attrs.name] = h.attrs.content or ""
elseif hn == "component" and h.attrs.name then
table.insert(graph.components, h.attrs.name .. ":" .. (h.attrs.level or "1"))
elseif hn == "unit" and h.attrs.category then
graph.units[h.attrs.category] = { name = h.attrs.name or "", factor = tonumber(h.attrs.conversionFactor) or 1 }
end
end
end
elseif name == "Scene" then
local scene: Parse.Node = { type = "Scene", fields = {} }
children(ch, scene)
local list = scene.fields.children
if type(list) == "table" then
graph.roots = list
end
for f, v in scene.fields do
-- a top-level node with another containerField still shows
if f ~= "children" and type(v) == "table" then
for _, x in v do
table.insert(graph.roots, x)
end
end
end
end
end
if failure then
return nil, failure
end
return graph, nil
end
return VXml
+160
View File
@@ -0,0 +1,160 @@
--!strict
-- codecs/model/Vrml: the VRML97 / X3D scene-graph engine shared by model/vrml (.wrl) and model/x3d (.x3d XML,
-- .x3dv classic): one parser for the classic encoding (codecs/model/Vrml/Parse), one for the XML encoding
-- (codecs/model/Vrml/Xml over codecs/text/Xml), both into the same node graph, and one builder from the graph to a
-- Scene (codecs/model/Vrml/Build, codecs/model/Vrml/Geometry). Gzipped files (.wrz / .x3dz / .x3dvz) are inflated
-- first. New code, written from ISO/IEC 14772-1 (VRML97), ISO/IEC 19775-1 (X3D) and its encodings 19776-1 / -2.
--
-- local graph, err = Vrml.graph(bytes) -- classic or XML, by content
-- local scene, err2 = Vrml.decode(bytes, { format = "vrml", files = { ["tex.png"] = png } })
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Deflate = require("@formats/codecs/compress/Deflate")
local XmlCodec = require("@formats/codecs/text/Xml")
local Parse = require("@formats/codecs/model/Vrml/Parse")
local VXml = require("@formats/codecs/model/Vrml/Xml")
local Build = require("@formats/codecs/model/Vrml/Build")
local Write = require("@formats/codecs/model/Vrml/Write")
local Vrml = {}
export type Graph = Parse.Graph
export type Node = Parse.Node
export type Options = Build.Options & {
files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string)
resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths)
maxBytes: number?, -- the inflated size of a gzipped file (default 2^28)
}
-- the bytes as text: gzip inflated, UTF-8 BOM dropped
local function text(data: buffer | string, maxBytes: number?): (string?, Err.Err?)
local b = if type(data) == "string" then buffer.fromstring(data) else data
if buffer.len(b) >= 2 and buffer.readu8(b, 0) == 0x1F and buffer.readu8(b, 1) == 0x8B then
local out, err = Deflate.gunzip(b)
if not out then
return nil, err
end
if buffer.len(out) > (maxBytes or 2 ^ 28) then
return nil, Err.new(Err.LIMIT, "inflated file over maxBytes")
end
b = out
end
local s = buffer.tostring(b)
if string.sub(s, 1, 3) == "\239\187\191" then
s = string.sub(s, 4)
end
return s, nil
end
local function code(msg: string): string
if string.find(msg, "unsupported", 1, true) then
return Err.UNSUPPORTED
elseif string.find(msg, "limit", 1, true) then
return Err.LIMIT
elseif string.find(msg, "unterminated", 1, true) then
return Err.TRUNCATED
end
return Err.CORRUPT
end
-- parse(text) -> the graph of a classic-encoding file (VRML97 / .x3dv)
function Vrml.parse(s: string): (Graph?, Err.Err?)
local g, msg = Parse.parse(s)
if not g then
return nil, Err.new(code(msg or "parse error"), msg or "parse error")
end
return g, nil
end
-- parseXml(text | XML document) -> the graph of an X3D XML file
function Vrml.parseXml(src: any): (Graph?, Err.Err?)
local doc = src
if type(src) == "string" then
local d, err = XmlCodec.decode(src)
if not d and err and err.code == Err.TRUNCATED and not string.find(src, "</X3D>", 1, true) then
-- VTK's X3D exporter leaves the root element open
d = XmlCodec.decode(src .. "\n</X3D>\n")
end
if not d then
return nil, err
end
doc = d
end
local g, msg = VXml.graph(doc)
if not g then
return nil, Err.new(code(msg or "bad X3D"), msg or "bad X3D")
end
return g, nil
end
-- graph(bytes, opts?) -> the graph of either encoding (XML when the text starts with "<"); binary X3D is UNSUPPORTED
function Vrml.graph(data: buffer | string, opts: Options?): (Graph?, Err.Err?)
local s, err = text(data, opts and opts.maxBytes)
if not s then
return nil, err
end
local head = string.match(s, "^%s*(.?)")
if head == "<" then
return Vrml.parseXml(s)
end
if string.sub(s, 1, 4) == "\224\0\0\1" or string.sub(s, 1, 4) == "$EXI" then
return nil, Err.new(Err.UNSUPPORTED, "binary X3D (Fast Infoset / EXI encoding)")
end
return Vrml.parse(s)
end
-- fetcher(opts) -> fetch(uri) -> buffer?: opts.files (uri or base name) / opts.resolve
function Vrml.fetcher(opts: Options?): (uri: string) -> buffer?
return function(uri: string): buffer?
if not opts then
return nil
end
local v: any = nil
if type(opts.files) == "table" then
v = opts.files[uri] or opts.files[string.match(uri, "([^/\\]+)$") or uri]
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
return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil
end
end
-- build(graph, opts?) -> Scene
function Vrml.build(graph: Graph, opts: Options?): (Types.Scene?, Err.Err?)
local o: any = table.clone(opts or {})
o.fetch = o.fetch or Vrml.fetcher(opts)
o.load = o.load or function(data: buffer): (any, string?)
local g, err = Vrml.graph(data, opts)
return g, if err then err.message else nil
end
local scene, msg = Build.scene(graph, o)
if not scene then
return nil, Err.new(code(msg or "build failed"), msg or "build failed")
end
return scene, nil
end
-- decode(bytes, opts?) -> Scene: graph + build
function Vrml.decode(data: buffer | string, opts: Options?): (Types.Scene?, Err.Err?)
local g, err = Vrml.graph(data, opts)
if not g then
return nil, err
end
return Vrml.build(g, opts)
end
-- encode(scene, opts?) -> text: opts.encoding "vrml97" (default) / "x3dv" / "xml"; texture bytes go into opts.files
function Vrml.encode(scene: Types.Scene, opts: Write.Options?): (string?, 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 s, msg = Write.text(scene, opts or {})
if not s then
return nil, Err.new(Err.ARG, msg or "the scene could not be written")
end
return s, nil
end
return Vrml
+31
View File
@@ -152,6 +152,37 @@ function Archive.entries(value: any): { { entry: Types.ArchiveEntry, read: () ->
return out
end
-- slice(buf, at, n) -> a loader for Entry.load: a copy of buf[at, at + n) (stored entries of uncompressed archives)
function Archive.slice(buf: buffer, at: number, n: number): () -> (buffer?, Err.Err?)
return function(): (buffer?, Err.Err?)
local out = buffer.create(n)
buffer.copy(out, 0, buf, at, n)
return out, nil
end
end
-- collect(value) -> { { entry, data } } | nil, Err: every entry of an Archive-shaped value with its bytes read
-- (directories: data = an empty buffer), for writers of simple archives (PAK, WAD, GRP, VPK, ...)
function Archive.collect(value: any): ({ { entry: Types.ArchiveEntry, data: buffer } }?, Err.Err?)
local items = Archive.entries(value)
if not items then
return nil, Err.new(Err.ARG, "expected an Archive")
end
local out: { { entry: Types.ArchiveEntry, data: buffer } } = {}
for _, it in items do
local b: buffer = buffer.create(0)
if not it.entry.dir then
local d, err = it.read()
if not d then
return nil, err or Err.new(Err.CORRUPT, "entry " .. it.entry.name .. ": read failed")
end
b = d
end
table.insert(out, { entry = it.entry, data = b })
end
return out, nil
end
-- streamName(opts, ext) -> the entry name for a single-stream archive: opts.name without its compression extension
-- (".tgz" -> ".tar"), else "data"
function Archive.streamName(opts: any?, exts: { string }): string
+663
View File
@@ -0,0 +1,663 @@
--!strict
-- model/3ds/Build: model/3ds/Read's chunk tables -> Types.Scene. The 3DS model: mesh vertices are stored in world
-- space and the mesh matrix (0x4160) is the object's world transform; the keyframer places node(t) = parent(t) *
-- T(pos) * R(rot) * S(scale) and draws a mesh at node(t) * T(-pivot) * inverse(mesh matrix) (a mirroring mesh matrix
-- also flips x, as 3ds Max writes it and assimp reads it). Rotation keys are axis / angle deltas from the previous key
-- (the angle measured clockwise). Cameras and spotlights look at their target node's position, with the camera's
-- roll about the view axis. Smoothing groups give the normals (corners of faces that share a group and a position
-- are averaged; group 0 is flat). Times are frame / fps.
local Types = require("@formats/Types")
local Mat4 = require("@formats/codecs/model/Mat4")
local Read = require("@formats/model/3ds/Read")
local Build = {}
local S = Types.Scene
local readf32, readu16, readu32, writef32, writeu32 = buffer.readf32, buffer.readu16, buffer.readu32, buffer.writef32, buffer.writeu32
local band = bit32.band
local sqrt, abs = math.sqrt, math.abs
export type Options = { normals: boolean?, flipV: boolean?, fps: number? }
-- ------------------------------------------------------------------------------------------------ math
-- the mesh matrix (X, Y, Z axes, origin) as a column-major 4x4
local function meshMatrix(m: { number }?): { number }
if not m then
return Mat4.identity()
end
return { m[1], m[2], m[3], 0, m[4], m[5], m[6], 0, m[7], m[8], m[9], 0, m[10], m[11], m[12], 1 }
end
Build.meshMatrix = meshMatrix
local function det3(m: { number }): number
return m[1] * (m[6] * m[11] - m[7] * m[10]) - m[5] * (m[2] * m[11] - m[3] * m[10]) + m[9] * (m[2] * m[7] - m[3] * m[6])
end
Build.det3 = det3
-- q(a) * q(b)
local function qmul(a: { number }, b: { number }): { number }
local ax, ay, az, aw = a[1], a[2], a[3], a[4]
local bx, by, bz, bw = b[1], b[2], b[3], b[4]
return {
aw * bx + ax * bw + ay * bz - az * by,
aw * by - ax * bz + ay * bw + az * bx,
aw * bz + ax * by - ay * bx + az * bw,
aw * bw - ax * bx - ay * by - az * bz,
}
end
Build.qmul = qmul
-- a rotation key (angle in radians, axis) -> its quaternion (3DS angles turn clockwise)
local function keyQuat(angle: number, x: number, y: number, z: number): { number }
if x == 0 and y == 0 and z == 0 then
return { 0, 0, 0, 1 }
end
return Mat4.axisAngle(x, y, z, -math.deg(angle))
end
local function normalize(x: number, y: number, z: number): (number, number, number, number)
local l = sqrt(x * x + y * y + z * z)
if l < 1e-30 then
return 0, 0, 0, 0
end
return x / l, y / l, z / l, l
end
-- lookAt(pos, target, rollDegrees) -> the rotation whose -Z looks from pos to target, +Y up (world up +Z)
function Build.lookAt(p: { number }, t: { number }, roll: number): { number }
local fx, fy, fz, l = normalize(t[1] - p[1], t[2] - p[2], t[3] - p[3])
if l == 0 then
fx, fy, fz = 0, 1, 0
end
local ux, uy, uz = 0, 0, 1
if abs(fz) > 0.999999 then
ux, uy, uz = 0, 1, 0
end
-- right = forward x up, up = right x forward
local rx, ry, rz = normalize(fy * uz - fz * uy, fz * ux - fx * uz, fx * uy - fy * ux)
ux, uy, uz = ry * fz - rz * fy, rz * fx - rx * fz, rx * fy - ry * fx
local a = math.rad(roll)
local c, s = math.cos(a), math.sin(a)
local Rx, Ry, Rz = c * rx + s * ux, c * ry + s * uy, c * rz + s * uz
local Ux, Uy, Uz = c * ux - s * rx, c * uy - s * ry, c * uz - s * rz
return Mat4.quat({ Rx, Ry, Rz, 0, Ux, Uy, Uz, 0, -fx, -fy, -fz, 0, 0, 0, 0, 1 })
end
-- ------------------------------------------------------------------------------------------------ accessors
local function floats(values: { number }, comps: number): Types.Accessor
local a = S.accessor(nil, "f32", comps, #values // comps)
for i = 1, (#values // comps) * comps do
writef32(a.data, (i - 1) * 4, values[i])
end
return a
end
-- ------------------------------------------------------------------------------------------------ materials
local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff" }
local function materials(raw: Read.Raw, scene: Types.Scene): { [string]: number }
local byName: { [string]: number } = {}
local texByFile: { [string]: number } = {}
local function texture(m: Read.Map): Types.TextureRef?
local file = m.file
if not file or file == "" then
return nil
end
local ti = texByFile[file]
if not ti then
local ext = string.lower(string.match(file, "%.(%w+)$") or "")
local tiling = m.tiling or 0
local wrap: any = if band(tiling, 0x10) ~= 0 then "clamp" elseif band(tiling, 0x2) ~= 0 then "mirror" else "repeat"
local tex: Types.Texture = { name = file, uri = file, mime = MIME[ext] :: string?, sampler = { wrapS = wrap, wrapT = wrap } }
table.insert(scene.textures, tex)
ti = #scene.textures
texByFile[file] = ti
end
local ref: Types.TextureRef = { texture = ti }
local us, vs, uo, vo, ang = m.uscale or 1, m.vscale or 1, m.uoffset or 0, m.voffset or 0, m.angle or 0
if us ~= 1 or vs ~= 1 or uo ~= 0 or vo ~= 0 or ang ~= 0 then
ref.transform = { scale = { us, vs }, offset = { uo, vo }, rotation = math.rad(ang) }
end
return ref
end
for i, m in raw.materials do
local mat = S.material(m.name)
local d = m.diffuse or { 0.5, 0.5, 0.5 }
local transparency = math.clamp(m.transparency or 0, 0, 1)
mat.baseColor = { d[1], d[2], d[3], 1 - transparency }
mat.metallic = 0
mat.roughness = math.clamp(1 - (m.shininess or 0), 0, 1)
local si = m.selfIllum or 0
if si > 0 then
mat.emissive = { d[1] * si, d[2] * si, d[3] * si }
end
mat.alphaMode = if transparency > 0 then "blend" else "opaque"
mat.doubleSided = m.twoSided
local maps: { [string]: any } = {}
for kind, mp in m.maps do
local ref = texture(mp)
maps[kind] = { file = mp.file, strength = mp.strength, tiling = mp.tiling, uscale = mp.uscale, vscale = mp.vscale, uoffset = mp.uoffset, voffset = mp.voffset, angle = mp.angle, texture = ref and ref.texture }
if kind == "diffuse" then
mat.baseColorTexture = ref
elseif kind == "selfIllum" and ref then
mat.emissiveTexture = ref
if si <= 0 then
mat.emissive = { 1, 1, 1 }
end
end
end
mat.extras = {
["3ds"] = {
ambient = m.ambient, diffuse = m.diffuse, specular = m.specular, shininess = m.shininess,
shinStrength = m.shinStrength, transparency = m.transparency, selfIllum = m.selfIllum,
shading = m.shading, wire = m.wire, twoSided = m.twoSided, maps = maps,
},
}
table.insert(scene.materials, mat)
local key = string.lower(m.name)
if byName[key] == nil then
byName[key] = i
end
end
return byName
end
-- ------------------------------------------------------------------------------------------------ meshes
-- mesh(obj, xf, matByName, opts) -> a Types.Mesh of the object's faces (one primitive per material), vertices moved
-- by xf (world -> the node's local space)
local function mesh(name: string, m: Read.Mesh, xf: { number }, matByName: { [string]: number }, opts: Options): Types.Mesh
local nv, nf = m.nv, m.nf
local pos, faces = m.positions, m.faces
-- local positions
local lp = table.create(nv * 3, 0)
for v = 0, nv - 1 do
local x, y, z = Mat4.point(xf, readf32(pos, v * 12), readf32(pos, v * 12 + 4), readf32(pos, v * 12 + 8))
lp[v * 3 + 1], lp[v * 3 + 2], lp[v * 3 + 3] = x, y, z
end
-- faces with valid corners, their materials
local fa, fb, fc = table.create(nf, 0), table.create(nf, 0), table.create(nf, 0)
local valid = table.create(nf, false)
for f = 0, nf - 1 do
local a, b, c = readu16(faces :: buffer, f * 8), readu16(faces :: buffer, f * 8 + 2), readu16(faces :: buffer, f * 8 + 4)
fa[f + 1], fb[f + 1], fc[f + 1] = a, b, c
valid[f + 1] = a < nv and b < nv and c < nv
end
local fmat = table.create(nf, 0)
for _, fm in m.faceMats do
local mi = matByName[string.lower(fm.name)] or 0
for _, f in fm.faces do
if f < nf then
fmat[f + 1] = mi
end
end
end
local smooth = m.smoothing
local doNormals = opts.normals ~= false
-- face normals (area weighted) and the faces around each distinct position
local fn = table.create(nf * 3, 0)
local around: { [number]: { number } } = {}
local group = table.create(nv, 0)
if doNormals then
local keyToGroup: { [string]: number } = {}
for v = 0, nv - 1 do
local k = buffer.readstring(pos, v * 12, 12)
local g = keyToGroup[k]
if not g then
g = v
keyToGroup[k] = g
end
group[v + 1] = g
end
for f = 1, nf do
if valid[f] then
local a, b, c = fa[f] * 3, fb[f] * 3, fc[f] * 3
local e1x, e1y, e1z = lp[b + 1] - lp[a + 1], lp[b + 2] - lp[a + 2], lp[b + 3] - lp[a + 3]
local e2x, e2y, e2z = lp[c + 1] - lp[a + 1], lp[c + 2] - lp[a + 2], lp[c + 3] - lp[a + 3]
fn[f * 3 - 2], fn[f * 3 - 1], fn[f * 3] = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x
for _, v in { fa[f], fb[f], fc[f] } do
local g = group[v + 1]
local list = around[g]
if not list then
list = {}
around[g] = list
end
if list[#list] ~= f then
table.insert(list, f)
end
end
end
end
end
local function sgOf(f: number): number
return if smooth then readu32(smooth, (f - 1) * 4) else 1
end
local function cornerNormal(f: number, v: number, sg: number): (number, number, number)
local x, y, z = fn[f * 3 - 2], fn[f * 3 - 1], fn[f * 3]
if sg ~= 0 then
local sx, sy, sz = 0, 0, 0
for _, g in around[group[v + 1]] do
if band(sgOf(g), sg) ~= 0 then
sx, sy, sz = sx + fn[g * 3 - 2], sy + fn[g * 3 - 1], sz + fn[g * 3]
end
end
local nx, ny, nz, l = normalize(sx, sy, sz)
if l > 0 then
return nx, ny, nz
end
end
local nx, ny, nz = normalize(x, y, z)
return nx, ny, nz
end
-- primitives in the order their material first appears
local order: { number } = {}
local byMat: { [number]: { number } } = {}
for f = 1, nf do
if valid[f] then
local mi = fmat[f]
if not byMat[mi] then
byMat[mi] = {}
table.insert(order, mi)
end
table.insert(byMat[mi], f)
end
end
local uvs, nuv = m.uvs, m.nuv
local flipV = opts.flipV ~= false
local out: Types.Mesh = { name = name, primitives = {} }
for _, mi in order do
local list = byMat[mi]
local remap: { [number]: number } = {}
local P: { number }, N: { number }, U: { number } = {}, {}, {}
local idx = table.create(#list * 3, 0)
local sgs = table.create(#list, 0)
local count = 0
for i, f in list do
local sg = sgOf(f)
sgs[i] = sg
for k, v in { fa[f], fb[f], fc[f] } do
local key = if not doNormals then v elseif sg ~= 0 then v * 4294967296 + sg else -(f * 65536 + v + 1)
local o: number = remap[key] or -1
if o < 0 then
o = count
count += 1
remap[key] = o
P[o * 3 + 1], P[o * 3 + 2], P[o * 3 + 3] = lp[v * 3 + 1], lp[v * 3 + 2], lp[v * 3 + 3]
if doNormals then
N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = cornerNormal(f, v, sg)
end
if uvs then
local u: number, w: number = 0, 0
if v < nuv then
u = readf32(uvs, v * 8)
w = readf32(uvs, v * 8 + 4)
end
U[o * 2 + 1] = u
U[o * 2 + 2] = if flipV then 1 - w else w
end
end
idx[(i - 1) * 3 + k] = o
end
end
local ind = S.accessor(nil, "u32", 1, #idx)
for i, v in idx do
writeu32(ind.data, (i - 1) * 4, v)
end
local prim: Types.Primitive = {
attributes = { POSITION = floats(P, 3) },
indices = ind,
mode = "triangles",
material = if mi > 0 then mi else nil,
extras = { ["3ds"] = { smoothing = sgs } },
}
if doNormals then
prim.attributes.NORMAL = floats(N, 3)
end
if uvs then
prim.attributes.TEXCOORD_0 = floats(U, 2)
end
table.insert(out.primitives, prim)
end
return out
end
-- ------------------------------------------------------------------------------------------------ tracks
-- the value of a track at a frame (linear between keys, clamped at the ends)
local function evalTrack(t: Read.Track?, frame: number, default: { number }): { number }
if not t or #t.frames == 0 then
return default
end
local fr, vals, n = t.frames, t.values, t.size
local function at(k: number): { number }
local r = table.create(n, 0)
for c = 1, n do
r[c] = vals[(k - 1) * n + c]
end
return r
end
if frame <= fr[1] then
return at(1)
end
for k = 1, #fr - 1 do
local f0, f1 = fr[k], fr[k + 1]
if frame <= f1 then
local u = if f1 > f0 then (frame - f0) / (f1 - f0) else 1
local a, b = at(k), at(k + 1)
for c = 1, n do
a[c] += (b[c] - a[c]) * u
end
return a
end
end
return at(#fr)
end
local function first(t: Read.Track?, default: { number }): { number }
return evalTrack(t, -math.huge, default)
end
local function scaleKey(v: { number }): { number }
return { if v[1] == 0 then 1 else v[1], if v[2] == 0 then 1 else v[2], if v[3] == 0 then 1 else v[3] }
end
-- absolute rotations from a rotation track: times (frames), quaternions; deltas over ~180 degrees get extra keys
local function rotations(t: Read.Track): ({ number }, { { number } })
local frames, quats = {}, {}
local acc: { number }? = nil
for k = 1, #t.frames do
local o = (k - 1) * 4
local angle, x, y, z = t.values[o + 1], t.values[o + 2], t.values[o + 3], t.values[o + 4]
if acc == nil then
acc = keyQuat(angle, x, y, z)
else
local prev = acc :: { number }
local steps = math.clamp(math.ceil(abs(angle) / (math.pi * 0.9)), 1, 64)
local f0 = frames[#frames]
for s = 1, steps - 1 do
table.insert(frames, f0 + (t.frames[k] - f0) * s / steps)
table.insert(quats, qmul(prev, keyQuat(angle * s / steps, x, y, z)))
end
acc = qmul(prev, keyQuat(angle, x, y, z))
end
local q = acc :: { number }
local n = sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4])
if n > 0 then
q = { q[1] / n, q[2] / n, q[3] / n, q[4] / n }
end
acc = q
table.insert(frames, t.frames[k])
table.insert(quats, q)
end
return frames, quats
end
-- ------------------------------------------------------------------------------------------------ scene
function Build.scene(raw: Read.Raw, opts: Options?): Types.Scene
local o: Options = opts or {}
local fps = o.fps or 30
local scene = S.new()
local matByName = materials(raw, scene)
-- objects by name
local objByName: { [string]: Read.Object } = {}
for _, obj in raw.objects do
if objByName[obj.name] == nil then
objByName[obj.name] = obj
end
local low = string.lower(obj.name)
if objByName[low] == nil then
objByName[low] = obj
end
end
local function findObj(name: string): Read.Object?
return objByName[name] or objByName[string.lower(name)]
end
local meshCache: { [any]: number } = {}
local function meshOf(obj: Read.Object, pivot: { number }?, placed: boolean): number?
local m = obj.mesh
if not m or m.nf == 0 or not m.faces then
return nil
end
local pv = pivot or { 0, 0, 0 }
local key = obj.name .. (if placed then string.format("|%.9g|%.9g|%.9g", pv[1], pv[2], pv[3]) else "|free")
if meshCache[key] then
return meshCache[key]
end
local M = meshMatrix(m.matrix)
local inv = Mat4.inverse(M) or Mat4.identity()
local xf = inv
if placed then
if det3(M) < 0 then
xf = Mat4.mul(Mat4.scaling(-1, 1, 1), xf)
end
xf = Mat4.mul(Mat4.translation(-pv[1], -pv[2], -pv[3]), xf)
end
local me = mesh(obj.name, m, xf, matByName, o)
if #me.primitives == 0 then
return nil
end
table.insert(scene.meshes, me)
meshCache[key] = #scene.meshes
return #scene.meshes
end
local camIndex: { [Read.Object]: number } = {}
local function cameraOf(obj: Read.Object): number
if camIndex[obj] then
return camIndex[obj]
end
local c = obj.camera :: Read.Camera
local hfov = if c.lens > 1e-3 then 2400 / c.lens else 45
hfov = math.clamp(hfov, 0.01, 179)
local aspect = 4 / 3
local yfov = 2 * math.atan(math.tan(math.rad(hfov) / 2) / aspect)
local near = if c.near and c.near > 0 then c.near else 0.1
local far = if c.far and c.far > near then c.far else nil
local cam: Types.Camera = { name = obj.name, type = "perspective", yfov = yfov, aspect = aspect, znear = near, zfar = far }
table.insert(scene.cameras, cam)
camIndex[obj] = #scene.cameras
return #scene.cameras
end
local lightIndex: { [Read.Object]: number } = {}
local function lightOf(obj: Read.Object): number
if lightIndex[obj] then
return lightIndex[obj]
end
local l = obj.light :: Read.Light
local L: Types.Light = { name = obj.name, type = "point", color = { l.color[1], l.color[2], l.color[3] }, intensity = l.multiplier }
if l.spot then
L.type = "spot"
local hot = math.clamp(l.spot.hotspot, 0, 179.9)
local fall = math.clamp(math.max(l.spot.falloff, hot), 0, 179.9)
L.innerCone, L.outerCone = math.rad(hot) / 2, math.rad(fall) / 2
end
if l.attenuate and l.outer and l.outer > 0 then
L.range = l.outer
end
table.insert(scene.lights, L)
lightIndex[obj] = #scene.lights
return #scene.lights
end
local kf = raw.keyframer
local kfNodes = if kf then kf.nodes else {}
-- targets of cameras / spotlights by name
local targets: { [string]: Read.Node } = {}
for _, n in kfNodes do
if n.kind == "target" or n.kind == "lightTarget" then
targets[n.name] = targets[n.name] or n
end
end
local placedObj: { [Read.Object]: boolean } = {}
local sceneOf: { [number]: number } = {} -- kf id -> scene node
local channels: { Types.Channel } = {}
local function channel(node: number, path: any, times: { number }, values: { number }, comps: number)
for i = 1, #times do
times[i] /= fps
end
local ch: Types.Channel = { node = node, path = path, input = floats(times, 1), output = floats(values, comps), interpolation = "LINEAR" }
table.insert(channels, ch)
end
local function addNode(n: Types.Node, parent: number?): number
table.insert(scene.nodes, n)
local i = #scene.nodes
if parent then
table.insert(scene.nodes[parent].children, i)
else
table.insert(scene.roots, i)
end
return i
end
for k, kn in kfNodes do
local kind = kn.kind
if kind == "target" or kind == "lightTarget" or kind == "ambient" then
continue
end
local id = kn.id or (k - 1)
local parent = if kn.parent >= 0 then sceneOf[kn.parent] else nil
local obj = findObj(kn.name)
local tr = kn.tracks
local name = if kn.instance and kn.instance ~= "" then kn.instance else kn.name
local node: Types.Node = { name = name, children = {} }
local x3ds: { [string]: any } = { kind = kind, object = kn.name, id = id, pivot = kn.pivot }
node.extras = { ["3ds"] = x3ds }
local animated = false
if kind == "object" then
if obj and obj.mesh then
node.mesh = meshOf(obj, kn.pivot, true)
placedObj[obj] = true
x3ds.hidden = obj.hidden or nil
end
node.translation = first(tr.pos, { 0, 0, 0 })
node.rotation = if tr.rot and #tr.rot.frames > 0 then (select(2, rotations(tr.rot)) :: any)[1] else { 0, 0, 0, 1 }
node.scale = scaleKey(first(tr.scl, { 1, 1, 1 }))
local ni = addNode(node, parent)
sceneOf[id] = ni
if tr.pos and #tr.pos.frames > 1 then
channel(ni, "translation", table.clone(tr.pos.frames), table.clone(tr.pos.values), 3)
end
if tr.rot and #tr.rot.frames > 1 then
local frames, quats = rotations(tr.rot)
local vals = {}
for _, q in quats do
table.move(q, 1, 4, #vals + 1, vals)
end
channel(ni, "rotation", frames, vals, 4)
end
if tr.scl and #tr.scl.frames > 1 then
local vals = {}
for i = 1, #tr.scl.frames do
local v = scaleKey({ tr.scl.values[i * 3 - 2], tr.scl.values[i * 3 - 1], tr.scl.values[i * 3] })
table.move(v, 1, 3, #vals + 1, vals)
end
channel(ni, "scale", table.clone(tr.scl.frames), vals, 3)
end
else
-- cameras and lights: position, target, roll
local isCam = kind == "camera"
local cam = if obj and isCam then obj.camera else nil
local lit = if obj and not isCam then obj.light else nil
local tgt = targets[kn.name]
local basePos = if cam then cam.pos elseif lit then lit.pos else { 0, 0, 0 }
local baseTgt = if cam then cam.target elseif lit and lit.spot then lit.spot.target else nil
local aims = isCam or kind == "spot" or baseTgt ~= nil
local function pose(frame: number): ({ number }, { number }?)
local p = evalTrack(tr.pos, frame, basePos)
if not aims then
return p, nil
end
local t = evalTrack(tgt and tgt.tracks.pos, frame, baseTgt or { p[1], p[2] + 1, p[3] })
local roll = evalTrack(tr.roll, frame, { if cam then cam.roll else 0 })[1]
return p, Build.lookAt(p, t, roll)
end
local p0, r0 = pose(-math.huge)
node.translation, node.rotation = p0, r0
if cam then
node.camera = cameraOf(obj :: Read.Object)
placedObj[obj :: Read.Object] = true
x3ds.lens, x3ds.roll = cam.lens, cam.roll
elseif lit then
node.light = lightOf(obj :: Read.Object)
placedObj[obj :: Read.Object] = true
x3ds.off = lit.off or nil
end
local ni = addNode(node, parent)
sceneOf[id] = ni
-- every key time of the position, roll and target tracks
local set: { [number]: boolean } = {}
local times: { number } = {}
for _, t in { tr.pos, tr.roll, if aims and tgt then tgt.tracks.pos else nil } do
if t and #t.frames > 1 then
animated = true
end
for _, f in (if t then t.frames else {}) :: { number } do
if not set[f] then
set[f] = true
table.insert(times, f)
end
end
end
if animated then
table.sort(times)
local tv, rv = {}, {}
for _, f in times do
local p, r = pose(f)
table.move(p, 1, 3, #tv + 1, tv)
if r then
table.move(r, 1, 4, #rv + 1, rv)
end
end
channel(ni, "translation", table.clone(times), tv, 3)
if aims then
channel(ni, "rotation", times, rv, 4)
end
end
end
end
-- objects the keyframer does not place (or files without one): at their own matrix / position
for _, obj in raw.objects do
if placedObj[obj] then
continue
end
local node: Types.Node = { name = obj.name, children = {}, extras = { ["3ds"] = { object = obj.name, hidden = obj.hidden or nil } } }
if obj.mesh then
local mi = meshOf(obj, nil, false)
if not mi then
continue
end
node.mesh = mi
if obj.mesh.matrix then
node.matrix = meshMatrix(obj.mesh.matrix)
end
elseif obj.camera then
local c = obj.camera
node.camera = cameraOf(obj)
node.translation, node.rotation = c.pos, Build.lookAt(c.pos, c.target, c.roll)
elseif obj.light then
local l = obj.light
node.light = lightOf(obj)
node.translation = l.pos
if l.spot then
node.rotation = Build.lookAt(l.pos, l.spot.target, 0)
end
else
continue
end
addNode(node, nil)
end
if #channels > 0 then
table.insert(scene.animations, { name = kf and kf.name or "3ds", channels = channels })
end
scene.meta.up = "z"
scene.meta.source = {
format = "3ds",
version = raw.version,
meshVersion = raw.meshVersion,
masterScale = raw.masterScale,
ambient = raw.ambient,
keyframer = kf ~= nil,
frames = if kf and kf.first then { kf.first, kf.last } else nil,
fps = fps,
}
return scene
end
return Build
+506
View File
@@ -0,0 +1,506 @@
--!strict
-- model/3ds/Read: the 3DS chunk tree (a u16 id and a u32 size that counts the 6-byte header, little endian) read
-- into plain tables: materials, named objects (triangle meshes, cameras, lights) and the keyframer (nodes with their
-- tracks). Chunk ids and layouts from the 3D Studio file format as documented by Autodesk's 3DS File Toolkit notes
-- and read by assimp's 3DS importer (BSD-3, used as the reference) and lib3ds (read for the layout only, no code).
-- Unknown chunks are skipped. A chunk running past the end of the data is an error; one running past its parent is
-- clipped to the parent. Never throws on bad data: returns nil, message, offset.
local Read = {}
local readu8, readu16, readu32, readi16, readf32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readi16, buffer.readf32
local band = bit32.band
-- ------------------------------------------------------------------------------------------------ chunk ids
local C = {
MAIN = 0x4D4D, VERSION = 0x0002, EDITOR = 0x3D3D, MESH_VERSION = 0x3D3E, MASTER_SCALE = 0x0100,
RGBF = 0x0010, RGBB = 0x0011, LIN_RGBB = 0x0012, LIN_RGBF = 0x0013, PERCENTW = 0x0030, PERCENTF = 0x0031,
AMBIENT_LIGHT = 0x2100, OBJECT = 0x4000, TRIMESH = 0x4100, VERTICES = 0x4110, FACES = 0x4120, FACE_MAT = 0x4130,
UVS = 0x4140, SMOOTH = 0x4150, MATRIX = 0x4160, LIGHT = 0x4600, SPOT = 0x4610, LIGHT_OFF = 0x4620,
ATTENUATE = 0x4625, INNER_RANGE = 0x4659, OUTER_RANGE = 0x465A, MULTIPLIER = 0x465B, CAMERA = 0x4700,
CAM_RANGES = 0x4720, OBJ_HIDDEN = 0x4010,
MATERIAL = 0xAFFF, MAT_NAME = 0xA000, MAT_AMBIENT = 0xA010, MAT_DIFFUSE = 0xA020, MAT_SPECULAR = 0xA030,
MAT_SHININESS = 0xA040, MAT_SHIN_STRENGTH = 0xA041, MAT_TRANSPARENCY = 0xA050, MAT_SELF_ILPCT = 0xA084,
MAT_TWO_SIDE = 0xA081, MAT_WIRE = 0xA085, MAT_SHADING = 0xA100, MAP_FILE = 0xA300, MAP_TILING = 0xA351,
MAP_USCALE = 0xA354, MAP_VSCALE = 0xA356, MAP_UOFFSET = 0xA358, MAP_VOFFSET = 0xA35A, MAP_ANGLE = 0xA35C,
KEYFRAMER = 0xB000, KF_HDR = 0xB00A, KF_FRAMES = 0xB008, NODE_HDR = 0xB010, NODE_INSTANCE = 0xB011,
NODE_PIVOT = 0xB013, NODE_ID = 0xB030, TRACK_POS = 0xB020, TRACK_ROT = 0xB021, TRACK_SCALE = 0xB022,
TRACK_FOV = 0xB023, TRACK_ROLL = 0xB024, TRACK_COLOR = 0xB025, TRACK_HOTSPOT = 0xB027, TRACK_FALLOFF = 0xB028,
}
Read.C = C
-- material map chunks -> their name in Raw materials
Read.MAPS = {
[0xA200] = "diffuse", [0xA33A] = "diffuse2", [0xA210] = "opacity", [0xA230] = "bump", [0xA204] = "specular",
[0xA33C] = "shininess", [0xA33D] = "selfIllum", [0xA220] = "reflection",
}
-- keyframer node chunks -> kind
local NODE_KINDS = {
[0xB001] = "ambient", [0xB002] = "object", [0xB003] = "camera", [0xB004] = "target", [0xB005] = "light",
[0xB006] = "lightTarget", [0xB007] = "spot",
}
-- track chunks -> (field, values per key)
local TRACKS: { [number]: { any } } = {
[0xB020] = { "pos", 3 }, [0xB021] = { "rot", 4 }, [0xB022] = { "scl", 3 }, [0xB023] = { "fov", 1 },
[0xB024] = { "roll", 1 }, [0xB025] = { "color", 3 }, [0xB027] = { "hotspot", 1 }, [0xB028] = { "falloff", 1 },
}
-- ------------------------------------------------------------------------------------------------ types
export type Map = { file: string?, strength: number?, tiling: number?, uscale: number?, vscale: number?, uoffset: number?, voffset: number?, angle: number? }
export type Material = {
name: string,
ambient: { number }?, diffuse: { number }?, specular: { number }?,
shininess: number?, shinStrength: number?, transparency: number?, selfIllum: number?, -- fractions 0..1
twoSided: boolean, wire: boolean, shading: number?,
maps: { [string]: Map },
}
export type Mesh = {
nv: number, positions: buffer, -- nv * 3 f32 (world space)
nuv: number, uvs: buffer?, -- nuv * 2 f32
nf: number, faces: buffer?, -- nf * 4 u16 (a, b, c, flags)
faceMats: { { name: string, faces: { number } } }, -- 0-based face numbers
smoothing: buffer?, -- nf u32
matrix: { number }?, -- 12 floats: the X, Y, Z axes and the origin (world space)
}
export type Camera = { pos: { number }, target: { number }, roll: number, lens: number, near: number?, far: number? }
export type Light = {
pos: { number }, color: { number }, multiplier: number, off: boolean, attenuate: boolean,
inner: number?, outer: number?, spot: { target: { number }, hotspot: number, falloff: number }?,
}
export type Object = { name: string, hidden: boolean, mesh: Mesh?, camera: Camera?, light: Light? }
export type Track = { frames: { number }, values: { number }, size: number, flags: number }
export type Node = {
kind: string, id: number?, name: string, parent: number, flags: number, instance: string?, pivot: { number }?,
tracks: { [string]: Track },
}
export type Raw = {
version: number?, meshVersion: number?, masterScale: number?, ambient: { number }?,
materials: { Material }, objects: { Object },
keyframer: { name: string?, length: number?, first: number?, last: number?, nodes: { Node } }?,
vertices: number,
}
-- ------------------------------------------------------------------------------------------------ helpers
type Ctx = { b: buffer, limit: number, maxVertices: number, raw: Raw }
-- each(ctx, p, stop, fn): calls fn(id, body, chunkEnd) for the chunks of [p, stop); returns fn's error or a size error
local function each(ctx: Ctx, p: number, stop: number, fn: (number, number, number) -> (string?, number?)): (string?, number?)
local b = ctx.b
while p + 6 <= stop do
local id, size = readu16(b, p), readu32(b, p + 2)
if size < 6 then
return nil, nil -- padding or garbage after the last chunk
end
local e = p + size
if e > ctx.limit then
return string.format("chunk 0x%04x runs past the end of the data", id), p
end
local err, at = fn(id, p + 6, math.min(e, stop))
if err then
return err, at
end
p = e
end
return nil, nil
end
-- cstring(b, p, stop) -> the NUL-terminated string at p, the offset after it | nil
local function cstring(b: buffer, p: number, stop: number): (string?, number)
for q = p, stop - 1 do
if readu8(b, q) == 0 then
return buffer.readstring(b, p, q - p), q + 1
end
end
return nil, stop
end
local function vec3(b: buffer, p: number): { number }
return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) }
end
-- a colour chunk list: the first float or byte colour (gamma-corrected "linear" variants only when nothing else)
local function color(ctx: Ctx, p: number, stop: number): { number }?
local b = ctx.b
local main: { number }?, lin: { number }? = nil, nil
each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?)
if (id == C.RGBF or id == C.LIN_RGBF) and e - q >= 12 then
local c = vec3(b, q)
if id == C.RGBF then
main = main or c
else
lin = lin or c
end
elseif (id == C.RGBB or id == C.LIN_RGBB) and e - q >= 3 then
local c = { readu8(b, q) / 255, readu8(b, q + 1) / 255, readu8(b, q + 2) / 255 }
if id == C.RGBB then
main = main or c
else
lin = lin or c
end
end
return nil, nil
end)
return main or lin
end
-- a percentage chunk list -> a fraction 0..1
local function percent(ctx: Ctx, p: number, stop: number): number?
local b = ctx.b
local v: number? = nil
each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?)
if v == nil and id == C.PERCENTW and e - q >= 2 then
v = readu16(b, q) / 100
elseif v == nil and id == C.PERCENTF and e - q >= 4 then
v = readf32(b, q) / 100
end
return nil, nil
end)
return v
end
-- ------------------------------------------------------------------------------------------------ materials
local function map(ctx: Ctx, p: number, stop: number): Map
local b = ctx.b
local m: Map = {}
m.strength = percent(ctx, p, stop)
each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?)
local n = e - q
if id == C.MAP_FILE then
m.file = cstring(b, q, e)
elseif id == C.MAP_TILING and n >= 2 then
m.tiling = readu16(b, q)
elseif n >= 4 then
local v = readf32(b, q)
if id == C.MAP_USCALE then
m.uscale = v
elseif id == C.MAP_VSCALE then
m.vscale = v
elseif id == C.MAP_UOFFSET then
m.uoffset = v
elseif id == C.MAP_VOFFSET then
m.voffset = v
elseif id == C.MAP_ANGLE then
m.angle = v
end
end
return nil, nil
end)
return m
end
local function material(ctx: Ctx, p: number, stop: number)
local b = ctx.b
local m: Material = { name = "", twoSided = false, wire = false, maps = {} }
each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?)
if id == C.MAT_NAME then
m.name = cstring(b, q, e) or ""
elseif id == C.MAT_AMBIENT then
m.ambient = color(ctx, q, e)
elseif id == C.MAT_DIFFUSE then
m.diffuse = color(ctx, q, e)
elseif id == C.MAT_SPECULAR then
m.specular = color(ctx, q, e)
elseif id == C.MAT_SHININESS then
m.shininess = percent(ctx, q, e)
elseif id == C.MAT_SHIN_STRENGTH then
m.shinStrength = percent(ctx, q, e)
elseif id == C.MAT_TRANSPARENCY then
m.transparency = percent(ctx, q, e)
elseif id == C.MAT_SELF_ILPCT then
m.selfIllum = percent(ctx, q, e)
elseif id == C.MAT_TWO_SIDE then
m.twoSided = true
elseif id == C.MAT_WIRE then
m.wire = true
elseif id == C.MAT_SHADING and e - q >= 2 then
m.shading = readu16(b, q)
elseif Read.MAPS[id] then
m.maps[Read.MAPS[id]] = map(ctx, q, e)
end
return nil, nil
end)
table.insert(ctx.raw.materials, m)
end
-- ------------------------------------------------------------------------------------------------ objects
local function faceList(ctx: Ctx, mesh: Mesh, p: number, stop: number): (string?, number?)
local b = ctx.b
if stop - p < 2 then
return "truncated face list", p
end
local nf = readu16(b, p)
if p + 2 + nf * 8 > stop then
return "face list runs past its chunk", p
end
local faces = buffer.create(nf * 8)
buffer.copy(faces, 0, b, p + 2, nf * 8)
mesh.nf, mesh.faces = nf, faces
return each(ctx, p + 2 + nf * 8, stop, function(id: number, q: number, e: number): (string?, number?)
if id == C.FACE_MAT then
local name, r = cstring(b, q, e)
if not name or r + 2 > e then
return "bad face material list", q
end
local n = readu16(b, r)
if r + 2 + n * 2 > e then
return "face material list runs past its chunk", q
end
local list: { number } = {}
for i = 0, n - 1 do
list[i + 1] = readu16(b, r + 2 + i * 2)
end
table.insert(mesh.faceMats, { name = name, faces = list })
elseif id == C.SMOOTH then
local n = math.min(nf, (e - q) // 4)
local s = buffer.create(nf * 4)
buffer.copy(s, 0, b, q, n * 4)
mesh.smoothing = s
end
return nil, nil
end)
end
local function trimesh(ctx: Ctx, p: number, stop: number): (Mesh?, string?, number?)
local b = ctx.b
local mesh: Mesh = { nv = 0, positions = buffer.create(0), nuv = 0, nf = 0, faceMats = {} }
local err, at = each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?)
if id == C.VERTICES or id == C.UVS then
if e - q < 2 then
return "truncated vertex list", q
end
local n = readu16(b, q)
local size = if id == C.VERTICES then 12 else 8
if q + 2 + n * size > e then
return "vertex list runs past its chunk", q
end
local data = buffer.create(n * size)
buffer.copy(data, 0, b, q + 2, n * size)
if id == C.VERTICES then
ctx.raw.vertices += n
if ctx.raw.vertices > ctx.maxVertices then
return "limit: more than " .. ctx.maxVertices .. " vertices", q
end
mesh.nv, mesh.positions = n, data
else
mesh.nuv, mesh.uvs = n, data
end
elseif id == C.FACES then
return faceList(ctx, mesh, q, e)
elseif id == C.MATRIX and e - q >= 48 then
local m: { number } = {}
for i = 0, 11 do
m[i + 1] = readf32(b, q + i * 4)
end
mesh.matrix = m
end
return nil, nil
end)
if err then
return nil, err, at
end
return mesh, nil, nil
end
local function camera(ctx: Ctx, p: number, stop: number): Camera?
local b = ctx.b
if stop - p < 32 then
return nil
end
local cam: Camera = { pos = vec3(b, p), target = vec3(b, p + 12), roll = readf32(b, p + 24), lens = readf32(b, p + 28) }
each(ctx, p + 32, stop, function(id: number, q: number, e: number): (string?, number?)
if id == C.CAM_RANGES and e - q >= 8 then
cam.near, cam.far = readf32(b, q), readf32(b, q + 4)
end
return nil, nil
end)
return cam
end
local function light(ctx: Ctx, p: number, stop: number): Light?
local b = ctx.b
if stop - p < 12 then
return nil
end
local l: Light = { pos = vec3(b, p), color = { 1, 1, 1 }, multiplier = 1, off = false, attenuate = false }
l.color = color(ctx, p + 12, stop) or l.color
each(ctx, p + 12, stop, function(id: number, q: number, e: number): (string?, number?)
local n = e - q
if id == C.SPOT and n >= 20 then
l.spot = { target = vec3(b, q), hotspot = readf32(b, q + 12), falloff = readf32(b, q + 16) }
elseif id == C.LIGHT_OFF then
l.off = true
elseif id == C.ATTENUATE then
l.attenuate = true
elseif id == C.MULTIPLIER and n >= 4 then
l.multiplier = readf32(b, q)
elseif id == C.INNER_RANGE and n >= 4 then
l.inner = readf32(b, q)
elseif id == C.OUTER_RANGE and n >= 4 then
l.outer = readf32(b, q)
end
return nil, nil
end)
return l
end
local function object(ctx: Ctx, p: number, stop: number): (string?, number?)
local b = ctx.b
local name, q = cstring(b, p, stop)
if not name then
return "object without a name", p
end
local obj: Object = { name = name, hidden = false }
local err, at = each(ctx, q, stop, function(id: number, r: number, e: number): (string?, number?)
if id == C.TRIMESH then
local mesh, merr, mat = trimesh(ctx, r, e)
if not mesh then
return merr, mat
end
obj.mesh = mesh
elseif id == C.CAMERA then
obj.camera = camera(ctx, r, e)
elseif id == C.LIGHT then
obj.light = light(ctx, r, e)
elseif id == C.OBJ_HIDDEN then
obj.hidden = true
end
return nil, nil
end)
if err then
return err, at
end
table.insert(ctx.raw.objects, obj)
return nil, nil
end
-- ------------------------------------------------------------------------------------------------ keyframer
-- a track: u16 flags, 8 unused bytes, u32 keys; each key: u32 frame, u16 spline flags (+ one f32 per set bit of
-- tension / continuity / bias / ease to / ease from), then the values
local function track(b: buffer, p: number, stop: number, size: number): Track?
if stop - p < 14 then
return nil
end
local flags, n = readu16(b, p), readu32(b, p + 10)
local t: Track = { frames = {}, values = {}, size = size, flags = flags }
p += 14
for _ = 1, n do
if p + 6 > stop then
break
end
local frame, spline = readu32(b, p), readu16(b, p + 4)
p += 6
for bit = 0, 4 do
if band(spline, bit32.lshift(1, bit)) ~= 0 then
p += 4
end
end
if p + size * 4 > stop then
break
end
table.insert(t.frames, frame)
for k = 0, size - 1 do
table.insert(t.values, readf32(b, p + k * 4))
end
p += size * 4
end
return t
end
local function node(ctx: Ctx, kind: string, p: number, stop: number, list: { Node })
local b = ctx.b
local n: Node = { kind = kind, name = "", parent = -1, flags = 0, tracks = {} }
each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?)
if id == C.NODE_ID and e - q >= 2 then
n.id = readu16(b, q)
elseif id == C.NODE_HDR then
local name, r = cstring(b, q, e)
n.name = name or ""
if r + 6 <= e then
n.flags = readu16(b, r)
n.parent = readi16(b, r + 4)
end
elseif id == C.NODE_INSTANCE then
n.instance = cstring(b, q, e)
elseif id == C.NODE_PIVOT and e - q >= 12 then
n.pivot = vec3(b, q)
elseif TRACKS[id] then
local spec = TRACKS[id]
n.tracks[spec[1]] = track(b, q, e, spec[2])
end
return nil, nil
end)
table.insert(list, n)
end
local function keyframer(ctx: Ctx, p: number, stop: number)
local b = ctx.b
local kf = { nodes = {} :: { Node }, name = nil :: string?, length = nil :: number?, first = nil :: number?, last = nil :: number? }
each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?)
if id == C.KF_HDR and e - q >= 2 then
local name, r = cstring(b, q + 2, e)
kf.name = name
if r + 4 <= e then
kf.length = readu32(b, r)
end
elseif id == C.KF_FRAMES and e - q >= 8 then
kf.first, kf.last = readu32(b, q), readu32(b, q + 4)
elseif NODE_KINDS[id] then
node(ctx, NODE_KINDS[id], q, e, kf.nodes)
end
return nil, nil
end)
ctx.raw.keyframer = kf
end
-- ------------------------------------------------------------------------------------------------ parse
local function editor(ctx: Ctx, p: number, stop: number): (string?, number?)
local b = ctx.b
return each(ctx, p, stop, function(id: number, q: number, e: number): (string?, number?)
if id == C.MATERIAL then
material(ctx, q, e)
elseif id == C.OBJECT then
return object(ctx, q, e)
elseif id == C.MESH_VERSION and e - q >= 4 then
ctx.raw.meshVersion = readu32(b, q)
elseif id == C.MASTER_SCALE and e - q >= 4 then
ctx.raw.masterScale = readf32(b, q)
elseif id == C.AMBIENT_LIGHT then
ctx.raw.ambient = color(ctx, q, e)
elseif id == C.KEYFRAMER then
keyframer(ctx, q, e) -- some writers nest it here
end
return nil, nil
end)
end
-- parse(b, base, limit, opts) -> Raw | nil, message, offset
function Read.parse(b: buffer, base: number, limit: number, opts: any?): (Raw?, string?, number?)
if limit - base < 6 or readu16(b, base) ~= C.MAIN then
return nil, "not a 3DS file (no 0x4D4D main chunk)", base
end
local raw: Raw = { materials = {}, objects = {}, vertices = 0 }
local ctx: Ctx = { b = b, limit = limit, maxVertices = opts and opts.maxVertices or 2 ^ 24, raw = raw }
local size = readu32(b, base + 2)
if size < 6 then
return nil, "bad main chunk size", base
end
-- a main chunk declared longer than the data: truncated
if base + size > limit then
return nil, "truncated: the main chunk runs past the end of the data", base
end
local err, at = each(ctx, base + 6, base + size, function(id: number, q: number, e: number): (string?, number?)
if id == C.VERSION and e - q >= 4 then
raw.version = readu32(b, q)
elseif id == C.EDITOR then
return editor(ctx, q, e)
elseif id == C.KEYFRAMER then
keyframer(ctx, q, e)
end
return nil, nil
end)
if err then
return nil, err, at
end
return raw, nil, nil
end
return Read
+827
View File
@@ -0,0 +1,827 @@
--!strict
-- model/3ds/Write: Types.Scene -> 3DS. One named object per mesh (split at 65535 vertices / faces), vertices in world
-- space at the first node that shows the mesh, its world matrix as the mesh matrix, uvs (v flipped back to 3DS's
-- bottom-left origin), smoothing groups (extras["3ds"].smoothing from model/3ds, else 0 for flat-shaded faces and 1
-- for the others), per-face materials; Phong materials (extras["3ds"] when present, else from the PBR fields) with
-- texture maps (file names: texture.uri, or a name for texture.data put into opts.files); cameras (lens from yfov and
-- aspect, target along -Z) and lights (omni / spot; directional lights become spots); the keyframer: every node in
-- tree order (object nodes, $$$DUMMY nodes for empty ones, camera / light nodes with their targets), pivot 0, one key
-- per track or the keys of the first animation (frames = round(time * fps)), rotation keys as axis / angle deltas.
-- Mirroring nodes are written the way 3ds Max does (positive keyframer transform, mirror in the mesh matrix).
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Sampler = require("@formats/codecs/model/Sampler")
local Mat4 = require("@formats/codecs/model/Mat4")
local Flatten = require("@formats/codecs/model/MeshFlatten")
local Read = require("@formats/model/3ds/Read")
local Build = require("@formats/model/3ds/Build")
local Write = {}
local C = Read.C
local S = Types.Scene
local writeu32 = buffer.writeu32
local sqrt, abs = math.sqrt, math.abs
export type Options = { flipV: boolean?, fps: number?, name: string?, files: { [string]: any }?, smoothing: boolean? }
-- ------------------------------------------------------------------------------------------------ chunks
type W = Bytes.Writer
local function open(w: W, id: number): number
local at = w.pos
w:u16le(id)
w:u32le(0)
return at
end
local function close(w: W, at: number)
writeu32(w.buf, at + 2, w.pos - at)
end
local function leaf(w: W, id: number, fn: () -> ())
local at = open(w, id)
fn()
close(w, at)
end
local function name(s: string?, fallback: string): string
local n = string.gsub(s or "", "%z", "")
if n == "" then
n = fallback
end
return string.sub(n, 1, 63)
end
local function colorChunk(w: W, id: number, c: { number })
leaf(w, id, function()
leaf(w, C.RGBF, function()
for k = 1, 3 do
w:f32le(c[k] or 0)
end
end)
leaf(w, C.RGBB, function()
for k = 1, 3 do
w:u8(math.clamp(math.floor((c[k] or 0) * 255 + 0.5), 0, 255))
end
end)
end)
end
local function percentChunk(w: W, id: number, v: number)
leaf(w, id, function()
leaf(w, C.PERCENTW, function()
w:u16le(math.clamp(math.floor(v * 100 + 0.5), 0, 100))
end)
leaf(w, C.PERCENTF, function()
w:f32le(v * 100)
end)
end)
end
-- ------------------------------------------------------------------------------------------------ math
local function world(scene: Types.Scene): ({ [number]: { number } }, { [number]: number }, { number })
local W: { [number]: { number } } = {}
local parent: { [number]: number } = {}
local order: { number } = {}
local function visit(i: number, p: number?, pm: { number }, depth: number)
local n = scene.nodes[i]
if type(n) ~= "table" or W[i] or depth > 256 then
return
end
W[i] = S.mul(pm, S.nodeMatrix(n))
parent[i] = p or 0
table.insert(order, i)
for _, c in n.children or {} do
visit(c, i, W[i], depth + 1)
end
end
for _, r in scene.roots do
visit(r, nil, S.IDENTITY, 0)
end
return W, parent, order
end
local function col(m: { number }, c: number): (number, number, number)
return m[c * 4 + 1], m[c * 4 + 2], m[c * 4 + 3]
end
local function unit(x: number, y: number, z: number): (number, number, number)
local l = sqrt(x * x + y * y + z * z)
if l < 1e-30 then
return 0, 0, 0
end
return x / l, y / l, z / l
end
-- a quaternion -> the 3DS (clockwise angle, axis)
local function axisAngle(q: { number }): (number, number, number, number)
local x, y, z, w = q[1], q[2], q[3], q[4]
local n = sqrt(x * x + y * y + z * z + w * w)
if n < 1e-30 then
return 0, 0, 0, 0
end
x, y, z, w = x / n, y / n, z / n, w / n
local s = sqrt(x * x + y * y + z * z)
if s < 1e-12 then
return 0, 0, 0, 0
end
local angle = 2 * math.atan2(s, w)
return -angle, x / s, y / s, z / s
end
local function conj(q: { number }): { number }
return { -q[1], -q[2], -q[3], q[4] }
end
-- a channel's value at a time (codecs/model/Sampler: STEP, LINEAR with slerp, CUBICSPLINE)
local function sample(ch: Types.Channel, t: number): { number }
local f = Sampler.channel(ch)
if not f then
return if ch.path == "rotation" then { 0, 0, 0, 1 } else { 0, 0, 0 }
end
return f(t)
end
-- ------------------------------------------------------------------------------------------------ materials
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/gif"] = "gif", ["image/x-tga"] = "tga", ["image/webp"] = "webp" }
local function textureFiles(scene: Types.Scene, opts: Options): { [number]: string }
local files = opts.files
local base = string.match(opts.name or "", "([^/\\]-)%.[^.]*$") or "texture"
local out: { [number]: string } = {}
for i, tex in scene.textures do
local file = tex.uri
if not file or file == "" or string.sub(file, 1, 5) == "data:" then
file = string.format("%s_%d.%s", base, i, EXT[tex.mime or ""] or "png")
if tex.data and type(files) == "table" then
files[file] = tex.data
end
end
out[i] = file
end
return out
end
local MAP_IDS: { [string]: number } = {}
for id, kind in Read.MAPS do
MAP_IDS[kind] = id
end
local MAP_ORDER = { "diffuse", "diffuse2", "opacity", "bump", "specular", "shininess", "selfIllum", "reflection" }
local function writeMaterial(w: W, m: Types.Material, mname: string, files: { [number]: string })
local x = (m.extras and m.extras["3ds"] or {}) :: { [string]: any }
local bc = m.baseColor or { 1, 1, 1, 1 }
local diffuse = { bc[1], bc[2], bc[3] }
local shininess = math.clamp(1 - (m.roughness or 1), 0, 1)
local transparency = math.clamp(1 - (bc[4] or 1), 0, 1)
local e = m.emissive or { 0, 0, 0 }
local selfIllum = math.clamp(math.max(e[1], e[2], e[3]), 0, 1)
local at = open(w, C.MATERIAL)
leaf(w, C.MAT_NAME, function()
w:cstring(mname)
end)
colorChunk(w, C.MAT_AMBIENT, x.ambient or diffuse)
colorChunk(w, C.MAT_DIFFUSE, diffuse)
colorChunk(w, C.MAT_SPECULAR, x.specular or { 0.5, 0.5, 0.5 })
percentChunk(w, C.MAT_SHININESS, shininess)
percentChunk(w, C.MAT_SHIN_STRENGTH, x.shinStrength or 0.5)
percentChunk(w, C.MAT_TRANSPARENCY, transparency)
percentChunk(w, C.MAT_SELF_ILPCT, x.selfIllum or selfIllum)
leaf(w, C.MAT_SHADING, function()
w:u16le(x.shading or 3)
end)
if m.doubleSided then
leaf(w, C.MAT_TWO_SIDE, function() end)
end
if x.wire then
leaf(w, C.MAT_WIRE, function() end)
end
-- maps: the PBR texture refs first, then the other kinds model/3ds read
local maps: { [string]: any } = {}
local function fromRef(ref: Types.TextureRef?, saved: any): any
if not ref or not files[ref.texture] then
return nil
end
local s = saved or {}
local tf = ref.transform
return {
file = files[ref.texture], strength = s.strength or 1, tiling = s.tiling,
uscale = if tf and tf.scale then tf.scale[1] else s.uscale, vscale = if tf and tf.scale then tf.scale[2] else s.vscale,
uoffset = if tf and tf.offset then tf.offset[1] else s.uoffset, voffset = if tf and tf.offset then tf.offset[2] else s.voffset,
angle = if tf and tf.rotation then math.deg(tf.rotation) else s.angle,
}
end
local saved = (x.maps or {}) :: { [string]: any }
maps.diffuse = fromRef(m.baseColorTexture, saved.diffuse)
maps.selfIllum = fromRef(m.emissiveTexture, saved.selfIllum)
for kind, s in saved do
if maps[kind] == nil and kind ~= "diffuse" and kind ~= "selfIllum" and type(s) == "table" then
maps[kind] = fromRef(if s.texture then { texture = s.texture } else nil, s)
end
end
for _, kind in MAP_ORDER do
local mp = maps[kind]
if mp then
local mat = open(w, MAP_IDS[kind])
leaf(w, C.PERCENTW, function()
w:u16le(math.clamp(math.floor((mp.strength or 1) * 100 + 0.5), 0, 100))
end)
leaf(w, C.MAP_FILE, function()
w:cstring(name(mp.file, "texture"))
end)
if mp.tiling then
leaf(w, C.MAP_TILING, function()
w:u16le(mp.tiling)
end)
end
for _, f in { { C.MAP_USCALE, mp.uscale }, { C.MAP_VSCALE, mp.vscale }, { C.MAP_UOFFSET, mp.uoffset }, { C.MAP_VOFFSET, mp.voffset }, { C.MAP_ANGLE, mp.angle } } do
local v = f[2]
if type(v) == "number" then
leaf(w, f[1], function()
w:f32le(v)
end)
end
end
close(w, mat)
end
end
close(w, at)
end
-- ------------------------------------------------------------------------------------------------ meshes
type Part = { name: string, positions: { number }, uvs: { number }?, faces: { number }, smooth: { number }, mats: { [number]: { number } } }
-- the mesh as 3DS parts (local space), or nil, message
local function parts(mesh: Types.Mesh, base: string, opts: Options): ({ Part }?, string?)
local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { mesh } }, function(n: string): boolean
return n == "TEXCOORD_0" or n == "NORMAL"
end, { triangulate = true })
if not merged then
return nil, err
end
local P = merged.attrs.POSITION.values
local N = merged.attrs.NORMAL and merged.attrs.NORMAL.values
local T = merged.attrs.TEXCOORD_0
local tv, tc = if T then T.values else nil, if T then T.components else 0
local flipV = opts.flipV ~= false
local corners = merged.corners
-- per face: material, smoothing group
local nf = #corners // 3
local fmat, fsg = table.create(nf, 0), table.create(nf, 1)
for _, part in merged.parts do
local prim: any = part.prim
local saved = prim.extras and prim.extras["3ds"] and prim.extras["3ds"].smoothing
local savedOk = type(saved) == "table" and #saved == part.faceCount and (prim.mode or "triangles") == "triangles"
for f = part.firstFace + 1, part.firstFace + part.faceCount do
fmat[f] = if type(prim.material) == "number" then prim.material else 0
if savedOk then
fsg[f] = saved[f - part.firstFace]
elseif N then
-- flat when every corner normal is the face normal
local a, b, c = corners[f * 3 - 2], corners[f * 3 - 1], corners[f * 3]
local e1 = { P[b * 3 + 1] - P[a * 3 + 1], P[b * 3 + 2] - P[a * 3 + 2], P[b * 3 + 3] - P[a * 3 + 3] }
local e2 = { P[c * 3 + 1] - P[a * 3 + 1], P[c * 3 + 2] - P[a * 3 + 2], P[c * 3 + 3] - P[a * 3 + 3] }
local nx, ny, nz = unit(e1[2] * e2[3] - e1[3] * e2[2], e1[3] * e2[1] - e1[1] * e2[3], e1[1] * e2[2] - e1[2] * e2[1])
local flat = true
for _, v in { a, b, c } do
local vx, vy, vz = unit(N[v * 3 + 1], N[v * 3 + 2], N[v * 3 + 3])
if vx * nx + vy * ny + vz * nz < 0.9998 then
flat = false
end
end
fsg[f] = if flat then 0 else 1
end
end
end
local out: { Part } = {}
local cur: Part? = nil
local remap: { [number]: number } = {}
local count = 0
for f = 1, nf do
local fresh = 0
for k = 1, 3 do
if not remap[corners[f * 3 - 3 + k]] then
fresh += 1
end
end
if cur == nil or count + fresh > 65535 or #cur.smooth >= 65535 then
cur = { name = if #out == 0 then base else string.sub(base, 1, 56) .. "." .. #out, positions = {}, uvs = if tv then {} else nil, faces = {}, smooth = {}, mats = {} }
table.insert(out, cur :: Part)
remap, count = {}, 0
end
local p = cur :: Part
for k = 1, 3 do
local v = corners[f * 3 - 3 + k]
local o = remap[v]
if not o then
o = count
count += 1
remap[v] = o
table.move(P, v * 3 + 1, v * 3 + 3, #p.positions + 1, p.positions)
if tv and p.uvs then
local u, vv = tv[v * tc + 1] or 0, tv[v * tc + 2] or 0
table.insert(p.uvs, u)
table.insert(p.uvs, if flipV then 1 - vv else vv)
end
end
table.insert(p.faces, o)
end
table.insert(p.smooth, fsg[f])
local mi = fmat[f]
if mi > 0 then
p.mats[mi] = p.mats[mi] or {}
table.insert(p.mats[mi], #p.smooth - 1)
end
end
return out, nil
end
local function writeMesh(w: W, part: Part, M: { number }, matNames: { [number]: string })
local at = open(w, C.OBJECT)
w:cstring(part.name)
local tm = open(w, C.TRIMESH)
local nv = #part.positions // 3
leaf(w, C.VERTICES, function()
w:u16le(nv)
local p = part.positions
for v = 0, nv - 1 do
local x, y, z = Mat4.point(M, p[v * 3 + 1], p[v * 3 + 2], p[v * 3 + 3])
w:f32le(x)
w:f32le(y)
w:f32le(z)
end
end)
if part.uvs then
local uvs = part.uvs
leaf(w, C.UVS, function()
w:u16le(nv)
for i = 1, nv * 2 do
w:f32le(uvs[i] or 0)
end
end)
end
leaf(w, C.MATRIX, function()
for _, c in { 0, 1, 2, 3 } do
local x, y, z = col(M, c)
w:f32le(x)
w:f32le(y)
w:f32le(z)
end
end)
local fl = open(w, C.FACES)
local nf = #part.smooth
w:u16le(nf)
for f = 0, nf - 1 do
w:u16le(part.faces[f * 3 + 1])
w:u16le(part.faces[f * 3 + 2])
w:u16le(part.faces[f * 3 + 3])
w:u16le(7) -- edges AB, BC, CA visible
end
local mats: { number } = {}
for mi in part.mats do
table.insert(mats, mi)
end
table.sort(mats)
for _, mi in mats do
local list = part.mats[mi]
leaf(w, C.FACE_MAT, function()
w:cstring(matNames[mi])
w:u16le(#list)
for _, f in list do
w:u16le(f)
end
end)
end
leaf(w, C.SMOOTH, function()
for _, s in part.smooth do
w:u32le(s)
end
end)
close(w, fl)
close(w, tm)
close(w, at)
end
-- ------------------------------------------------------------------------------------------------ cameras / lights
-- the eye, target and roll of a node's world matrix (looking down -Z, Y up)
local function aim(m: { number }, dist: number): ({ number }, { number }, number)
local p = { m[13], m[14], m[15] }
local fx, fy, fz = unit(-m[9], -m[10], -m[11])
if fx == 0 and fy == 0 and fz == 0 then
fx, fy, fz = 0, 0, -1
end
local t = { p[1] + fx * dist, p[2] + fy * dist, p[3] + fz * dist }
-- the roll: the angle from the unrolled up vector (Build.lookAt) to the node's Y axis
local q0 = Build.lookAt(p, t, 0)
local m0 = Mat4.fromQuat(q0)
local ux, uy, uz = unit(m[5], m[6], m[7])
local cu = ux * m0[5] + uy * m0[6] + uz * m0[7]
local cr = ux * m0[1] + uy * m0[2] + uz * m0[3]
return p, t, math.deg(math.atan2(-cr, cu))
end
local function writeCamera(w: W, cname: string, cam: Types.Camera, m: { number }, dist: number)
local p, t, roll = aim(m, dist)
local aspect = cam.aspect or 4 / 3
local yfov = if cam.type == "perspective" and cam.yfov then cam.yfov else math.rad(45)
local hfov = math.deg(2 * math.atan(math.tan(yfov / 2) * aspect))
local at = open(w, C.OBJECT)
w:cstring(cname)
local c = open(w, C.CAMERA)
for _, v in { p[1], p[2], p[3], t[1], t[2], t[3], roll, 2400 / math.max(hfov, 1e-3) } do
w:f32le(v)
end
leaf(w, C.CAM_RANGES, function()
w:f32le(cam.znear or 0)
w:f32le(cam.zfar or 1000)
end)
close(w, c)
close(w, at)
end
local function writeLight(w: W, lname: string, l: Types.Light, m: { number }, dist: number)
local p, t = aim(m, dist)
local at = open(w, C.OBJECT)
w:cstring(lname)
local c = open(w, C.LIGHT)
for k = 13, 15 do
w:f32le(m[k])
end
leaf(w, C.RGBF, function()
for k = 1, 3 do
w:f32le(l.color and l.color[k] or 1)
end
end)
if l.type ~= "point" then
local inner = if l.type == "spot" then (l.innerCone or 0) else math.rad(45)
local outer = if l.type == "spot" then (l.outerCone or math.pi / 4) else math.rad(45)
leaf(w, C.SPOT, function()
for k = 1, 3 do
w:f32le(t[k])
end
w:f32le(math.deg(inner * 2))
w:f32le(math.deg(math.max(outer, inner) * 2))
end)
end
if l.range and l.range > 0 then
leaf(w, C.ATTENUATE, function() end)
leaf(w, C.OUTER_RANGE, function()
w:f32le(l.range :: number)
end)
end
leaf(w, C.MULTIPLIER, function()
w:f32le(l.intensity or 1)
end)
close(w, c)
close(w, at)
return p
end
-- ------------------------------------------------------------------------------------------------ keyframer
local function writeTrack(w: W, id: number, frames: { number }, values: { number }, size: number)
leaf(w, id, function()
w:u16le(0)
w:u32le(0)
w:u32le(0)
w:u32le(#frames)
for k, f in frames do
w:u32le(f)
w:u16le(0)
for c = 1, size do
w:f32le(values[(k - 1) * size + c])
end
end
end)
end
type KfNode = {
chunk: number, name: string, instance: string?, parent: number, -- parent: kf index or -1
frames: { [string]: { number } }, values: { [string]: { number } },
}
-- frames (rounded, strictly increasing) and the indices of the channel keys they keep
local function frameKeys(ch: Types.Channel, fps: number): ({ number }, { number })
local IN = S.reader(ch.input) :: any
local frames, keep = {}, {}
for k = 0, ch.input.count - 1 do
local f = math.max(0, math.floor(IN(k, 0) * fps + 0.5))
if #frames == 0 or f > frames[#frames] then
table.insert(frames, f)
table.insert(keep, k)
end
end
return frames, keep
end
local function channelValues(ch: Types.Channel, keep: { number }, comps: number): { { number } }
local OUT = S.reader(ch.output) :: any
local cubic = ch.interpolation == "CUBICSPLINE"
local out = {}
for _, k in keep do
local e = if cubic then k * 3 + 1 else k
local v = table.create(comps, 0)
for c = 1, comps do
v[c] = OUT(e, c - 1)
end
table.insert(out, v)
end
return out
end
local function rotTrack(quats: { { number } }): { number }
local vals = {}
local prev: { number }? = nil
for _, q in quats do
local d = q
if prev then
d = Build.qmul(conj(prev), q)
if d[4] < 0 then
d = { -d[1], -d[2], -d[3], -d[4] }
end
end
local a, x, y, z = axisAngle(d)
table.insert(vals, a)
table.insert(vals, x)
table.insert(vals, y)
table.insert(vals, z)
prev = q
end
return vals
end
-- ------------------------------------------------------------------------------------------------ encode
function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?)
local o: Options = opts or {}
local fps = o.fps or 30
local W, parentOf, order = world(scene)
local w = Bytes.writer(65536)
local main = open(w, C.MAIN)
leaf(w, C.VERSION, function()
w:u32le(3)
end)
local ed = open(w, C.EDITOR)
leaf(w, C.MESH_VERSION, function()
w:u32le(3)
end)
-- materials (unique names)
local files = textureFiles(scene, o)
local matNames: { [number]: string } = {}
local used: { [string]: boolean } = {}
local function unique(base: string): string
local n, k = base, 1
while used[string.lower(n)] do
k += 1
n = string.sub(base, 1, 56) .. "_" .. k
end
used[string.lower(n)] = true
return n
end
for i, m in scene.materials do
matNames[i] = unique(name(m.name, "Material" .. i))
writeMaterial(w, m, matNames[i], files)
end
leaf(w, C.MASTER_SCALE, function()
w:f32le(1)
end)
-- meshes: at the first node showing them; their kf world (mirrors moved out of the keyframer)
used = {}
local firstNode: { [number]: number } = {}
for _, i in order do
local mi = scene.nodes[i].mesh
if mi and scene.meshes[mi] and not firstNode[mi] then
firstNode[mi] = i
end
end
local meshParts: { [number]: { Part } } = {}
local meshM: { [number]: { number } } = {}
for mi, mesh in scene.meshes do
local ni = firstNode[mi]
if ni == nil and #scene.nodes > 0 then
continue
end
local list, err = parts(mesh, unique(name(mesh.name, "Mesh" .. mi)), o)
if not list then
return nil, err
end
local M = if ni then W[ni] else S.IDENTITY
if not Mat4.inverse(M) then
M = S.IDENTITY
end
meshParts[mi], meshM[mi] = list, M
for _, part in list do
used[string.lower(part.name)] = true
writeMesh(w, part, M, matNames)
end
end
-- the keyframer world of each node: W, or W * flip-x where the node's mesh matrix mirrors
local KW: { [number]: { number } } = {}
for _, i in order do
local n = scene.nodes[i]
local m = W[i]
if n.mesh and meshM[n.mesh] and Build.det3(meshM[n.mesh]) < 0 then
m = S.mul(m, Mat4.scaling(-1, 1, 1))
end
KW[i] = m
end
local kfs: { KfNode } = {}
local kfOf: { [number]: number } = {}
local anim = scene.animations[1]
local byNode: { [number]: { [string]: Types.Channel } } = {}
if anim then
for _, ch in anim.channels do
if ch.path ~= "weights" then
byNode[ch.node] = byNode[ch.node] or {}
byNode[ch.node][ch.path] = ch
end
end
end
local lastFrame = 0
local function single(v: { number }): { number }
return table.clone(v)
end
for _, i in order do
local n = scene.nodes[i]
local p = parentOf[i]
local pk = if p ~= 0 then kfOf[p] else nil
local camOrLight = (n.camera and scene.cameras[n.camera]) or (n.light and scene.lights[n.light])
local dist = 100
local function placeCamLight(kind: number, objName: string, tgtChunk: number?)
local pos, tgt, roll = aim(W[i], dist)
local kn: KfNode = { chunk = kind, name = objName, parent = -1, frames = { pos = { 0 }, roll = { 0 } }, values = { pos = pos, roll = { roll } } }
table.insert(kfs, kn)
local idx = #kfs
-- animated root cameras / lights: position, target and roll at the key times
local chs: any = if p == 0 then byNode[i] else nil
local targetFrames, targetVals = { 0 }, tgt
if chs and (chs.translation or chs.rotation) then
local fr: { [number]: boolean } = {}
local frames: { number } = {}
local list: { Types.Channel } = {}
table.insert(list, chs.translation)
table.insert(list, chs.rotation)
for _, ch in list do
for _, f in (frameKeys(ch, fps)) do
if not fr[f] then
fr[f] = true
table.insert(frames, f)
end
end
end
table.sort(frames)
local pv, tv, rv = {}, {}, {}
for _, f in frames do
local t = f / fps
local ct, cr = chs.translation, chs.rotation
local tr = if ct then sample(ct, t) else { W[i][13], W[i][14], W[i][15] }
local rq = if cr then sample(cr, t) else (n.rotation or { 0, 0, 0, 1 })
local sc = n.scale or { 1, 1, 1 }
local ps, ts, rs = aim(Mat4.compose(tr, rq, sc), dist)
table.move(ps, 1, 3, #pv + 1, pv)
table.move(ts, 1, 3, #tv + 1, tv)
table.insert(rv, rs)
lastFrame = math.max(lastFrame, f)
end
kn.frames.pos, kn.values.pos = frames, pv
kn.frames.roll, kn.values.roll = frames, rv
targetFrames, targetVals = frames, tv
end
if tgtChunk then
table.insert(kfs, { chunk = tgtChunk, name = objName, parent = -1, frames = { pos = targetFrames }, values = { pos = targetVals } })
end
if kind ~= 0xB003 then
kn.frames.roll, kn.values.roll = nil :: any, nil :: any
end
return idx
end
local function camLight(onlyThis: boolean): number?
if not camOrLight then
return nil
end
local idx: number? = nil
if n.camera and scene.cameras[n.camera] then
local cname = unique(name(scene.cameras[n.camera].name or n.name, "Camera" .. n.camera))
writeCamera(w, cname, scene.cameras[n.camera], W[i], dist)
idx = placeCamLight(0xB003, cname, 0xB004)
end
if n.light and scene.lights[n.light] then
local l = scene.lights[n.light]
local lname = unique(name(l.name or n.name, "Light" .. n.light))
writeLight(w, lname, l, W[i], dist)
local k = placeCamLight(if l.type == "point" then 0xB005 else 0xB007, lname, if l.type == "point" then nil else 0xB006)
idx = idx or k
end
if onlyThis and idx then
kfOf[i] = idx
-- the node's frame in the keyframer: the camera / light pose
local kn = kfs[idx]
local pos = kn.values.pos
local m: { number } = W[i]
if kn.chunk == 0xB005 then
KW[i] = Mat4.translation(pos[1], pos[2], pos[3])
else
local _, tgt, roll = aim(m, dist)
KW[i] = Mat4.compose(pos, Build.lookAt({ pos[1], pos[2], pos[3] }, tgt, if kn.chunk == 0xB003 then roll else 0), nil)
end
end
return idx
end
if n.mesh == nil and camOrLight then
camLight(true)
continue
end
-- an object node (or a dummy) with the node's transform relative to its keyframer parent
local pkw = if p ~= 0 and kfOf[p] then KW[p] else S.IDENTITY
local inv = Mat4.inverse(pkw) or Mat4.identity()
local L = S.mul(inv, KW[i])
local t, r, s = Mat4.decompose(L)
local plist = if n.mesh then meshParts[n.mesh] else nil
local objName = if plist then plist[1].name else "$$$DUMMY"
local instance = if plist and n.name and n.name ~= objName then name(n.name, objName) elseif not plist then name(n.name, "Dummy" .. i) else nil
local kn: KfNode = { chunk = 0xB002, name = objName, instance = instance, parent = if pk then pk - 1 else -1, frames = { pos = { 0 }, rot = { 0 }, scl = { 0 } }, values = { pos = single(t), rot = rotTrack({ r }), scl = single(s) } }
-- animation keys, when the keyframer transform is the node's own (no mirror fix-up up the tree)
local chs = byNode[i]
if chs then
local own = S.nodeMatrix(n)
local same = true
for k = 1, 16 do
if abs(own[k] - L[k]) > 1e-5 * math.max(1, abs(own[k])) then
same = false
end
end
if same then
for path, field in { translation = "pos", rotation = "rot", scale = "scl" } :: { [string]: string } do
local ch = chs[path]
if ch then
local frames, keep = frameKeys(ch, fps)
local vals = channelValues(ch, keep, if path == "rotation" then 4 else 3)
lastFrame = math.max(lastFrame, frames[#frames] or 0)
kn.frames[field] = frames
if path == "rotation" then
kn.values[field] = rotTrack(vals)
else
local flat = {}
for _, v in vals do
table.move(v, 1, 3, #flat + 1, flat)
end
kn.values[field] = flat
end
end
end
end
end
table.insert(kfs, kn)
kfOf[i] = #kfs
for k = 2, if plist then #plist else 0 do
local extra = table.clone(kn)
extra.name, extra.instance = (plist :: { Part })[k].name, nil
table.insert(kfs, extra)
end
camLight(false)
end
close(w, ed)
-- the keyframer
local kf = open(w, C.KEYFRAMER)
leaf(w, C.KF_HDR, function()
w:u16le(5)
w:cstring("MAXSCENE")
w:u32le(math.max(lastFrame, 100))
end)
leaf(w, C.KF_FRAMES, function()
w:u32le(0)
w:u32le(math.max(lastFrame, 100))
end)
for id, kn in kfs do
local nc = open(w, kn.chunk)
leaf(w, C.NODE_ID, function()
w:u16le(id - 1)
end)
leaf(w, C.NODE_HDR, function()
w:cstring(kn.name)
w:u16le(0x4000)
w:u16le(0)
w:u16le(if kn.parent >= 0 then kn.parent else 0xFFFF)
end)
if kn.instance then
leaf(w, C.NODE_INSTANCE, function()
w:cstring(kn.instance :: string)
end)
end
if kn.chunk == 0xB002 then
leaf(w, C.NODE_PIVOT, function()
w:f32le(0)
w:f32le(0)
w:f32le(0)
end)
end
for _, tr in { { "pos", C.TRACK_POS, 3 }, { "rot", C.TRACK_ROT, 4 }, { "scl", C.TRACK_SCALE, 3 }, { "roll", C.TRACK_ROLL, 1 } } do
local field = tr[1] :: string
local frames = kn.frames[field]
if frames then
writeTrack(w, tr[2] :: number, frames, kn.values[field], tr[3] :: number)
end
end
close(w, nc)
end
close(w, kf)
close(w, main)
local out = buffer.create(w.pos)
buffer.copy(out, 0, w.buf, 0, w.pos)
return out, nil
end
return Write
+100
View File
@@ -0,0 +1,100 @@
--!strict
-- model/3ds: Autodesk 3D Studio (.3ds, the chunked binary of 3D Studio R4 / 3ds Max's exporter). New code, from the
-- chunk layout as documented by the 3DS File Toolkit notes and read by assimp's 3DS importer (BSD-3: the reference
-- for transforms and conventions; no code ported) and lib3ds (layouts only).
-- Reads: triangle meshes (vertices, faces, uvs (TEXCOORD_0, flipped to glTF's top-left origin), the mesh matrix,
-- per-face materials -> one primitive per material, smoothing groups -> NORMAL: corners of faces sharing a group and
-- a position are averaged, group 0 is flat; extras["3ds"].smoothing keeps the groups per triangle), materials
-- (ambient / diffuse / specular colours, shininess, shininess strength, transparency, self-illumination, two-sided,
-- shading, wire; texture maps -> Textures with `uri` (never loaded: F.model.loadTextures resolves them), diffuse as
-- baseColorTexture, self-illumination as emissiveTexture, the others in extras["3ds"].maps; uv scale / offset /
-- angle as a texture transform), cameras (lens -> yfov at a 4:3 aspect, near / far ranges; -Z looking at the
-- target, rolled), lights (omni -> point, spot -> spot with hotspot / falloff cones, colour, multiplier, outer range),
-- the keyframer (node hierarchy by node id, $$$DUMMY nodes with their instance names, instances of one object,
-- pivots, the first key of every track as the node's TRS, tracks with several keys -> one animation: position /
-- scale keys linear, rotation keys accumulated from their axis / angle deltas, cameras / spotlights sampled from
-- their position, target and roll tracks; TCB spline parameters are ignored, times are frame / opts.fps). Objects
-- without a keyframer node stand at their mesh matrix. meta.up = "z"; meta.source has version, masterScale (not
-- applied), the keyframer frame range.
-- Writes: see model/3ds/Write (meshes, materials, texture names, cameras, lights, the keyframer and the first
-- animation). Not supported: 3DS project / material library files (.prj, .mli), morph / hide tracks, procedural
-- and shadow parameters, background / atmosphere settings, mesh limits beyond 65535 vertices per object (split on
-- write), vertex colours / normals (3DS has neither; normals come from smoothing groups).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Read = require("@formats/model/3ds/Read")
local Build = require("@formats/model/3ds/Build")
local Write = require("@formats/model/3ds/Write")
-- ------------------------------------------------------------------------------------------------ contract
local ThreeDs = {
name = "3ds",
category = "model",
extensions = { "3ds" },
mime = { "application/x-3ds", "image/x-3ds" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten", "codecs/model/Sampler" },
caps = { decode = true, encode = true, materials = true, textures = true, animation = true, cameras = true, lights = true, instancing = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
normals: boolean?, -- compute NORMAL from the smoothing groups (default true; false keeps the file's vertices)
flipV: boolean?, -- TEXCOORD_0.v = 1 - v (default true: glTF's convention)
fps: number?, -- keyframer frames per second (default 30, 3ds Max's default)
maxVertices: number?, -- refuse more vertices in total (default 2^24)
}
export type EncodeOptions = {
flipV: boolean?, -- default true (the inverse of decode)
fps: number?, -- seconds -> keyframer frames (default 30)
name: string?, -- the destination's file name (names textures that have no uri)
files: { [string]: any }?, -- receives the bytes of textures that have data but no uri
}
-- ------------------------------------------------------------------------------------------------ sniff
function ThreeDs.sniff(r: Bytes.Reader): number
local h = r:peek(8)
if #h < 8 or string.byte(h, 1) ~= 0x4D or string.byte(h, 2) ~= 0x4D then
return 0
end
local b1, b2, b3, b4, c1, c2 = string.byte(h, 3, 8)
local size = b1 + b2 * 256 + b3 * 65536 + b4 * 16777216
local child = c1 + c2 * 256
if size < 16 or not (child == 0x0002 or child == 0x3D3D or child == 0xB000) then
return 0
end
return if size == r.limit - r.pos then 0.95 else 0.7
end
-- ------------------------------------------------------------------------------------------------ decode
function ThreeDs.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local raw, msg, at = Read.parse(r.buf, r.base, r.limit, opts)
if not raw then
return nil, Err.from(msg, at)
end
-- the scene builder is plain (not native) code: a bug there must not escape as an error
local ok, scene = pcall(Build.scene, raw, opts :: any)
if not ok then
return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene))
end
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function ThreeDs.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(scene) ~= "table" or scene.kind ~= "scene" then
return nil, Err.new(Err.ARG, "needs a Scene")
end
local ok, out, err = pcall(Write.encode, scene, opts :: any)
if not ok then
return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out))
end
if not out then
return nil, Err.new(Err.ARG, tostring(err))
end
return out, nil
end
return ThreeDs
+576
View File
@@ -0,0 +1,576 @@
--!strict
-- model/b3d/Read: the BB3D chunk tree -> Types.Scene (see model/b3d for what is read and how it is mapped). Chunks are
-- walked with containers/Chunks (4-byte id, u32 little-endian size, no padding); fields are read through core/Bytes
-- readers over each chunk body, so a short body sets the reader's sticky error instead of reading past the end.
-- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from).
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Chunks = require("@formats/containers/Chunks")
local Mat4 = require("@formats/codecs/model/Mat4")
local Read = {}
export type Options = {
resolve: ((uri: string) -> any)?,
files: { [string]: any }?,
maxVertices: number?,
maxDepth: number?,
}
local LAYOUT: Chunks.Layout = { maxChunks = 1000000 }
local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" }
type Brush = { name: string, color: { number }, shininess: number, blend: number, fx: number, textures: { number } }
type TexInfo = { file: string, flags: number, blend: number, offset: { number }, scale: { number }, rotation: number, index: number }
type MeshRec = { mesh: number, node: number, count: number, joints: { { number } }, weights: { { number } } }
type Bone = { node: number, target: MeshRec?, list: { number } }
type Keys = { t: { [number]: { number } }, s: { [number]: { number } }, r: { [number]: { number } } }
-- the file's left-handed Y-up values in glTF's right-handed frame: z mirrored; quaternions as w x y z, conjugated
-- (Blitz3D stores the inverse rotation, as assimp's reader reads them) then mirrored
local function vec(r: Bytes.Reader): { number }
local x, y, z = r:f32le(), r:f32le(), r:f32le()
return { x, y, -z }
end
local function quat(r: Bytes.Reader): { number }
local w, x, y, z = r:f32le(), r:f32le(), r:f32le(), r:f32le()
local l = math.sqrt(w * w + x * x + y * y + z * z)
if l < 1e-12 or l ~= l then
return { 0, 0, 0, 1 }
end
return { x / l, y / l, -z / l, w / l }
end
local function fetcher(opts: Options?): (string) -> buffer?
local files = opts and opts.files
local resolve = opts and opts.resolve
return function(uri: string): buffer?
local v: any = if type(files) == "table" then files[uri] else nil
if v == nil and type(resolve) == "function" then
local ok, res = pcall(resolve, uri)
v = if ok then res else nil
end
return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil
end
end
-- scene(r, opts) -> Scene | nil, message, kind
function Read.scene(src: Bytes.Reader, opts: Options?): (Types.Scene?, string?, string?)
local buf = src.buf
local maxVertices = opts and opts.maxVertices or 2 ^ 24
local maxDepth = opts and opts.maxDepth or 256
local fetch = fetcher(opts)
local top = Chunks.walk(buf, src.base, src.limit, LAYOUT)
local head = top[1]
if not head or head.id ~= "BB3D" then
return nil, "not a BB3D file", nil
end
if head.truncated then
return nil, "truncated", "truncated"
end
local hr = Bytes.reader(buf, head.offset, head.size)
local version = hr:i32le()
if hr.err then
return nil, "truncated", "truncated"
end
local scene = Types.Scene.new()
local texs: { TexInfo } = {}
local brushes: { Brush } = {}
local materialOf: { [number]: number } = {} -- brush index (0-based) -> material
local meshes: { MeshRec } = {}
local bones: { Bone } = {}
local nodeKeys: { [number]: Keys } = {}
local anim: { frames: number, fps: number, flags: number }? = nil
local lastMesh: MeshRec? = nil
local totalVertices = 0
local failure: string?, failKind: string? = nil, nil
local function fail(msg: string, kind: string?)
if not failure then
failure, failKind = msg, kind
end
end
local function body(c: Chunks.Chunk): Bytes.Reader
if c.truncated then
fail("truncated " .. c.id .. " chunk", "truncated")
end
return Bytes.reader(buf, c.offset, c.avail)
end
local function readTexs(r: Bytes.Reader)
while r.pos < r.limit and not r.err do
local file = r:cstring()
local t: TexInfo = { file = file, flags = r:i32le(), blend = r:i32le(), offset = { r:f32le(), r:f32le() }, scale = { r:f32le(), r:f32le() }, rotation = r:f32le(), index = 0 }
if r.err then
return fail("truncated TEXS entry", "truncated")
end
local tex: Types.Texture = { name = string.match(file, "([^/\\]+)$") or file, uri = file, mime = MIME[string.lower(string.match(file, "%.(%w+)$") or "")] }
local data = fetch(file)
if not data then
local base = string.match(file, "([^/\\]+)$")
if base and base ~= file then
data = fetch(base)
end
end
tex.data = data
if bit32.band(t.flags, 48) ~= 0 then
tex.sampler = { wrapS = if bit32.band(t.flags, 16) ~= 0 then "clamp" else "repeat", wrapT = if bit32.band(t.flags, 32) ~= 0 then "clamp" else "repeat" }
end
tex.extras = { b3d = { flags = t.flags, blend = t.blend } }
table.insert(scene.textures, tex)
t.index = #scene.textures
table.insert(texs, t)
end
end
local function readBrus(r: Bytes.Reader)
local n = r:i32le()
if r.err or n < 0 or n > 8 then
return fail("bad BRUS texture count")
end
while r.pos < r.limit and not r.err do
local b: Brush = { name = r:cstring(), color = { r:f32le(), r:f32le(), r:f32le(), r:f32le() }, shininess = r:f32le(), blend = r:i32le(), fx = r:i32le(), textures = {} }
for i = 1, n do
b.textures[i] = r:i32le()
end
if r.err then
return fail("truncated BRUS entry", "truncated")
end
table.insert(brushes, b)
end
end
-- the material of brush id (0-based) | nil for -1 / out of range
local function material(id: number): number?
if id < 0 or id >= #brushes then
return nil
end
local have = materialOf[id]
if have then
return have
end
local b = brushes[id + 1]
local m = Types.Scene.material(b.name ~= "" and b.name or nil)
local c = b.color
local function clamp01(v: number): number
return if v ~= v then 1 else math.clamp(v, 0, 1)
end
m.baseColor = { clamp01(c[1]), clamp01(c[2]), clamp01(c[3]), clamp01(c[4]) }
m.metallic = 0
m.roughness = 1 - 0.8 * clamp01(b.shininess)
m.doubleSided = bit32.band(b.fx, 16) ~= 0
if m.baseColor[4] < 1 or bit32.band(b.fx, 32) ~= 0 then
m.alphaMode = "blend"
end
if bit32.band(b.fx, 1) ~= 0 then
m.extensions = { KHR_materials_unlit = {} }
end
local extraTex: { number } = {}
for i, tid in b.textures do
local t = texs[tid + 1]
if tid >= 0 and t then
if not m.baseColorTexture then
local ref: Types.TextureRef = { texture = t.index, texCoord = if bit32.band(t.flags, 65536) ~= 0 then 1 else nil }
local o, s, rot = t.offset, t.scale, t.rotation
if o[1] ~= 0 or o[2] ~= 0 or s[1] ~= 1 or s[2] ~= 1 or rot ~= 0 then
ref.transform = { offset = { o[1], o[2] }, scale = { s[1], s[2] }, rotation = rot }
end
m.baseColorTexture = ref
if bit32.band(t.flags, 4) ~= 0 then
m.alphaMode = "mask"
elseif bit32.band(t.flags, 2) ~= 0 then
m.alphaMode = "blend"
end
else
extraTex[i] = t.index
end
end
end
m.extras = { b3d = { shininess = b.shininess, blend = b.blend, fx = b.fx, textures = if next(extraTex) then extraTex else nil } }
table.insert(scene.materials, m)
materialOf[id] = #scene.materials
return #scene.materials
end
local function readMesh(r: Bytes.Reader, nodeIndex: number): number?
local master = r:i32le()
if r.err then
fail("truncated MESH", "truncated")
return nil
end
local list = Chunks.walk(buf, r.pos, r.limit, LAYOUT)
local attrs: { [string]: Types.Accessor }? = nil
local count = 0
local mesh: Types.Mesh = { primitives = {} }
local rec: MeshRec = { mesh = 0, node = nodeIndex, count = 0, joints = {}, weights = {} }
for _, c in list do
local cr = body(c)
if c.id == "VRTS" and not attrs then
local flags, sets, size = cr:i32le(), cr:i32le(), cr:i32le()
if cr.err or sets < 0 or sets > 8 or size < 0 or size > 4 then
fail("bad VRTS header")
return nil
end
local hasN, hasC = bit32.band(flags, 1) ~= 0, bit32.band(flags, 2) ~= 0
local stride = 12 + (if hasN then 12 else 0) + (if hasC then 16 else 0) + sets * size * 4
local n = (cr.limit - cr.pos) // stride
totalVertices += n
if totalVertices > maxVertices then
fail(string.format("limit: %d vertices is over the %d vertex limit", totalVertices, maxVertices), "limit")
return nil
end
local pos = buffer.create(n * 12)
local nrm = if hasN then buffer.create(n * 12) else nil
local col = if hasC then buffer.create(n * 16) else nil
local uvs: { buffer } = {}
for s = 1, sets do
uvs[s] = buffer.create(n * 8)
end
local readf32, writef32 = buffer.readf32, buffer.writef32
local p = cr.pos
for i = 0, n - 1 do
writef32(pos, i * 12, readf32(buf, p))
writef32(pos, i * 12 + 4, readf32(buf, p + 4))
writef32(pos, i * 12 + 8, -readf32(buf, p + 8))
p += 12
if nrm then
writef32(nrm, i * 12, readf32(buf, p))
writef32(nrm, i * 12 + 4, readf32(buf, p + 4))
writef32(nrm, i * 12 + 8, -readf32(buf, p + 8))
p += 12
end
if col then
for k = 0, 3 do
writef32(col, i * 16 + k * 4, readf32(buf, p + k * 4))
end
p += 16
end
for s = 1, sets do
if size >= 1 then
writef32(uvs[s], i * 8, readf32(buf, p))
end
if size >= 2 then
writef32(uvs[s], i * 8 + 4, readf32(buf, p + 4))
end
p += size * 4
end
end
local a: { [string]: Types.Accessor } = { POSITION = Types.Scene.accessor(pos, "f32", 3, n) }
if nrm then
a.NORMAL = Types.Scene.accessor(nrm, "f32", 3, n)
end
if col then
a.COLOR_0 = Types.Scene.accessor(col, "f32", 4, n)
end
if size > 0 then
for s = 1, sets do
a["TEXCOORD_" .. (s - 1)] = Types.Scene.accessor(uvs[s], "f32", 2, n)
end
end
attrs, count = a, n
mesh.extras = { b3d = { vertexFlags = flags, texCoordSets = sets, texCoordSize = size } }
elseif c.id == "TRIS" then
local brush = cr:i32le()
if cr.err then
fail("truncated TRIS", "truncated")
return nil
end
if not attrs then
fail("TRIS before VRTS")
return nil
end
local nt = (cr.limit - cr.pos) // 12
local idx = buffer.create(nt * 12)
local readu32, writeu32 = buffer.readu32, buffer.writeu32
local p = cr.pos
for i = 0, nt - 1 do
local a, b, cc = readu32(buf, p), readu32(buf, p + 4), readu32(buf, p + 8)
if a >= count or b >= count or cc >= count then
fail(string.format("triangle %d: vertex index out of range", i))
return nil
end
-- mirrored z: reverse the winding to keep the faces front-facing
writeu32(idx, i * 12, a)
writeu32(idx, i * 12 + 4, cc)
writeu32(idx, i * 12 + 8, b)
p += 12
end
local prim: Types.Primitive = { attributes = attrs, indices = Types.Scene.accessor(idx, "u32", 1, nt * 3), mode = "triangles" }
prim.material = material(if brush == -1 then master else brush)
table.insert(mesh.primitives, prim)
end
end
if not attrs then
return nil -- a mesh without vertices: the node stays a pivot
end
if #mesh.primitives == 0 then
table.insert(mesh.primitives, { attributes = attrs, mode = "points" :: "points" })
end
table.insert(scene.meshes, mesh)
rec.mesh, rec.count = #scene.meshes, count
table.insert(meshes, rec)
lastMesh = rec
return #scene.meshes
end
local function readBone(r: Bytes.Reader, nodeIndex: number)
local b: Bone = { node = nodeIndex, target = lastMesh, list = {} }
table.insert(bones, b)
local list = b.list
while r.pos + 8 <= r.limit do
local v, w = r:i32le(), r:f32le()
table.insert(list, v)
table.insert(list, w)
end
end
local function readKeys(r: Bytes.Reader, nodeIndex: number)
local flags = r:i32le()
local per = 4 + (if bit32.band(flags, 1) ~= 0 then 12 else 0) + (if bit32.band(flags, 2) ~= 0 then 12 else 0) + (if bit32.band(flags, 4) ~= 0 then 16 else 0)
local k = nodeKeys[nodeIndex]
if not k then
k = { t = {}, s = {}, r = {} }
nodeKeys[nodeIndex] = k
end
while not r.err and r.pos + per <= r.limit do
local frame = r:i32le()
if bit32.band(flags, 1) ~= 0 then
k.t[frame] = vec(r)
end
if bit32.band(flags, 2) ~= 0 then
local x, y, z = r:f32le(), r:f32le(), r:f32le()
k.s[frame] = { x, y, z }
end
if bit32.band(flags, 4) ~= 0 then
k.r[frame] = quat(r)
end
end
end
local function readNode(c: Chunks.Chunk, depth: number): number?
if depth > maxDepth then
fail("limit: nodes nested deeper than " .. maxDepth, "limit")
return nil
end
local r = body(c)
local name = r:cstring()
local t = vec(r)
local sx, sy, sz = r:f32le(), r:f32le(), r:f32le()
local q = quat(r)
if r.err then
fail("truncated NODE", "truncated")
return nil
end
local node: Types.Node = { name = name, children = {} }
if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then
node.translation = t
end
if q[1] ~= 0 or q[2] ~= 0 or q[3] ~= 0 then
node.rotation = q
end
if sx ~= 1 or sy ~= 1 or sz ~= 1 then
node.scale = { sx, sy, sz }
end
table.insert(scene.nodes, node)
local index = #scene.nodes
for _, sub in Chunks.walk(buf, r.pos, r.limit, LAYOUT) do
if failure then
break
end
local id = sub.id
if id == "NODE" then
local child = readNode(sub, depth + 1)
if child then
table.insert(node.children, child)
end
elseif id == "MESH" and not node.mesh then
node.mesh = readMesh(body(sub), index)
elseif id == "BONE" then
readBone(body(sub), index)
elseif id == "KEYS" then
readKeys(body(sub), index)
elseif id == "ANIM" then
local ar = body(sub)
local flags, frames, fps = ar:i32le(), ar:i32le(), ar:f32le()
if not ar.err and not anim then
anim = { flags = flags, frames = frames, fps = if fps > 0 and fps < 1e6 then fps else 60 }
end
end
end
return index
end
for _, c in Chunks.walk(buf, hr.pos, head.offset + head.size, LAYOUT) do
if failure then
break
end
if c.id == "TEXS" then
readTexs(body(c))
elseif c.id == "BRUS" then
readBrus(body(c))
elseif c.id == "NODE" then
local n = readNode(c, 1)
if n then
table.insert(scene.roots, n)
end
end
end
if failure then
return nil, failure, failKind
end
if #scene.nodes == 0 then
return nil, "no NODE chunk", nil
end
-- ------------------------------------------------------------------------------------------ skins
local parent: { [number]: number } = {}
for i, n in scene.nodes do
for _, ch in n.children do
parent[ch] = i
end
end
local worldCache: { [number]: { number } } = {}
local function world(i: number): { number }
local w = worldCache[i]
if not w then
local n = scene.nodes[i]
local l = Mat4.compose(n.translation, n.rotation, n.scale)
w = if parent[i] then Mat4.mul(world(parent[i]), l) else l
worldCache[i] = w
end
return w
end
local bonesOf: { [MeshRec]: { Bone } } = {}
for _, b in bones do
local m = b.target
if m then
local l = bonesOf[m] or {}
bonesOf[m] = l
table.insert(l, b)
end
end
for _, rec in meshes do
local list = bonesOf[rec]
if list then
local nv = rec.count
local inf: { { number } } = {}
local joints: { number } = {}
for j, b in list do
joints[j] = b.node
local l = b.list
for k = 1, #l, 2 do
local v, w = l[k], l[k + 1]
if v >= 0 and v < nv and w > 0 and w == w then
local e = inf[v + 1]
if not e then
e = {}
inf[v + 1] = e
end
table.insert(e, j - 1)
table.insert(e, w)
end
end
end
local self: number? = nil -- the mesh node as a joint, for vertices no bone moves
local jb, wb = buffer.create(nv * 8), buffer.create(nv * 16)
for v = 0, nv - 1 do
local e = inf[v + 1]
if not e then
if not self then
table.insert(joints, rec.node)
self = #joints - 1
end
buffer.writeu16(jb, v * 8, self :: number)
buffer.writef32(wb, v * 16, 1)
else
-- the 4 strongest, normalised
local order = {}
for k = 1, #e, 2 do
table.insert(order, k)
end
table.sort(order, function(a: number, b: number): boolean
return e[a + 1] > e[b + 1]
end)
local sum = 0
for k = 1, math.min(4, #order) do
sum += e[order[k] + 1]
end
for k = 1, math.min(4, #order) do
buffer.writeu16(jb, v * 8 + (k - 1) * 2, e[order[k]])
buffer.writef32(wb, v * 16 + (k - 1) * 4, e[order[k] + 1] / sum)
end
end
end
local meshWorld = world(rec.node)
local ibm = buffer.create(#joints * 64)
for j, ni in joints do
local inv = Mat4.inverse(world(ni)) or Mat4.identity()
local m = Mat4.mul(inv, meshWorld)
for k = 1, 16 do
buffer.writef32(ibm, (j - 1) * 64 + (k - 1) * 4, m[k])
end
end
local ia = Types.Scene.accessor(ibm, "f32", 16, #joints)
ia.matrix = true
table.insert(scene.skins, { joints = joints, inverseBindMatrices = ia })
scene.nodes[rec.node].skin = #scene.skins
local J, W = Types.Scene.accessor(jb, "u16", 4, nv), Types.Scene.accessor(wb, "f32", 4, nv)
for _, prim in scene.meshes[rec.mesh].primitives do
prim.attributes.JOINTS_0 = J
prim.attributes.WEIGHTS_0 = W
end
end
end
-- ------------------------------------------------------------------------------------------ animation
local fps = if anim then anim.fps else 60
local channels: { Types.Channel } = {}
for ni = 1, #scene.nodes do
local k = nodeKeys[ni]
if k then
for _, path in { "translation", "rotation", "scale" } do
local map = if path == "translation" then k.t elseif path == "rotation" then k.r else k.s
local frames = {}
for f in map do
table.insert(frames, f)
end
if #frames > 0 then
table.sort(frames)
local nc = if path == "rotation" then 4 else 3
local input, output = buffer.create(#frames * 4), buffer.create(#frames * nc * 4)
for i, f in frames do
buffer.writef32(input, (i - 1) * 4, f / fps)
local v = map[f]
for c = 1, nc do
buffer.writef32(output, ((i - 1) * nc + c - 1) * 4, v[c])
end
end
table.insert(channels, {
node = ni,
path = path :: any,
input = Types.Scene.accessor(input, "f32", 1, #frames),
output = Types.Scene.accessor(output, "f32", nc, #frames),
interpolation = "LINEAR" :: "LINEAR",
})
end
end
end
end
if #channels > 0 then
table.insert(scene.animations, { name = "b3d", channels = channels })
end
scene.meta.up = "y"
scene.meta.source = {
format = "b3d",
version = version,
brushes = #brushes,
frames = if anim then anim.frames else nil,
fps = if anim then anim.fps else nil,
handedness = "left", -- converted: z mirrored, winding reversed
}
return scene, nil, nil
end
return Read
+68
View File
@@ -0,0 +1,68 @@
--!strict
-- model/b3d: Blitz3D .b3d (BB3D chunk format, version 1), read. Written from the Blitz3D file format description
-- (blitzbasic.com "b3dfile_specs.txt") and checked against assimp's B3D importer.
-- Reads: TEXS (texture files -> scene.textures, data through opts.files / opts.resolve, clamp flags -> sampler,
-- position / scale / rotation -> the first texture's KHR_texture_transform, flag 65536 = second UV set), BRUS (brushes ->
-- materials: colour + alpha, shininess -> roughness, FX 1 = unlit, 16 = double sided, 32 = blend; the first texture is
-- baseColorTexture, the others are listed in extras.b3d.textures; texture flags 2 / 4 -> blend / mask), the NODE tree
-- (name, position, scale, rotation; MESH -> one Mesh per node: VRTS -> POSITION / NORMAL / COLOR_0 (f32 RGBA) /
-- TEXCOORD_0..7 shared by the mesh's primitives, one "triangles" primitive per TRIS chunk with its brush, else the
-- mesh's master brush), BONE vertex weights -> a skin on the mesh read last before the bone (the 4 strongest weights
-- per vertex, normalised, JOINTS_0 / WEIGHTS_0; vertices no bone moves follow the mesh node, which then joins the
-- joints; inverse bind matrices from the bind pose), KEYS (position / scale / rotation keys) + ANIM (frames, fps,
-- default 60) -> one animation of LINEAR channels at frame / fps seconds.
-- Blitz3D is left-handed and Y up: z is mirrored (positions, normals, translations, keys), the triangle winding
-- reversed and the rotations mirrored, so the scene is glTF's right-handed Y up (meta.up = "y"). UVs keep their
-- top-left origin (= glTF). meta.source = { format, version, brushes, frames?, fps?, handedness = "left" }.
-- Not supported: writing; multiple VRTS chunks in one MESH (the first is used); per-brush blend modes beyond the
-- extras; texture coordinate sets of 3 / 4 components keep their first two.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Read = require("@formats/model/b3d/Read")
-- ------------------------------------------------------------------------------------------------ contract
local B3d = {
name = "b3d",
category = "model",
extensions = { "b3d" },
mime = { "model/x-b3d" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks", "codecs/model/Mat4" },
caps = { decode = true, encode = false, materials = true, textures = true, skins = true, animation = true, colors = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
resolve: ((uri: string) -> any)?, -- texture files (the api sets it for paths)
files: { [string]: any }?, -- or: the files by name
maxVertices: number?, -- default 2^24
maxDepth: number?, -- node nesting (default 256)
}
-- ------------------------------------------------------------------------------------------------ sniff
function B3d.sniff(r: Bytes.Reader): number
if r:peek(4) == "BB3D" then
return if r:peek(4, 8) ~= "" then 1 else 0.8
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function B3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
if r:peek(4) ~= "BB3D" then
return nil, Err.new(Err.CORRUPT, "no BB3D chunk")
end
-- the scene builder is plain (not native) code: a bug there must not escape as an error
local ok, scene, msg, kind = pcall(Read.scene, r, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "bad chunk tree: " .. tostring(scene))
end
if not scene then
return nil, Err.from(msg, nil, kind)
end
return scene, nil
end
return B3d
+90 -4
View File
@@ -9,6 +9,7 @@ local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Base64 = require("@formats/core/Base64")
local Pack = require("@formats/model/gltf/Pack")
local Draco = require("@formats/codecs/model/Draco")
local Read = {}
@@ -50,6 +51,7 @@ local KNOWN = {
EXT_texture_avif = true,
KHR_node_visibility = true,
KHR_xmp_json_ld = true,
KHR_draco_mesh_compression = true,
}
Read.KNOWN = KNOWN
@@ -100,6 +102,57 @@ local function keep(obj: any, handled: { [string]: boolean }?): { [string]: any
return { gltf = { extras = extras, extensions = ext } }
end
-- a Draco attribute as the type its glTF accessor declares (the bytes as they are when the layouts agree, else value
-- by value: normalized integers <-> floats, ints widened or narrowed)
local DRACO_HANDLED = { KHR_draco_mesh_compression = true }
local DRACO_SIZE = { i8 = 1, u8 = 1, i16 = 2, u16 = 2, i32 = 4, u32 = 4, f32 = 4 }
local DRACO_SAME: { [string]: string } = { i8 = "i8", u8 = "u8", i16 = "i16", u16 = "u16", u32 = "u32", f32 = "f32", snorm8 = "i8", unorm8 = "u8", snorm16 = "i16", unorm16 = "u16", i32 = "i32" }
local DRACO_WRITE: { [string]: (buffer, number, number) -> () } = { i8 = buffer.writei8, u8 = buffer.writeu8, i16 = buffer.writei16, u16 = buffer.writeu16, i32 = buffer.writei32, u32 = buffer.writeu32, f32 = buffer.writef32 }
local NORM_MAX: { [string]: number } = { u8 = 255, i8 = 127, u16 = 65535, i16 = 32767, u32 = 4294967295, i32 = 2147483647 }
local function dracoAccessor(da: Draco.Attribute, acc: Types.Accessor, n: number): Types.Accessor?
if da.components ~= acc.components or not DRACO_SIZE[da.type] then
return nil
end
local out = Types.Scene.accessor(nil, acc.type, acc.components, n)
out.name = acc.name
if DRACO_SAME[acc.type] == da.type then
out.data = da.data
return out
end
local reader = Types.Scene.reader({ data = da.data, type = da.type :: any, components = da.components, count = n })
local size = Types.COMPONENT_SIZE[acc.type]
local norm = string.match(acc.type, "^[us]norm") ~= nil
local base: string = DRACO_SAME[acc.type] or acc.type
local wr = DRACO_WRITE[base]
local dmax = NORM_MAX[base] or 1
if not reader or not wr or not size then
return nil
end
local get = reader :: (number, number) -> number
local w = wr :: (buffer, number, number) -> ()
local stride = size * acc.components
local function put(v: number, c: number, x: number)
if base ~= "f32" then
if norm then
x = math.clamp(x, if base == "u8" or base == "u16" then 0 else -1, 1) * dmax
end
x = math.floor(x + 0.5)
end
w(out.data, v * stride + c * size, x)
end
local srcMax = if da.normalized then NORM_MAX[da.type] else nil
for v = 0, n - 1 do
for c = 0, da.components - 1 do
local x = get(v, c)
if srcMax then
x = math.max(x / srcMax, -1)
end
put(v, c, x)
end
end
return out
end
function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Scene?, Err.Err?)
local maxBytes = opts and opts.maxBytes or 2 ^ 30
if type(doc) ~= "table" then
@@ -422,13 +475,39 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc
if type(p) ~= "table" or type(p.attributes) ~= "table" then
return nil, Err.new(Err.CORRUPT, string.format("mesh %d primitive %d: no attributes", i - 1, k - 1))
end
if type(p.extensions) == "table" and (p.extensions.KHR_draco_mesh_compression or p.extensions.EXT_meshopt_compression) then
return nil, Err.new(Err.UNSUPPORTED, "compressed primitives (Draco / meshopt)")
local pext = if type(p.extensions) == "table" then p.extensions else nil
if pext and pext.EXT_meshopt_compression then
return nil, Err.new(Err.UNSUPPORTED, "meshopt compressed primitives (EXT_meshopt_compression)")
end
-- KHR_draco_mesh_compression: the attributes it lists and the indices come from the Draco data
local dext = pext and pext.KHR_draco_mesh_compression
local draco: Draco.Geometry? = nil
local dmap: { [string]: number } = {}
if dext ~= nil then
local view = type(dext) == "table" and int(dext.bufferView) and views[dext.bufferView + 1]
if not view then
return nil, Err.new(Err.CORRUPT, string.format("mesh %d primitive %d: draco: bad bufferView", i - 1, k - 1))
end
local g, derr = Draco.decode(view.buf, view.offset, view.length, { maxPoints = maxBytes // 4, maxFaces = maxBytes // 12 })
if not g then
local e = derr :: Err.Err
return nil, Err.new(e.code, string.format("mesh %d primitive %d: %s", i - 1, k - 1, e.message))
end
draco = g
for name, id in (if type(dext.attributes) == "table" then dext.attributes else {}) do
if type(name) == "string" and int(id) then
dmap[name] = id
end
end
end
local attrs: { [string]: Types.Accessor } = {}
local count = -1
for name, ai in p.attributes do
local a = accessor(ai)
if a and draco and dmap[name] then
local da = Draco.attribute(draco, dmap[name])
a = if da then dracoAccessor(da, a, draco.numPoints) else nil
end
if not a then
return nil, Err.new(Err.CORRUPT, string.format("mesh %d: attribute %s: bad accessor", i - 1, tostring(name)))
end
@@ -443,7 +522,14 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc
return nil, Err.new(Err.CORRUPT, "bad primitive mode")
end
local prim: Types.Primitive = { attributes = attrs, mode = mode :: any, material = if int(p.material) and p.material < #scene.materials then p.material + 1 else nil }
if p.indices ~= nil then
if draco then
if draco.kind == "mesh" then
prim.indices = Types.Scene.accessor(draco.indices, "u32", 1, draco.numFaces * 3)
prim.mode = "triangles"
else
prim.mode = "points"
end
elseif p.indices ~= nil then
local ind = accessor(p.indices)
if not ind or ind.components ~= 1 or (ind.type ~= "u8" and ind.type ~= "u16" and ind.type ~= "u32") then
return nil, Err.new(Err.CORRUPT, "bad indices accessor")
@@ -472,7 +558,7 @@ function Read.scene(doc: any, bin: buffer?, fetch: Fetch, opts: any?): (Types.Sc
end
prim.targets = targets
end
prim.extras = keep(p, nil)
prim.extras = keep(p, DRACO_HANDLED)
table.insert(mesh.primitives, prim)
end
table.insert(scene.meshes, mesh)
+7 -4
View File
@@ -12,8 +12,11 @@
-- External .bin / image files come from opts.resolve(uri) or opts.files[uri] (the api sets resolve for paths).
-- Writes .gltf (buffers and images embedded as data: URIs by default; opts.external = true writes <name>.bin and the
-- images into opts.files) or .glb (opts.binary, or opts.format == "glb": the api passes the destination's extension).
-- Not supported: Draco (KHR_draco_mesh_compression) and meshopt (EXT_meshopt_compression) compressed primitives
-- (UNSUPPORTED), KHR_animation_pointer channels (skipped and counted in the animation's extras).
-- Draco compressed primitives (KHR_draco_mesh_compression) decode through codecs/model/Draco: the attributes the
-- extension lists and the indices come from the Draco data, as the types their accessors declare. Written back
-- uncompressed (the extension is dropped).
-- Not supported: meshopt (EXT_meshopt_compression) compressed primitives (UNSUPPORTED), KHR_animation_pointer channels
-- (skipped and counted in the animation's extras).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
@@ -31,8 +34,8 @@ local Gltf = {
category = "model",
extensions = { "gltf", "glb" },
mime = { "model/gltf+json", "model/gltf-binary" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff" },
caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Json", "core/Base64", "core/Sniff", "codecs/model/Draco" },
caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, draco = true },
}
-- ------------------------------------------------------------------------------------------------ types
+359
View File
@@ -0,0 +1,359 @@
--!strict
-- model/iqm/Read: an Inter-Quake Model (version 2) -> Types.Scene. From the IQM format description (iqm.txt and
-- iqm.h of the IQM SDK by Lee Salzman, public domain), checked against assimp's IQM importer (no code taken).
-- Every header range is checked against the data before it is read. Plain code (the caller wraps it in pcall).
local Types = require("@formats/Types")
local Rig = require("@formats/codecs/model/Rig")
local Read = {}
local Scene = Types.Scene
local readu8, readi8, readu16, readi16, readu32, readi32, readf32, readf64 = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi16, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64
local writef32, writeu32, writeu8, writeu16 = buffer.writef32, buffer.writeu32, buffer.writeu8, buffer.writeu16
Read.HEADER = {
"version", "filesize", "flags", "num_text", "ofs_text", "num_meshes", "ofs_meshes", "num_vertexarrays", "num_vertexes",
"ofs_vertexarrays", "num_triangles", "ofs_triangles", "ofs_adjacency", "num_joints", "ofs_joints", "num_poses",
"ofs_poses", "num_anims", "ofs_anims", "num_frames", "num_framechannels", "ofs_frames", "ofs_bounds", "num_comment",
"ofs_comment", "num_extensions", "ofs_extensions",
}
Read.SIZES = { [0] = 1, 1, 2, 2, 4, 4, 2, 4, 8 } -- byte, ubyte, short, ushort, int, uint, half, float, double
Read.ARRAYS = { [0] = "position", "texcoord", "normal", "tangent", "blendindexes", "blendweights", "color" }
local function half(h: number): number
local s = if bit32.band(h, 0x8000) ~= 0 then -1 else 1
local e = bit32.band(bit32.rshift(h, 10), 0x1F)
local m = bit32.band(h, 0x3FF)
if e == 0 then
return s * m * 2 ^ -24
elseif e == 31 then
return if m == 0 then s * math.huge else 0
end
return s * (1 + m / 1024) * 2 ^ (e - 15)
end
-- the values of one vertex array element range as numbers (normalized = integer formats scaled to 0..1 / -1..1)
local function values(b: buffer, at: number, format: number, n: number, normalized: boolean): { number }
local out = table.create(n) :: { number }
local size = Read.SIZES[format]
for i = 0, n - 1 do
local p = at + i * size
local v: number
if format == 0 then
v = readi8(b, p)
v = if normalized then math.max(v / 127, -1) else v
elseif format == 1 then
v = readu8(b, p)
v = if normalized then v / 255 else v
elseif format == 2 then
v = readi16(b, p)
v = if normalized then math.max(v / 32767, -1) else v
elseif format == 3 then
v = readu16(b, p)
v = if normalized then v / 65535 else v
elseif format == 4 then
v = readi32(b, p)
elseif format == 5 then
v = readu32(b, p)
elseif format == 6 then
v = half(readu16(b, p))
elseif format == 7 then
v = readf32(b, p)
else
v = readf64(b, p)
end
out[i + 1] = v
end
return out
end
local function f32acc(vals: { number }, comps: number): Types.Accessor
local d = buffer.create(#vals * 4)
for i, v in vals do
writef32(d, (i - 1) * 4, v)
end
return Scene.accessor(d, "f32", comps, #vals // comps)
end
local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", tga = "image/x-tga", bmp = "image/bmp", dds = "image/vnd-ms.dds" }
-- scene(b, base, limit, opts) -> Scene | nil, message
function Read.scene(b: buffer, base: number, limit: number, opts: { maxVertices: number? }?): (Types.Scene?, string?)
local size = limit - base
local H: { [string]: number } = {}
for i, name in Read.HEADER do
H[name] = readu32(b, base + 12 + i * 4)
end
if H.version ~= 2 then
return nil, "unsupported: IQM version " .. H.version .. " (only 2)"
end
if H.filesize > size then
return nil, "truncated: the header says " .. H.filesize .. " bytes, " .. size .. " present"
end
local maxV = opts and opts.maxVertices or 2 ^ 25
if H.num_vertexes > maxV or H.num_triangles > maxV then
return nil, "limit: more than " .. maxV .. " vertices / triangles"
end
local function range(ofs: number, count: number, each: number, what: string): string?
if count > 0 and (ofs < 124 or count * each > H.filesize or ofs + count * each > H.filesize) then
return "the " .. what .. " lie outside the file"
end
return nil
end
local err = range(H.ofs_text, H.num_text, 1, "text")
or range(H.ofs_meshes, H.num_meshes, 24, "meshes")
or range(H.ofs_vertexarrays, H.num_vertexarrays, 20, "vertex arrays")
or range(H.ofs_triangles, H.num_triangles, 12, "triangles")
or range(H.ofs_joints, H.num_joints, 48, "joints")
or range(H.ofs_poses, H.num_poses, 88, "poses")
or range(H.ofs_anims, H.num_anims, 20, "anims")
or range(H.ofs_frames, H.num_frames * H.num_framechannels, 2, "frames")
or range(H.ofs_bounds, if H.ofs_bounds > 0 then H.num_frames else 0, 32, "bounds")
or range(H.ofs_comment, H.num_comment, 1, "comment")
if err then
return nil, err
end
local text = if H.num_text > 0 then buffer.readstring(b, base + H.ofs_text, H.num_text) else ""
local function str(ofs: number): string
if ofs >= #text then
return ""
end
local z = string.find(text, "\0", ofs + 1, true)
return string.sub(text, ofs + 1, (z or #text + 1) - 1)
end
local scene = Scene.new()
scene.meta.up = "z"
local source: { [string]: any } = { format = "iqm", version = 2, flags = H.flags }
scene.meta.source = source
if H.num_comment > 0 then
source.comment = string.match(buffer.readstring(b, base + H.ofs_comment, H.num_comment), "^[^%z]*")
end
-- vertex arrays (the whole model's vertices; meshes are ranges of them)
local nv = H.num_vertexes
type Array = { kind: string, name: string, format: number, comps: number, offset: number }
local arrays: { Array } = {}
for i = 0, H.num_vertexarrays - 1 do
local p = base + H.ofs_vertexarrays + i * 20
local typ, format, comps, offset = readu32(b, p), readu32(b, p + 8), readu32(b, p + 12), readu32(b, p + 16)
local esize = Read.SIZES[format]
if not esize or comps < 1 or comps > 16 then
return nil, "vertex array " .. i .. " has format " .. format .. " / " .. comps .. " components"
end
local e = range(offset, nv, comps * esize, "vertex array " .. i)
if e then
return nil, e
end
local kind = Read.ARRAYS[typ]
local name = if kind then kind else "_" .. (if typ >= 0x10 then str(typ - 0x10) else tostring(typ))
table.insert(arrays, { kind = kind or "custom", name = name, format = format, comps = comps, offset = base + offset })
end
-- joints -> nodes + a skin
local jointNodes: { number } = {}
local skin: number? = nil
if H.num_joints > 0 then
local joints: { Rig.Joint } = {}
for j = 0, H.num_joints - 1 do
local p = base + H.ofs_joints + j * 48
local parent = readi32(b, p + 4)
local f = table.create(10) :: { number }
for k = 0, 9 do
f[k + 1] = readf32(b, p + 8 + k * 4)
end
local q = { f[4], f[5], f[6], f[7] }
local ql = math.sqrt(q[1] ^ 2 + q[2] ^ 2 + q[3] ^ 2 + q[4] ^ 2)
q = if ql > 0 then { q[1] / ql, q[2] / ql, q[3] / ql, q[4] / ql } else { 0, 0, 0, 1 }
joints[j + 1] = { name = str(readu32(b, p)), parent = parent + 1, translation = { f[1], f[2], f[3] }, rotation = q, scale = { f[8], f[9], f[10] } }
end
jointNodes, skin = Rig.skeleton(scene, joints, "local")
end
-- materials: one per distinct material string (IQM names its texture there)
local matOf: { [string]: number } = {}
local function material(name: string): number?
if name == "" then
return nil
end
local hit = matOf[name]
if hit then
return hit
end
local mat = Scene.material(name)
mat.metallic = 0
local ext = string.lower(string.match(name, "%.(%w+)$") or "")
table.insert(scene.textures, { name = name, uri = name, mime = MIME[ext] })
mat.baseColorTexture = { texture = #scene.textures }
table.insert(scene.materials, mat)
matOf[name] = #scene.materials
return #scene.materials
end
-- meshes
for m = 0, H.num_meshes - 1 do
local p = base + H.ofs_meshes + m * 24
local name, mname = str(readu32(b, p)), str(readu32(b, p + 4))
local fv, cv, ft, ct = readu32(b, p + 8), readu32(b, p + 12), readu32(b, p + 16), readu32(b, p + 20)
if fv + cv > nv or ft + ct > H.num_triangles then
return nil, "mesh " .. m .. " points outside the vertex / triangle arrays"
end
local attributes: { [string]: Types.Accessor } = {}
for _, a in arrays do
local esize = Read.SIZES[a.format]
local at = a.offset + fv * a.comps * esize
if a.kind == "blendindexes" then
local vals = values(b, at, a.format, cv * a.comps, false)
local big = a.format ~= 1
local d = buffer.create(cv * 4 * (if big then 2 else 1))
for v = 0, cv - 1 do
for c = 0, 3 do
local x = if c < a.comps then vals[v * a.comps + c + 1] else 0
x = math.clamp(math.floor(x), 0, if big then 65535 else 255)
if big then
writeu16(d, (v * 4 + c) * 2, x)
else
writeu8(d, v * 4 + c, x)
end
end
end
attributes.JOINTS_0 = Scene.accessor(d, if big then "u16" else "u8", 4, cv)
elseif a.kind == "blendweights" or (a.kind == "color" and a.format == 1) then
local vals = values(b, at, a.format, cv * a.comps, true)
local d = buffer.create(cv * 4)
for v = 0, cv - 1 do
for c = 0, 3 do
local x = if c < a.comps then vals[v * a.comps + c + 1] elseif a.kind == "color" and c == 3 then 1 else 0
writeu8(d, v * 4 + c, math.clamp(math.floor(x * 255 + 0.5), 0, 255))
end
end
attributes[if a.kind == "color" then "COLOR_0" else "WEIGHTS_0"] = Scene.accessor(d, "unorm8", 4, cv)
else
local vals = values(b, at, a.format, cv * a.comps, true)
local name0 = if a.kind == "position" then "POSITION" elseif a.kind == "texcoord" then "TEXCOORD_0" elseif a.kind == "normal" then "NORMAL" elseif a.kind == "tangent" then "TANGENT" elseif a.kind == "color" then "COLOR_0" else a.name
local want = if a.kind == "position" or a.kind == "normal" then 3 elseif a.kind == "texcoord" then 2 elseif a.kind == "tangent" or a.kind == "color" then 4 else a.comps
if want ~= a.comps then
local fixed = table.create(cv * want, 0) :: { number }
for v = 0, cv - 1 do
for c = 0, want - 1 do
fixed[v * want + c + 1] = if c < a.comps then vals[v * a.comps + c + 1] elseif c == 3 then 1 else 0
end
end
vals = fixed
end
attributes[name0] = f32acc(vals, want)
end
end
if not attributes.POSITION then
return nil, "no position array"
end
-- triangles: IQM's front faces are clockwise; corners 2 and 3 swap for glTF's counter-clockwise
local ib = buffer.create(ct * 12)
for k = 0, ct - 1 do
local q = base + H.ofs_triangles + (ft + k) * 12
local a, c2, c3 = readu32(b, q), readu32(b, q + 4), readu32(b, q + 8)
if a < fv or c2 < fv or c3 < fv or a >= fv + cv or c2 >= fv + cv or c3 >= fv + cv then
return nil, "triangle " .. (ft + k) .. " uses a vertex outside mesh " .. m
end
writeu32(ib, k * 12, a - fv)
writeu32(ib, k * 12 + 4, c3 - fv)
writeu32(ib, k * 12 + 8, c2 - fv)
end
local prim: Types.Primitive = { attributes = attributes, indices = Scene.accessor(ib, "u32", 1, ct * 3), mode = "triangles", material = material(mname) }
table.insert(scene.meshes, { name = name, primitives = { prim } })
local node: Types.Node = { name = name, children = {}, mesh = #scene.meshes }
if skin and attributes.JOINTS_0 then
node.skin = skin
end
table.insert(scene.nodes, node)
table.insert(scene.roots, #scene.nodes)
end
-- animations: frames hold the masked pose channels (offset + value * scale), in pose order
if H.num_anims > 0 and H.num_frames > 0 and H.num_poses > 0 then
local np = H.num_poses
local poses: { { mask: number, offset: { number }, scale: { number } } } = {}
local channels = 0
for i = 0, np - 1 do
local p = base + H.ofs_poses + i * 88
local mask = readu32(b, p + 4)
local off, sc = table.create(10) :: { number }, table.create(10) :: { number }
for c = 0, 9 do
off[c + 1] = readf32(b, p + 8 + c * 4)
sc[c + 1] = readf32(b, p + 48 + c * 4)
if bit32.band(mask, bit32.lshift(1, c)) ~= 0 then
channels += 1
end
end
poses[i + 1] = { mask = mask, offset = off, scale = sc }
end
if channels ~= H.num_framechannels then
return nil, "the poses use " .. channels .. " frame channels, the header says " .. H.num_framechannels
end
-- frame f, pose i -> 10 values
local frameBytes: number = H.num_framechannels * 2
local framesAt: number = base + H.ofs_frames
local function frame(f: number): { { number } }
local out = table.create(np) :: { { number } }
local q = framesAt + f * frameBytes
for i = 1, np do
local ps = poses[i]
local v = table.create(10) :: { number }
for c = 0, 9 do
local x = ps.offset[c + 1]
if bit32.band(ps.mask, bit32.lshift(1, c)) ~= 0 then
local k: number = ps.scale[c + 1]
x += readu16(b, q) * k
q += 2
end
v[c + 1] = x
end
out[i] = v
end
return out
end
local anims: { any } = {}
for a = 0, H.num_anims - 1 do
local p = base + H.ofs_anims + a * 20
local name, first, count, rate, flags = str(readu32(b, p)), readu32(b, p + 4), readu32(b, p + 8), readf32(b, p + 12), readu32(b, p + 16)
if first + count > H.num_frames then
return nil, "animation " .. a .. " uses frames past the end"
end
local fps = if rate > 0 and rate == rate then rate else 30
local times = table.create(count) :: { number }
local tracks: { [number]: Rig.Track } = {}
for j = 1, math.min(np, #jointNodes) do
tracks[j] = { translation = {}, rotation = {}, scale = {} }
end
for k = 0, count - 1 do
times[k + 1] = k / fps
local fr = frame(first + k)
for j, tr in tracks do
local v = fr[j]
local t, r, s = tr.translation :: { number }, tr.rotation :: { number }, tr.scale :: { number }
table.move(v, 1, 3, #t + 1, t)
local ql = math.sqrt(v[4] ^ 2 + v[5] ^ 2 + v[6] ^ 2 + v[7] ^ 2)
ql = if ql > 0 then ql else 1
table.move({ v[4] / ql, v[5] / ql, v[6] / ql, v[7] / ql }, 1, 4, #r + 1, r)
table.move(v, 8, 10, #s + 1, s)
end
end
if count > 0 then
Rig.animation(scene, name, jointNodes, times, tracks)
end
table.insert(anims, { name = name, first = first, frames = count, framerate = rate, loop = bit32.band(flags, 1) ~= 0 })
end
source.animations = anims
end
-- bounds: one box per frame
if H.ofs_bounds > 0 and H.num_frames > 0 then
local boxes = {}
for f = 0, H.num_frames - 1 do
local p = base + H.ofs_bounds + f * 32
boxes[f + 1] = {
min = { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) },
max = { readf32(b, p + 12), readf32(b, p + 16), readf32(b, p + 20) },
xyradius = readf32(b, p + 24),
radius = readf32(b, p + 28),
}
end
source.bounds = boxes
end
return scene, nil
end
return Read
+706
View File
@@ -0,0 +1,706 @@
--!strict
-- model/iqm/Write: Types.Scene -> an Inter-Quake Model (version 2). One IQM mesh per triangle-able primitive (lines
-- and points are skipped), vertex arrays position / texcoord / normal / tangent (f32), blend indexes / weights
-- (u8, the four strongest weights, summing to 255) and colour (u8). The skeleton is the union of the scene's skins
-- (parents before children; a joint's parent is its nearest ancestor that is a joint): bind poses from the inverse
-- bind matrices, so IQM's implied inverse bind matrices are the scene's. Unskinned primitives are baked into world
-- space and, in a skinned model, bound to their nearest joint ancestor (else the first joint). Animations are
-- sampled (codecs/model/Sampler) at their own key spacing when it is uniform, else at opts.framerate (default 30),
-- quantized per pose channel to 16 bits, with per-frame bounds from the skinned vertices.
-- Coordinates are written as they are (IQM is z-up: a y-up scene can be turned with F.ops.mesh.setUp first).
-- Plain code (the caller wraps it in pcall).
local Types = require("@formats/Types")
local Bytes = require("@formats/core/Bytes")
local Mat4 = require("@formats/codecs/model/Mat4")
local Sampler = require("@formats/codecs/model/Sampler")
local Read = require("@formats/model/iqm/Read")
local Write = {}
local Scene = Types.Scene
type M4 = { number }
-- ------------------------------------------------------------------------------------------------ scene walk
-- world matrices (rest pose, or with a pose's overrides) and the parent of every node
local function parents(scene: Types.Scene): { [number]: number }
local parent: { [number]: number } = {}
for i, n in scene.nodes do
for _, c in n.children or {} do
if parent[c] == nil and c ~= i then
parent[c] = i
end
end
end
return parent
end
local function localMatrix(node: Types.Node, over: { [string]: { number } }?): M4
if not over then
return Scene.nodeMatrix(node)
end
if node.matrix and #node.matrix == 16 and not (over.translation or over.rotation or over.scale) then
return node.matrix
end
local t, r, s = node.translation, node.rotation, node.scale
if node.matrix and #node.matrix == 16 then
t, r, s = Mat4.decompose(node.matrix)
end
return Mat4.compose(over.translation or t, over.rotation or r, over.scale or s)
end
local function worlds(scene: Types.Scene, parent: { [number]: number }, pose: Sampler.Pose?): { [number]: M4 }
local world: { [number]: M4 } = {}
local function get(i: number, depth: number): M4
local w = world[i]
if w then
return w
end
local m = localMatrix(scene.nodes[i], pose and pose[i])
local p = parent[i]
if p and depth < #scene.nodes then
m = Mat4.mul(get(p, depth + 1), m)
end
world[i] = m
return m
end
for i in scene.nodes do
get(i, 0)
end
return world
end
-- ------------------------------------------------------------------------------------------------ geometry
-- the triangle corners of a primitive (0-based vertex numbers), or nil for lines / points
local function triangles(prim: Types.Primitive): { number }?
local mode = prim.mode or "triangles"
local nv = prim.attributes.POSITION.count
local idx: { number } = {}
if prim.indices then
local get = Scene.reader(prim.indices)
if not get then
return nil
end
for k = 0, prim.indices.count - 1 do
idx[k + 1] = get(k, 0)
end
else
for k = 0, nv - 1 do
idx[k + 1] = k
end
end
local out: { number } = {}
if mode == "triangles" then
for k = 1, #idx - 2, 3 do
table.move(idx, k, k + 2, #out + 1, out)
end
elseif mode == "triangle_strip" then
for k = 1, #idx - 2 do
if k % 2 == 1 then
table.move({ idx[k], idx[k + 1], idx[k + 2] }, 1, 3, #out + 1, out)
else
table.move({ idx[k + 1], idx[k], idx[k + 2] }, 1, 3, #out + 1, out)
end
end
elseif mode == "triangle_fan" then
for k = 2, #idx - 1 do
table.move({ idx[1], idx[k], idx[k + 1] }, 1, 3, #out + 1, out)
end
elseif mode == "polygons" and prim.faces then
local fget = Scene.reader(prim.faces)
local at = 1
for f = 0, prim.faces.count - 1 do
local n = if fget then fget(f, 0) else 0
for k = 1, n - 2 do
table.move({ idx[at], idx[at + k], idx[at + k + 1] }, 1, 3, #out + 1, out)
end
at += n
end
else
return nil
end
for _, v in out do
if v >= nv or v < 0 then
error("index " .. v .. " out of range", 0)
end
end
return out
end
local function readAll(acc: Types.Accessor?, comps: number, nv: number, default: { number }): { number }?
if not acc then
return nil
end
local get = Scene.reader(acc)
if not get or acc.count < nv then
return nil
end
local out = table.create(nv * comps) :: { number }
for v = 0, nv - 1 do
for c = 0, comps - 1 do
out[v * comps + c + 1] = if c < acc.components then get(v, c) else default[c + 1]
end
end
return out
end
-- the influences of vertex v: global joint numbers, the 4 strongest, u8 weights summing to 255, as a flat list
local function influences(skin: Types.Skin, jointIndex: { [number]: number }, joints: { number }, weights: { number }, v: number): { number }
local pairs_: { { number } } = {}
for c = 1, 4 do
local w = weights[v * 4 + c]
local node = skin.joints[math.floor(joints[v * 4 + c]) + 1]
if w > 0 and node and jointIndex[node] then
table.insert(pairs_, { jointIndex[node], w })
end
end
table.sort(pairs_, function(a: { number }, b: { number }): boolean
return a[2] > b[2]
end)
local sum = 0
for _, pr in pairs_ do
sum += pr[2]
end
local q: { number } = {}
local left = 255
for k, pr in pairs_ do
q[k] = if sum > 0 then math.floor(pr[2] / sum * 255 + 0.5) else 0
left -= q[k]
end
if #pairs_ > 0 then
q[1] += left
end
local list: { number } = {}
for k, pr in pairs_ do
if q[k] > 0 then
table.insert(list, pr[1])
table.insert(list, q[k])
end
end
return list
end
-- appends a flat influence list to the blend index / weight arrays (4 slots)
local function push4(bi: { number }, bw: { number }, list: { number })
local n = #bi
for c = 1, 4 do
bi[n + c] = list[c * 2 - 1] or 0
bw[n + c] = list[c * 2] or 0
end
end
-- ------------------------------------------------------------------------------------------------ writer
type MeshOut = { name: string, material: string, first: number, count: number, tfirst: number, tcount: number }
function Write.iqm(scene: Types.Scene, opts: { framerate: number?, comment: string? }?): (buffer?, string?)
local parent = parents(scene)
local rest = worlds(scene, parent, nil)
-- the skeleton: every skin joint, parents first
local isJoint: { [number]: boolean } = {}
local ibmOf: { [number]: M4 } = {}
for _, skin in scene.skins do
local get = skin.inverseBindMatrices and Scene.reader(skin.inverseBindMatrices)
for j, node in skin.joints do
if scene.nodes[node] then
isJoint[node] = true
if get and ibmOf[node] == nil and skin.inverseBindMatrices and skin.inverseBindMatrices.count >= j then
local m = table.create(16) :: M4
for k = 1, 16 do
m[k] = get(j - 1, k - 1)
end
ibmOf[node] = m
end
end
end
end
-- the skins' joints in order, each after its joint ancestors (IQM wants parents first)
local jointList: { number } = {}
local jointIndex: { [number]: number } = {} -- node -> 0-based joint
local function add(n: number, depth: number)
if jointIndex[n] or depth > #scene.nodes then
return
end
local p = parent[n]
local guard = 0
while p and not isJoint[p] and guard <= #scene.nodes do
p = parent[p]
guard += 1
end
if p and isJoint[p] then
add(p, depth + 1)
end
if not jointIndex[n] then
table.insert(jointList, n)
jointIndex[n] = #jointList - 1
end
end
for _, skin in scene.skins do
for _, n in skin.joints do
if isJoint[n] then
add(n, 0)
end
end
end
if #jointList > 65535 then
return nil, "limit: more than 65535 joints"
end
local function jointParent(n: number): number
local p = parent[n]
local guard = 0
while p and guard <= #scene.nodes do
if jointIndex[p] then
return jointIndex[p]
end
p = parent[p]
guard += 1
end
return -1
end
local bindWorld: { [number]: M4 } = {}
for _, n in jointList do
local ibm = ibmOf[n]
bindWorld[n] = (ibm and Mat4.inverseFull(ibm)) or rest[n]
end
local function poseLocal(n: number, world: { [number]: M4 }): ({ number }, { number }, { number })
local p = jointParent(n)
local m = world[n]
if p >= 0 then
local inv = Mat4.inverseFull(world[jointList[p + 1]])
if inv then
m = Mat4.mul(inv, m)
end
end
return Mat4.decompose(m)
end
-- the meshes
local nodeOfMesh: { [number]: number } = {}
local placed: { { node: number, mesh: number } } = {}
local seen: { [number]: boolean } = {}
local function visit(i: number, depth: number)
if seen[i] or depth > #scene.nodes then
return
end
seen[i] = true
local node = scene.nodes[i]
if node.mesh and scene.meshes[node.mesh] then
table.insert(placed, { node = i, mesh = node.mesh })
nodeOfMesh[node.mesh] = nodeOfMesh[node.mesh] or i
end
for _, c in node.children or {} do
visit(c, depth + 1)
end
end
local roots = scene.roots
if not roots or #roots == 0 then
roots = {}
for i in scene.nodes do
if parent[i] == nil then
table.insert(roots, i)
end
end
end
for _, r in roots do
visit(r, 0)
end
if #placed == 0 and #scene.nodes == 0 then
for mi in scene.meshes do
table.insert(placed, { node = 0, mesh = mi })
end
end
local hasJoints = #jointList > 0
local P, TC, N, TG, BI, BW, C = {}, {}, {}, {}, {}, {}, {}
local hasTC, hasN, hasTG, hasC = false, false, false, false
local tris: { number } = {}
local meshes: { MeshOut } = {}
-- every primitive's per-vertex skinning as lists (joint, weight), for the bounds
local skinOf: { { number } } = {}
local nvTotal = 0
for _, pl in placed do
local node = scene.nodes[pl.node]
local mesh = scene.meshes[pl.mesh]
local skinned = node and node.skin and scene.skins[node.skin]
local world = if pl.node > 0 then rest[pl.node] else Scene.IDENTITY
local nrmM = Mat4.normalMatrix(world)
for pi, prim in mesh.primitives do
local pos = prim.attributes.POSITION
local tri = pos and triangles(prim)
if tri and #tri > 0 then
local nv = pos.count
local first = nvTotal
local positions = readAll(pos, 3, nv, { 0, 0, 0 }) :: { number }
local normals = readAll(prim.attributes.NORMAL, 3, nv, { 0, 0, 1 })
local tangents = readAll(prim.attributes.TANGENT, 4, nv, { 1, 0, 0, 1 })
local uvs = readAll(prim.attributes.TEXCOORD_0, 2, nv, { 0, 0 })
local cols = readAll(prim.attributes.COLOR_0, 4, nv, { 1, 1, 1, 1 })
local joints = skinned and readAll(prim.attributes.JOINTS_0, 4, nv, { 0, 0, 0, 0 })
local weights = skinned and readAll(prim.attributes.WEIGHTS_0, 4, nv, { 0, 0, 0, 0 })
local rigid = -1
if hasJoints and not (joints and weights) then
local p = if pl.node > 0 then pl.node else nil
local guard = 0
while p and guard <= #scene.nodes do
if jointIndex[p] then
rigid = jointIndex[p]
break
end
p = parent[p]
guard += 1
end
rigid = math.max(rigid, 0)
end
local bake = not (joints and weights)
for v = 0, nv - 1 do
local x, y, z = positions[v * 3 + 1], positions[v * 3 + 2], positions[v * 3 + 3]
if bake then
x, y, z = Mat4.point(world, x, y, z)
end
table.move({ x, y, z }, 1, 3, #P + 1, P)
if normals then
local nx, ny, nz = normals[v * 3 + 1], normals[v * 3 + 2], normals[v * 3 + 3]
if bake then
nx, ny, nz = Mat4.point(nrmM, nx, ny, nz)
nx, ny, nz = nx - nrmM[13], ny - nrmM[14], nz - nrmM[15]
local l = math.sqrt(nx * nx + ny * ny + nz * nz)
if l > 0 then
nx, ny, nz = nx / l, ny / l, nz / l
end
end
hasN = true
table.move({ nx, ny, nz }, 1, 3, #N + 1, N)
else
table.move({ 0, 0, 1 }, 1, 3, #N + 1, N)
end
if tangents then
local tx, ty, tz = tangents[v * 4 + 1], tangents[v * 4 + 2], tangents[v * 4 + 3]
if bake then
tx, ty, tz = Mat4.point(world, tx, ty, tz)
tx, ty, tz = tx - world[13], ty - world[14], tz - world[15]
end
hasTG = true
table.move({ tx, ty, tz, tangents[v * 4 + 4] }, 1, 4, #TG + 1, TG)
else
table.move({ 1, 0, 0, 1 }, 1, 4, #TG + 1, TG)
end
if uvs then
hasTC = true
table.move(uvs, v * 2 + 1, v * 2 + 2, #TC + 1, TC)
else
table.move({ 0, 0 }, 1, 2, #TC + 1, TC)
end
if cols then
hasC = true
table.move(cols, v * 4 + 1, v * 4 + 4, #C + 1, C)
else
table.move({ 1, 1, 1, 1 }, 1, 4, #C + 1, C)
end
-- influences: global joint numbers, the 4 strongest, u8 weights summing to 255
local list: { number }
if joints and weights and skinned then
list = influences(skinned, jointIndex, joints, weights, v)
elseif rigid >= 0 then
list = { rigid, 255 }
else
list = {}
end
push4(BI, BW, list)
skinOf[#skinOf + 1] = list
end
-- triangles back to IQM's clockwise order
local tfirst = #tris // 3
for k = 1, #tri, 3 do
table.move({ first + tri[k], first + tri[k + 2], first + tri[k + 1] }, 1, 3, #tris + 1, tris)
end
local mat = prim.material and scene.materials[prim.material]
local mname = ""
if mat then
local ref = mat.baseColorTexture
local tex = ref and scene.textures[ref.texture]
mname = if tex and tex.uri then tex.uri elseif mat.name then mat.name else ""
end
local name = mesh.name or ("mesh" .. pl.mesh)
if #mesh.primitives > 1 then
name ..= "_" .. pi
end
table.insert(meshes, { name = name, material = mname, first = first, count = nv, tfirst = tfirst, tcount = #tri // 3 })
nvTotal += nv
end
end
end
if #meshes == 0 then
return nil, "nothing to write: no triangle primitives"
end
-- animation frames
local frames: { { { number } } } = {} -- frames[f][joint] = 10 values
local anims: { { name: string, first: number, count: number, rate: number } } = {}
local frameWorld: { { [number]: M4 } } = {}
if hasJoints then
for ai, anim in scene.animations do
local keys = Sampler.times(anim)
if #keys > 0 then
local rate = opts and opts.framerate
if not rate then
-- the key spacing when uniform (decoded IQM / MD5 animations), else 30 per second
local dt = if #keys > 1 then keys[2] - keys[1] else 0
local uniform = dt > 0 and math.abs(keys[1] - math.floor(keys[1] / dt + 0.5) * dt) < 1e-4
for k = 2, #keys do
uniform = uniform and math.abs(keys[k] - keys[k - 1] - dt) < 1e-4
end
rate = if uniform then 1 / dt else 30
end
local fps: number = math.clamp(rate :: number, 1e-3, 1e4)
local last = keys[#keys]
local count = math.max(1, math.floor(last * fps + 0.5) + 1)
if count > 100000 then
return nil, "limit: animation " .. ai .. " has more than 100000 frames"
end
local cache = {}
local first = #frames
local prevQ: { [number]: { number } } = {}
for k = 0, count - 1 do
local pose = Sampler.pose(scene, anim, k / fps, cache)
local world = worlds(scene, parent, pose)
local fr = table.create(#jointList) :: { { number } }
for j, n in jointList do
local t, r, s = poseLocal(n, world)
local pq = prevQ[j]
if pq and pq[1] * r[1] + pq[2] * r[2] + pq[3] * r[3] + pq[4] * r[4] < 0 then
r = { -r[1], -r[2], -r[3], -r[4] }
end
prevQ[j] = r
fr[j] = { t[1], t[2], t[3], r[1], r[2], r[3], r[4], s[1], s[2], s[3] }
end
table.insert(frames, fr)
table.insert(frameWorld, world)
end
table.insert(anims, { name = anim.name or ("anim" .. ai), first = first, count = count, rate = fps })
end
end
end
-- quantization per pose channel
local masks, offsets, scales = {}, {}, {}
local numChannels = 0
for j = 1, #jointList do
local lo, hi = table.create(10, math.huge), table.create(10, -math.huge)
for _, fr in frames do
for c = 1, 10 do
lo[c] = math.min(lo[c], fr[j][c])
hi[c] = math.max(hi[c], fr[j][c])
end
end
local mask = 0
local off, sc = table.create(10, 0), table.create(10, 0)
for c = 1, 10 do
if lo[c] <= hi[c] then
off[c] = lo[c]
if hi[c] - lo[c] > 1e-6 then
mask = bit32.bor(mask, bit32.lshift(1, c - 1))
sc[c] = (hi[c] - lo[c]) / 65535
numChannels += 1
end
end
end
masks[j], offsets[j], scales[j] = mask, off, sc
end
-- text
local text = { "\0" }
local textLen = 1
local textAt: { [string]: number } = { [""] = 0 }
local function str(s: string): number
local hit = textAt[s]
if hit then
return hit
end
s = string.gsub(s, "%z", "")
local at = textLen
table.insert(text, s .. "\0")
textLen += #s + 1
textAt[s] = at
return at
end
for _, m in meshes do
str(m.name)
str(m.material)
end
for _, n in jointList do
str(scene.nodes[n].name or "")
end
for _, a in anims do
str(a.name)
end
local comment = opts and opts.comment
-- layout
local w = Bytes.writer(124 + nvTotal * 64 + #tris * 4)
local H: { [string]: number } = {}
local function at(): number
return w:tell()
end
w:string("INTERQUAKEMODEL\0")
for _ = 1, 27 do
w:u32le(0)
end
H.ofs_text, H.num_text = at(), textLen
w:string(table.concat(text))
while at() % 4 ~= 0 do
w:u8(0)
H.num_text += 1
end
H.ofs_meshes, H.num_meshes = at(), #meshes
for _, m in meshes do
for _, v in { str(m.name), str(m.material), m.first, m.count, m.tfirst, m.tcount } do
w:u32le(v)
end
end
-- vertex arrays: headers, then data
type Arr = { typ: number, format: number, comps: number, data: { number } }
local arrs: { Arr } = { { typ = 0, format = 7, comps = 3, data = P } }
if hasTC then
table.insert(arrs, { typ = 1, format = 7, comps = 2, data = TC })
end
if hasN then
table.insert(arrs, { typ = 2, format = 7, comps = 3, data = N })
end
if hasTG then
table.insert(arrs, { typ = 3, format = 7, comps = 4, data = TG })
end
if hasJoints then
table.insert(arrs, { typ = 4, format = if #jointList > 256 then 3 else 1, comps = 4, data = BI })
table.insert(arrs, { typ = 5, format = 1, comps = 4, data = BW })
end
if hasC then
table.insert(arrs, { typ = 6, format = 1, comps = 4, data = C })
end
H.ofs_vertexarrays, H.num_vertexarrays, H.num_vertexes = at(), #arrs, nvTotal
w:fill(0, #arrs * 20)
local dataAt: { number } = {}
for i, a in arrs do
while at() % 4 ~= 0 do
w:u8(0)
end
dataAt[i] = at()
if a.format == 7 then
for _, v in a.data do
w:f32le(v)
end
elseif a.format == 3 then
for _, v in a.data do
w:u16le(math.clamp(math.floor(v), 0, 65535))
end
elseif a.typ == 6 then
for _, v in a.data do
w:u8(math.clamp(math.floor(v * 255 + 0.5), 0, 255))
end
else
for _, v in a.data do
w:u8(math.clamp(math.floor(v), 0, 255))
end
end
end
while at() % 4 ~= 0 do
w:u8(0)
end
H.ofs_triangles, H.num_triangles = at(), #tris // 3
for _, v in tris do
w:u32le(v)
end
if hasJoints then
H.ofs_joints, H.num_joints = at(), #jointList
for _, n in jointList do
local p = jointParent(n)
local t, r, s = poseLocal(n, bindWorld)
w:u32le(str(scene.nodes[n].name or ""))
w:u32le(if p < 0 then p + 2 ^ 32 else p)
for _, v in { t[1], t[2], t[3], r[1], r[2], r[3], r[4], s[1], s[2], s[3] } do
w:f32le(v)
end
end
if #frames > 0 then
H.ofs_poses, H.num_poses = at(), #jointList
for j, n in jointList do
local jp = jointParent(n)
w:u32le(if jp < 0 then jp + 2 ^ 32 else jp)
w:u32le(masks[j])
for c = 1, 10 do
w:f32le(offsets[j][c])
end
for c = 1, 10 do
w:f32le(scales[j][c])
end
end
H.ofs_anims, H.num_anims = at(), #anims
for _, a in anims do
w:u32le(str(a.name))
w:u32le(a.first)
w:u32le(a.count)
w:f32le(a.rate)
w:u32le(0)
end
H.ofs_frames, H.num_frames, H.num_framechannels = at(), #frames, numChannels
for _, fr in frames do
for j = 1, #jointList do
local mask = masks[j]
for c = 1, 10 do
if bit32.band(mask, bit32.lshift(1, c - 1)) ~= 0 then
local q = (fr[j][c] - offsets[j][c]) / scales[j][c]
w:u16le(math.clamp(math.floor(q + 0.5), 0, 65535))
end
end
end
end
while at() % 4 ~= 0 do
w:u8(0)
end
-- bounds of the skinned vertices per frame
H.ofs_bounds = at()
local skinM = table.create(#jointList) :: { M4 }
for f, world in frameWorld do
for j, n in jointList do
local invBind = Mat4.inverseFull(bindWorld[n]) or Mat4.identity()
skinM[j] = Mat4.mul(world[n], invBind)
end
local lo, hi = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
local xy, rad = 0, 0
for v = 0, nvTotal - 1 do
local x, y, z = P[v * 3 + 1], P[v * 3 + 2], P[v * 3 + 3]
local list = skinOf[v + 1]
if #list > 0 then
local sx, sy, sz = 0, 0, 0
for k = 1, #list - 1, 2 do
local m = skinM[list[k] + 1]
local wt = list[k + 1] / 255
local px, py, pz = Mat4.point(m, x, y, z)
sx, sy, sz = sx + px * wt, sy + py * wt, sz + pz * wt
end
x, y, z = sx, sy, sz
end
lo = { math.min(lo[1], x), math.min(lo[2], y), math.min(lo[3], z) }
hi = { math.max(hi[1], x), math.max(hi[2], y), math.max(hi[3], z) }
xy = math.max(xy, x * x + y * y)
rad = math.max(rad, x * x + y * y + z * z)
end
for _, v in { lo[1], lo[2], lo[3], hi[1], hi[2], hi[3], math.sqrt(xy), math.sqrt(rad) } do
w:f32le(v)
end
local _ = f
end
end
end
if comment and comment ~= "" then
H.ofs_comment, H.num_comment = at(), #comment + 1
w:string(comment .. "\0")
end
local out = w:finish()
H.version, H.filesize = 2, buffer.len(out)
for i, name in Read.HEADER do
buffer.writeu32(out, 12 + i * 4, H[name] or 0)
end
for i, a in arrs do
local p = H.ofs_vertexarrays + (i - 1) * 20
buffer.writeu32(out, p, a.typ)
buffer.writeu32(out, p + 4, 0)
buffer.writeu32(out, p + 8, a.format)
buffer.writeu32(out, p + 12, a.comps)
buffer.writeu32(out, p + 16, dataAt[i])
end
return out, nil
end
return Write
+82
View File
@@ -0,0 +1,82 @@
--!strict
-- model/iqm: Inter-Quake Model (IQM version 2), read and write. New code from the IQM format description (iqm.txt /
-- iqm.h of Lee Salzman's IQM SDK, public domain); checked against assimp (which reads IQM geometry).
-- Reads meshes (one node + mesh each; material strings -> materials whose baseColorTexture uri is that string, as
-- IQM tools name the texture there), vertex arrays in every IQM format (position, texcoord (top-left origin, as
-- glTF), normal, tangent, blend indexes / weights -> JOINTS_0 / WEIGHTS_0, colour, custom arrays as _<name>), joints
-- (a node each, bind pose TRS, one skin with the inverse bind matrices), poses + frames + anims (16-bit channels
-- dequantized into translation / rotation / scale channels at the anim's frame rate; loop flags and frame ranges in
-- meta.source.animations) and per-frame bounds (meta.source.bounds). IQM's clockwise triangles become glTF's
-- counter-clockwise ones; IQM is z-up (meta.up = "z", nothing is rotated).
-- Writes the same (see model/iqm/Write): any Scene's triangle primitives, skins merged into one skeleton, sampled and
-- quantized animations, bounds. Not supported: IQM version 1, adjacency and extensions (skipped on read, not written).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Read = require("@formats/model/iqm/Read")
local Write = require("@formats/model/iqm/Write")
-- ------------------------------------------------------------------------------------------------ contract
local Iqm = {
name = "iqm",
category = "model",
extensions = { "iqm" },
mime = { "model/x-iqm" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/Rig", "codecs/model/Sampler" },
caps = { decode = true, encode = true, materials = true, skins = true, animation = true, vertexColors = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxVertices: number?, -- refuse more vertices or triangles (default 2^25)
}
export type EncodeOptions = {
framerate: number?, -- animation sampling rate (default: the key spacing when uniform, else 30 per second)
comment: string?, -- stored in the comment block
}
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = "INTERQUAKEMODEL\0"
-- ------------------------------------------------------------------------------------------------ sniff
function Iqm.sniff(r: Bytes.Reader): number
return if r:peek(16) == MAGIC then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Iqm.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
if r.limit - r.base < 124 then
return nil, Err.new(Err.TRUNCATED, "shorter than the header", r.base)
end
if r:peek(16) ~= MAGIC then
return nil, Err.new(Err.CORRUPT, "no INTERQUAKEMODEL magic", r.base)
end
local ok, scene, msg = pcall(Read.scene, r.buf, r.base, r.limit, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "bad model data: " .. tostring(scene))
end
if not scene then
return nil, Err.from(msg)
end
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Iqm.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(scene) ~= "table" or scene.kind ~= "scene" then
return nil, Err.new(Err.ARG, "needs a Scene")
end
local ok, out, msg = pcall(Write.iqm, scene, opts)
if not ok then
return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out))
end
if not out then
local e = Err.from(msg)
return nil, Err.new(if e.code == Err.CORRUPT then Err.ARG else e.code, e.message)
end
return out, nil
end
return Iqm
+319
View File
@@ -0,0 +1,319 @@
--!strict
-- model/ldraw/Colors: the LDraw colour table: code -> { name, rgb, edge, alpha, luminance, finish }, parsed from
-- !COLOUR lines. The built-in table is the colour list of LDraw.org's LDConfig.ldr (UPDATE 2025-05-20; CC BY 2.0, see
-- licenses/LDRAW_COLOURS.txt), one line per colour without the "0 !COLOUR " prefix and with the MATERIAL parameters cut
-- after the material's type. Colours are 0xRRGGBB (sRGB); an edge is a colour code or a direct colour 0x2RRGGBB.
local Colors = {}
export type Colour = { name: string, rgb: number, edge: number, alpha: number, luminance: number, finish: string? }
export type Table = { [number]: Colour }
local FINISHES = { CHROME = true, PEARLESCENT = true, RUBBER = true, MATTE_METALLIC = true, METAL = true }
-- entry(rest) -> code, Colour | nil: one "Name CODE n VALUE #RRGGBB EDGE #RRGGBB|code [ALPHA a] [LUMINANCE l] ..."
function Colors.entry(rest: string): (number?, Colour?)
local words: { string } = {}
for w in string.gmatch(rest, "%S+") do
table.insert(words, w)
end
local name = words[1]
local code, rgb, edge: number?, alpha, lum, finish = nil, nil, nil, 255, 0, nil
local i = 2
while i <= #words do
local k, v = words[i], words[i + 1]
if k == "CODE" and v then
code = tonumber(v)
i += 1
elseif k == "VALUE" and v and rgb == nil then
rgb = tonumber(string.match(v, "^#(%x%x%x%x%x%x)$") or "", 16)
i += 1
elseif k == "EDGE" and v then
local hex = string.match(v, "^#(%x%x%x%x%x%x)$")
edge = if hex then 0x2000000 + (tonumber(hex, 16) :: number) else tonumber(v)
i += 1
elseif k == "ALPHA" and v then
alpha = math.clamp(tonumber(v) or 255, 0, 255)
i += 1
elseif k == "LUMINANCE" and v then
lum = math.clamp(tonumber(v) or 0, 0, 255)
i += 1
elseif FINISHES[k] then
finish = k
elseif k == "MATERIAL" and v then
finish = v
break
end
i += 1
end
if not name or not code or not rgb or code % 1 ~= 0 then
return nil, nil
end
return code, { name = name, rgb = rgb :: number, edge = edge or 0x2333333, alpha = alpha, luminance = lum, finish = finish }
end
-- parse(text, into?) -> into (a new table by default) with every "0 !COLOUR" line of text added
function Colors.parse(text: string, into: Table?): Table
local t: Table = into or {}
for line in string.gmatch(text, "[^\n]+") do
local rest = string.match(line, "^%s*0%s+!COLOUR%s+(.-)%s*$")
if rest then
local code, c = Colors.entry(rest)
if code and c then
t[code] = c
end
end
end
return t
end
local BUILTIN = [[
Black CODE 0 VALUE #1B2A34 EDGE #808080
Blue CODE 1 VALUE #1E5AA8 EDGE #333333
Green CODE 2 VALUE #00852B EDGE #333333
Dark_Turquoise CODE 3 VALUE #069D9F EDGE #333333
Red CODE 4 VALUE #B40000 EDGE #333333
Dark_Pink CODE 5 VALUE #D3359D EDGE #333333
Brown CODE 6 VALUE #543324 EDGE #1E1E1E
Light_Grey CODE 7 VALUE #8A928D EDGE #333333
Dark_Grey CODE 8 VALUE #545955 EDGE #333333
Light_Blue CODE 9 VALUE #97CBD9 EDGE #333333
Bright_Green CODE 10 VALUE #58AB41 EDGE #333333
Light_Turquoise CODE 11 VALUE #00AAA4 EDGE #333333
Salmon CODE 12 VALUE #F06D61 EDGE #333333
Pink CODE 13 VALUE #F6A9BB EDGE #333333
Yellow CODE 14 VALUE #FAC80A EDGE #333333
White CODE 15 VALUE #F4F4F4 EDGE #333333
Light_Green CODE 17 VALUE #ADD9A8 EDGE #333333
Light_Yellow CODE 18 VALUE #FFD67F EDGE #333333
Tan CODE 19 VALUE #D7BA8C EDGE #333333
Light_Violet CODE 20 VALUE #AFBED6 EDGE #333333
Purple CODE 22 VALUE #671F81 EDGE #333333
Dark_Blue_Violet CODE 23 VALUE #0E3E9A EDGE #333333
Orange CODE 25 VALUE #D67923 EDGE #333333
Magenta CODE 26 VALUE #901F76 EDGE #333333
Lime CODE 27 VALUE #A5CA18 EDGE #333333
Dark_Tan CODE 28 VALUE #897D62 EDGE #333333
Bright_Pink CODE 29 VALUE #FF9ECD EDGE #333333
Medium_Lavender CODE 30 VALUE #A06EB9 EDGE #333333
Lavender CODE 31 VALUE #CDA4DE EDGE #333333
Very_Light_Orange CODE 68 VALUE #FDC383 EDGE #333333
Bright_Reddish_Lilac CODE 69 VALUE #8A12A8 EDGE #333333
Reddish_Brown CODE 70 VALUE #5F3109 EDGE #808080
Light_Bluish_Grey CODE 71 VALUE #969696 EDGE #333333
Dark_Bluish_Grey CODE 72 VALUE #646464 EDGE #333333
Medium_Blue CODE 73 VALUE #7396C8 EDGE #333333
Medium_Green CODE 74 VALUE #7FC475 EDGE #333333
Light_Pink CODE 77 VALUE #FECCCF EDGE #333333
Light_Nougat CODE 78 VALUE #FFC995 EDGE #333333
Medium_Nougat CODE 84 VALUE #AA7D55 EDGE #333333
Medium_Lilac CODE 85 VALUE #441A91 EDGE #333333
Light_Brown CODE 86 VALUE #7B5D41 EDGE #333333
Blue_Violet CODE 89 VALUE #1C58A7 EDGE #333333
Nougat CODE 92 VALUE #BB805A EDGE #333333
Light_Salmon CODE 100 VALUE #F9B7A5 EDGE #333333
Violet CODE 110 VALUE #26469A EDGE #333333
Medium_Violet CODE 112 VALUE #4861AC EDGE #333333
Medium_Lime CODE 115 VALUE #B7D425 EDGE #333333
Aqua CODE 118 VALUE #9CD6CC EDGE #333333
Light_Lime CODE 120 VALUE #DEEA92 EDGE #333333
Light_Orange CODE 125 VALUE #F9A777 EDGE #333333
Dark_Nougat CODE 128 VALUE #AD6140 EDGE #333333
Very_Light_Bluish_Grey CODE 151 VALUE #C8C8C8 EDGE #333333
Bright_Light_Orange CODE 191 VALUE #FCAC00 EDGE #333333
Bright_Light_Blue CODE 212 VALUE #9DC3F7 EDGE #333333
Rust CODE 216 VALUE #872B17 EDGE #333333
Reddish_Lilac CODE 218 VALUE #8E5597 EDGE #333333
Lilac CODE 219 VALUE #564E9D EDGE #333333
Bright_Light_Yellow CODE 226 VALUE #FFEC6C EDGE #333333
Sky_Blue CODE 232 VALUE #77C9D8 EDGE #333333
Dark_Blue CODE 272 VALUE #19325A EDGE #333333
Dark_Green CODE 288 VALUE #00451A EDGE #808080
Flamingo_Pink CODE 295 VALUE #FF94C2 EDGE #333333
Dark_Brown CODE 308 VALUE #352100 EDGE #808080
Maersk_Blue CODE 313 VALUE #ABD9FF EDGE #333333
Dark_Red CODE 320 VALUE #720012 EDGE #333333
Dark_Azure CODE 321 VALUE #469BC3 EDGE #333333
Medium_Azure CODE 322 VALUE #68C3E2 EDGE #333333
Light_Aqua CODE 323 VALUE #D3F2EA EDGE #333333
Yellowish_Green CODE 326 VALUE #E2F99A EDGE #333333
Olive_Green CODE 330 VALUE #77774E EDGE #333333
Sand_Red CODE 335 VALUE #88605E EDGE #333333
Medium_Dark_Pink CODE 351 VALUE #F785B1 EDGE #333333
Coral CODE 353 VALUE #FF6D77 EDGE #333333
Earth_Orange CODE 366 VALUE #D86D2C EDGE #333333
Neon_Yellow CODE 368 VALUE #EDFF21 EDGE #333333
Medium_Brown CODE 370 VALUE #755945 EDGE #333333
Medium_Tan CODE 371 VALUE #CCA373 EDGE #333333
Sand_Purple CODE 373 VALUE #75657D EDGE #333333
Sand_Green CODE 378 VALUE #708E7C EDGE #333333
Sand_Blue CODE 379 VALUE #70819A EDGE #333333
Reddish_Orange CODE 402 VALUE #CA4C0B EDGE #333333
Sienna_Brown CODE 422 VALUE #915C3C EDGE #333333
Umber_Brown CODE 423 VALUE #543F33 EDGE #333333
Fabuland_Brown CODE 450 VALUE #D27744 EDGE #333333
Medium_Orange CODE 462 VALUE #F58624 EDGE #333333
Dark_Orange CODE 484 VALUE #91501C EDGE #333333
Very_Light_Grey CODE 503 VALUE #BCB4A5 EDGE #333333
Light_Orange_Brown CODE 507 VALUE #FA9C1C EDGE #333333
Fabuland_Red CODE 508 VALUE #C65127 EDGE #333333
Fabuland_Orange CODE 509 VALUE #CF8A47 EDGE #333333
Fabuland_Lime CODE 510 VALUE #78FC78 EDGE #333333
Trans_Dark_Blue CODE 33 VALUE #0020A0 EDGE #000B38 ALPHA 128
Trans_Green CODE 34 VALUE #237841 EDGE #174F2B ALPHA 128
Trans_Bright_Green CODE 35 VALUE #56E646 EDGE #27AF18 ALPHA 128
Trans_Red CODE 36 VALUE #C91A09 EDGE #660D05 ALPHA 128
Trans_Dark_Pink CODE 37 VALUE #DF6695 EDGE #B9275F ALPHA 128
Trans_Neon_Orange CODE 38 VALUE #FF800D EDGE #A85100 ALPHA 128
Trans_Very_Light_Blue CODE 39 VALUE #C1DFF0 EDGE #6FB4DC ALPHA 128
Trans_Brown CODE 40 VALUE #635F52 EDGE #2A2823 ALPHA 128
Trans_Medium_Blue CODE 41 VALUE #559AB7 EDGE #326276 ALPHA 128
Trans_Neon_Green CODE 42 VALUE #C0FF00 EDGE #739900 ALPHA 128
Trans_Light_Blue CODE 43 VALUE #AEE9EF EDGE #59D1DE ALPHA 128
Trans_Bright_Reddish_Lilac CODE 44 VALUE #96709F EDGE #5F4365 ALPHA 128
Trans_Pink CODE 45 VALUE #FC97AC EDGE #F9345B ALPHA 128
Trans_Yellow CODE 46 VALUE #F5CD2F EDGE #B49208 ALPHA 128
Trans_Clear CODE 47 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 128
Trans_Purple CODE 52 VALUE #A5A5CB EDGE #6464A6 ALPHA 128
Trans_Neon_Yellow CODE 54 VALUE #DAB000 EDGE #755E00 ALPHA 128
Trans_Orange CODE 57 VALUE #F08F1C EDGE #9E5C0A ALPHA 128
Trans_Black_IR_Lens CODE 32 VALUE #000000 EDGE #333333 ALPHA 210
Trans_Neon_Red CODE 158 VALUE #F18EBB EDGE #E63384 ALPHA 128
Trans_Bright_Light_Green CODE 227 VALUE #B5D96C EDGE #86B22E ALPHA 128
Trans_Bright_Light_Orange CODE 231 VALUE #FCB76D EDGE #FA860A ALPHA 128
Trans_Fire_Yellow CODE 234 VALUE #FBE890 EDGE #F7D22B ALPHA 128
Trans_Reddish_Lilac CODE 284 VALUE #C281A5 EDGE #944771 ALPHA 128
Trans_Light_Green CODE 285 VALUE #7DC291 EDGE #46955D ALPHA 128
Trans_Light_Blue_Violet CODE 293 VALUE #6BABE4 EDGE #247BC6 ALPHA 128
Trans_Black CODE 10375 VALUE #212121 EDGE #545454 ALPHA 128
Chrome_Antique_Brass CODE 60 VALUE #645A4C EDGE #665B4D CHROME
Chrome_Blue CODE 61 VALUE #6C96BF EDGE #3D638A CHROME
Chrome_Green CODE 62 VALUE #3CB371 EDGE #226741 CHROME
Chrome_Pink CODE 63 VALUE #AA4D8E EDGE #632C52 CHROME
Chrome_Black CODE 64 VALUE #1B2A34 EDGE #3D5F76 CHROME
Chrome_Gold CODE 334 VALUE #DFC176 EDGE #C2982E CHROME
Chrome_Silver CODE 383 VALUE #CECECE EDGE #9C9C9C CHROME
Pearl_Black CODE 83 VALUE #0A1327 EDGE #333333 PEARLESCENT
Copper CODE 134 VALUE #764D3B EDGE #333333 PEARLESCENT
Pearl_Light_Grey CODE 135 VALUE #A0A0A0 EDGE #333333 PEARLESCENT
Metallic_Blue CODE 137 VALUE #5B7590 EDGE #333333 PEARLESCENT
Pearl_Light_Gold CODE 142 VALUE #DEAC66 EDGE #333333 PEARLESCENT
Pearl_Dark_Gold CODE 147 VALUE #83724F EDGE #333333 PEARLESCENT
Pearl_Dark_Grey CODE 148 VALUE #484D48 EDGE #333333 PEARLESCENT
Pearl_Very_Light_Grey CODE 150 VALUE #989B99 EDGE #333333 PEARLESCENT
Pearl_Red CODE 176 VALUE #945148 EDGE #333333 PEARLESCENT
Pearl_Yellow CODE 178 VALUE #AB673A EDGE #333333 PEARLESCENT
Pearl_Silver CODE 179 VALUE #898788 EDGE #333333 PEARLESCENT
Pearl_White CODE 183 VALUE #F6F2DF EDGE #333333 PEARLESCENT
Metallic_Bright_Red CODE 184 VALUE #D60026 EDGE #333333 PEARLESCENT
Metallic_Bright_Blue CODE 185 VALUE #0059A3 EDGE #333333 PEARLESCENT
Metallic_Dark_Green CODE 186 VALUE #008E3C EDGE #333333 PEARLESCENT
Pearl_Brown CODE 187 VALUE #57392C EDGE #333333 PEARLESCENT
Reddish_Gold CODE 189 VALUE #AC8247 EDGE #333333 PEARLESCENT
Lemon_Metallic CODE 200 VALUE #708224 EDGE #333333 PEARLESCENT
Pearl_Gold CODE 297 VALUE #AA7F2E EDGE #333333 PEARLESCENT
Metallic_Silver CODE 80 VALUE #767676 EDGE #333333 METAL
Metallic_Green CODE 81 VALUE #C2C06F EDGE #333333 METAL
Metallic_Gold CODE 82 VALUE #DBAC34 EDGE #333333 METAL
Metallic_Dark_Grey CODE 87 VALUE #3E3C39 EDGE #333333 METAL
Metallic_Copper CODE 300 VALUE #C27F53 EDGE #333333 METAL
Metallic_Light_Blue CODE 10045 VALUE #97CBD9 EDGE #333333 METAL
Metallic_Pink CODE 10046 VALUE #AD659A EDGE #333333 METAL
Metallic_Light_Pink CODE 10049 VALUE #FECCCF EDGE #333333 METAL
Milky_White CODE 79 VALUE #EEEEEE EDGE #BABABA ALPHA 240
Glow_In_Dark_Opaque CODE 21 VALUE #E0FFB0 EDGE #B8FF4D ALPHA 240 LUMINANCE 15
Glow_In_Dark_Trans CODE 294 VALUE #BDC6AD EDGE #8D9D72 ALPHA 240 LUMINANCE 15
Glow_In_Dark_White CODE 329 VALUE #F5F3D7 EDGE #E0DA85 ALPHA 240 LUMINANCE 15
Glitter_Trans_Dark_Pink CODE 114 VALUE #DF6695 EDGE #B9275F ALPHA 128 MATERIAL GLITTER
Glitter_Trans_Clear CODE 117 VALUE #EEEEEE EDGE #BABABA ALPHA 128 MATERIAL GLITTER
Glitter_Trans_Purple CODE 129 VALUE #640061 EDGE #000000 ALPHA 128 MATERIAL GLITTER
Glitter_Trans_Light_Blue CODE 302 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 MATERIAL GLITTER
Glitter_Trans_Neon_Green CODE 339 VALUE #C0FF00 EDGE #739900 ALPHA 128 MATERIAL GLITTER
Glitter_Trans_Orange CODE 341 VALUE #F08F1C EDGE #9E5C0A ALPHA 128 MATERIAL GLITTER
Opal_Trans_Clear CODE 360 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 240 LUMINANCE 5 MATERIAL GLITTER
Opal_Trans_Light_Blue CODE 362 VALUE #AEE9EF EDGE #59D1DE ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
Opal_Trans_Black CODE 363 VALUE #635F52 EDGE #2A2823 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
Opal_Trans_Dark_Pink CODE 364 VALUE #DF6695 EDGE #B9275F ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
Opal_Trans_Purple CODE 365 VALUE #671F81 EDGE #441456 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
Opal_Trans_Green CODE 367 VALUE #237841 EDGE #174F2B ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
Glitter_Trans_Bright_Green CODE 10351 VALUE #56E646 EDGE #27AF18 ALPHA 128 MATERIAL GLITTER
Opal_Trans_Dark_Blue CODE 10366 VALUE #0020A0 EDGE #000B38 ALPHA 200 LUMINANCE 5 MATERIAL GLITTER
Speckle_Black_Copper CODE 75 VALUE #000000 EDGE #AB6038 MATERIAL SPECKLE
Speckle_Dark_Bluish_Grey_Silver CODE 76 VALUE #635F61 EDGE #898788 MATERIAL SPECKLE
Speckle_Black_Silver CODE 132 VALUE #000000 EDGE #898788 MATERIAL SPECKLE
Speckle_Black_Gold CODE 133 VALUE #000000 EDGE #DBAC34 MATERIAL SPECKLE
Rubber_Yellow CODE 65 VALUE #FAC80A EDGE #333333 RUBBER
Rubber_Black CODE 256 VALUE #1B2A34 EDGE #808080 RUBBER
Rubber_Blue CODE 273 VALUE #1E5AA8 EDGE #333333 RUBBER
Rubber_Red CODE 324 VALUE #B40000 EDGE #333333 RUBBER
Rubber_Orange CODE 350 VALUE #D67923 EDGE #333333 RUBBER
Rubber_Light_Grey CODE 375 VALUE #8A928D EDGE #333333 RUBBER
Rubber_Dark_Blue CODE 406 VALUE #19325A EDGE #333333 RUBBER
Rubber_Purple CODE 449 VALUE #671F81 EDGE #333333 RUBBER
Rubber_Lime CODE 490 VALUE #A5CA18 EDGE #333333 RUBBER
Rubber_Light_Bluish_Grey CODE 496 VALUE #969696 EDGE #333333 RUBBER
Rubber_Flat_Silver CODE 504 VALUE #898788 EDGE #333333 RUBBER
Rubber_White CODE 511 VALUE #F4F4F4 EDGE #333333 RUBBER
Rubber_Green CODE 10002 VALUE #00852B EDGE #333333 RUBBER
Rubber_Bright_Green CODE 10010 VALUE #58AB41 EDGE #333333 RUBBER
Rubber_Tan CODE 10019 VALUE #D7BA8C EDGE #333333 RUBBER
Rubber_Magenta CODE 10026 VALUE #901F76 EDGE #333333 RUBBER
Rubber_Bright_Pink CODE 10029 VALUE #FF9ECD EDGE #333333 RUBBER
Rubber_Medium_Lavender CODE 10030 VALUE #A06EB9 EDGE #333333 RUBBER
Rubber_Lavender CODE 10031 VALUE #CDA4DE EDGE #333333 RUBBER
Rubber_Reddish_Brown CODE 10070 VALUE #5F3109 EDGE #808080 RUBBER
Rubber_Dark_Bluish_Grey CODE 10072 VALUE #646464 EDGE #333333 RUBBER
Rubber_Medium_Blue CODE 10073 VALUE #7396C8 EDGE #333333 RUBBER
Rubber_Light_Nougat CODE 10078 VALUE #FFC995 EDGE #333333 RUBBER
Rubber_Bright_Light_Yellow CODE 10226 VALUE #FFEC6C EDGE #333333 RUBBER
Rubber_Dark_Brown CODE 10308 VALUE #352100 EDGE #808080 RUBBER
Rubber_Dark_Red CODE 10320 VALUE #720012 EDGE #333333 RUBBER
Rubber_Dark_Azure CODE 10321 VALUE #469BC3 EDGE #333333 RUBBER
Rubber_Medium_Azure CODE 10322 VALUE #68C3E2 EDGE #333333 RUBBER
Rubber_Light_Aqua CODE 10323 VALUE #D3F2EA EDGE #333333 RUBBER
Rubber_Sand_Green CODE 10378 VALUE #708E7C EDGE #333333 RUBBER
Rubber_Dark_Orange CODE 10484 VALUE #91501C EDGE #333333 RUBBER
Rubber_Trans_Yellow CODE 66 VALUE #F5CD2F EDGE #B49208 ALPHA 128 RUBBER
Rubber_Trans_Clear CODE 67 VALUE #FCFCFC EDGE #C9C9C9 ALPHA 128 RUBBER
Rubber_Trans_Bright_Green CODE 10035 VALUE #56E646 EDGE #27AF18 ALPHA 128 RUBBER
Rubber_Trans_Red CODE 10036 VALUE #C91A09 EDGE #660D05 ALPHA 128 RUBBER
Rubber_Trans_Light_Blue CODE 10043 VALUE #AEE9EF EDGE #59D1DE ALPHA 128 RUBBER
Canvas_Black CODE 20000 VALUE #1B2A34 EDGE #808080 MATERIAL FABRIC
Canvas_Blue CODE 20001 VALUE #1E5AA8 EDGE #333333 MATERIAL FABRIC
Canvas_Green CODE 20002 VALUE #00852B EDGE #333333 MATERIAL FABRIC
Canvas_Red CODE 20004 VALUE #B40000 EDGE #333333 MATERIAL FABRIC
Canvas_Bright_Green CODE 20010 VALUE #58AB41 EDGE #333333 MATERIAL FABRIC
Canvas_Yellow CODE 20014 VALUE #FAC80A EDGE #333333 MATERIAL FABRIC
Canvas_White CODE 20015 VALUE #F4F4F4 EDGE #333333 MATERIAL FABRIC
Canvas_Reddish_Brown CODE 20070 VALUE #5F3109 EDGE #808080 MATERIAL FABRIC
Canvas_Light_Brown CODE 20086 VALUE #7B5D41 EDGE #333333 MATERIAL FABRIC
Canvas_Dark_Green CODE 20288 VALUE #00451A EDGE #808080 MATERIAL FABRIC
Canvas_Cream CODE 20500 VALUE #F8F3E4 EDGE #333333 MATERIAL FABRIC
Main_Colour CODE 16 VALUE #FFFF80 EDGE #333333
Edge_Colour CODE 24 VALUE #7F7F7F EDGE #333333
Magnet CODE 493 VALUE #656761 EDGE #333333 METAL
Electric_Contact_Alloy CODE 494 VALUE #D0D0D0 EDGE #333333 METAL
Electric_Contact_Copper CODE 495 VALUE #AE7A59 EDGE #333333 METAL
Trans_Sticker CODE 10047 VALUE #FFFFFF EDGE #FFFFFF ALPHA 16
]]
local cache: Table? = nil
-- builtin() -> a fresh copy of the LDConfig.ldr table (callers may add to it)
function Colors.builtin(): Table
if not cache then
local t: Table = {}
for line in string.gmatch(BUILTIN, "[^\n]+") do
local code, c = Colors.entry(line)
if code and c then
t[code] = c
end
end
cache = t
end
local copy: Table = {}
for k, v in cache :: Table do
copy[k] = v
end
return copy
end
return Colors
+580
View File
@@ -0,0 +1,580 @@
--!strict
-- model/ldraw/Read: LDraw text -> Types.Scene (see model/ldraw for the mapping). Files are parsed once into command
-- lists (MPD sections, then sub-files through opts.files / opts.resolve with the library paths); parts are baked into
-- one mesh per (part, colour, inversion), with the BFC rules applied inside the part; model files become nodes.
-- Returns nil, message[, kind] on failure (the contract turns it into an Err with Err.from).
local Types = require("@formats/Types")
local Colors = require("@formats/model/ldraw/Colors")
local Read = {}
export type Options = {
resolve: ((uri: string) -> any)?,
files: { [string]: any }?,
ldconfig: string?,
color: number?,
upright: boolean?,
flatten: boolean?,
lines: boolean?,
optionalLines: boolean?,
maxDepth: number?,
maxTriangles: number?,
maxNodes: number?,
}
-- a parsed line: k = 0 (a BFC state change: cw / clip), 1 (a reference: v = x y z a b c d e f g h i), 2..5
type Cmd = { k: number, c: number, v: { number }, name: string?, inv: boolean?, step: number?, cw: boolean?, clip: boolean? }
type File = {
name: string,
key: string,
cmds: { Cmd },
certified: boolean,
org: string?,
refs: number,
library: boolean,
main: boolean,
title: string?,
author: string?,
model: boolean?,
}
type Group = { mode: string, colour: number, ds: boolean, pos: { number }, ctrl: { number }? }
local PREFIXES = { "", "parts/", "p/", "parts/s/", "models/" }
local LIBRARY = { ["parts/"] = true, ["p/"] = true, ["parts/s/"] = true }
local FLIP = { 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1 }
local IDENTITY12 = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0 }
local function norm(name: string): string
return string.lower((string.gsub(string.match(name, "^%s*(.-)%s*$") or name, "\\", "/")))
end
local function srgbToLinear(v: number): number
return if v <= 0.04045 then v / 12.92 else ((v + 0.055) / 1.055) ^ 2.4
end
-- parse(text, name) -> File (colour definitions go into colours as they are met)
local function parse(text: string, name: string, colours: Colors.Table, stats: { bad: number, lines: number }): File
local f: File = { name = name, key = norm(name), cmds = {}, certified = false, refs = 0, library = false, main = false }
local cmds = f.cmds
local invert, step, first = false, 1, true
for line in string.gmatch(text, "[^\n]+") do
local t = string.match(line, "^%s*(%d)%s")
if t then
stats.lines += 1
end
if t == "0" then
local w1, rest = string.match(line, "^%s*0%s+(%S+)%s*(.-)%s*$")
if w1 == "BFC" and rest then
local u = string.upper(rest)
local cmd: Cmd? = nil
for word in string.gmatch(u, "%S+") do
if word == "CERTIFY" then
f.certified = true
elseif word == "NOCERTIFY" then
f.certified = false
elseif word == "INVERTNEXT" then
invert = true
elseif word == "CW" or word == "CCW" or word == "CLIP" or word == "NOCLIP" then
local c: Cmd = cmd or { k = 0, c = 0, v = IDENTITY12 }
cmd = c
if word == "CW" or word == "CCW" then
c.cw = word == "CW"
else
c.clip = word == "CLIP"
end
end
end
if cmd then
table.insert(cmds, cmd)
end
elseif w1 == "!COLOUR" then
Colors.parse(line, colours)
elseif w1 == "!LDRAW_ORG" and rest then
f.org = string.match(rest, "^(%S+)")
elseif w1 == "STEP" then
step += 1
elseif w1 == "Author:" then
f.author = rest
elseif w1 == "Name:" or w1 == "FILE" or w1 == "NOFILE" or w1 == "!HISTORY" or w1 == "!LICENSE" then
-- (headers)
elseif first and w1 and string.sub(w1, 1, 1) ~= "!" and w1 ~= "//" then
f.title = (string.match(line, "^%s*0%s+(.-)%s*$"))
end
first = false
elseif t then
first = false
local k = tonumber(t) :: number
local inv = invert
invert = false
if k == 1 then
local c, x, y, z, a, b, cc, d, e, ff, g, h, i, file = string.match(line, "^%s*1%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(%S+)%s+(.-)%s*$")
local v = { tonumber(a), tonumber(b), tonumber(cc), tonumber(x), tonumber(d), tonumber(e), tonumber(ff), tonumber(y), tonumber(g), tonumber(h), tonumber(i), tonumber(z) }
local code = tonumber(c)
local complete = true
for j = 1, 12 do
if v[j] == nil then
complete = false
end
end
if file and file ~= "" and complete and code and code >= 0 and code % 1 == 0 then
table.insert(cmds, { k = 1, c = code, v = v :: { number }, name = file, inv = inv, step = step })
f.refs += 1
else
stats.bad += 1
end
elseif k >= 2 and k <= 5 then
local need = if k == 2 then 6 elseif k == 3 then 9 else 12
local v: { number } = {}
local code: number? = nil
local n = 0
for w in string.gmatch(line, "%S+") do
n += 1
if n == 2 then
code = tonumber(w)
elseif n > 2 and n <= need + 2 then
local num = tonumber(w)
if not num then
break
end
v[n - 2] = num
end
end
if code and code >= 0 and code % 1 == 0 and #v == need then
table.insert(cmds, { k = k, c = code, v = v })
else
stats.bad += 1
end
elseif k ~= 0 then
stats.bad += 1
end
end
end
return f
end
-- scene(text, opts) -> Scene | nil, message, kind
function Read.scene(text: string, opts: Options?): (Types.Scene?, string?, string?)
local o: Options = opts or {}
local colours = Colors.builtin()
if type(o.ldconfig) == "string" then
Colors.parse(o.ldconfig, colours)
end
local maxDepth = o.maxDepth or 64
local maxTriangles = o.maxTriangles or 2 ^ 24
local maxNodes = o.maxNodes or 2 ^ 20
local withLines = o.lines ~= false
local withOptional = o.optionalLines == true
local stats = { bad = 0, lines = 0 }
-- ------------------------------------------------------------------------------------------ MPD sections
text = string.gsub(text, "\r", "")
local sections: { [string]: string } = {}
local mainName: string? = nil
local mpd = string.find(text, "^%s*0%s+FILE%s") ~= nil or string.find(text, "\n%s*0%s+FILE%s") ~= nil
local mainText = text
if mpd then
local cur: string? = nil
local buf: { string } = {}
local function close()
if cur and sections[cur] == nil then
sections[cur] = table.concat(buf, "\n")
end
cur, buf = nil, {}
end
for line in string.gmatch(text, "[^\n]+") do
local fname = string.match(line, "^%s*0%s+FILE%s+(.-)%s*$")
if fname then
close()
cur = norm(fname)
if not mainName then
mainName = fname
end
elseif string.find(line, "^%s*0%s+NOFILE%f[%W]") then
close()
elseif cur then
table.insert(buf, line)
end
end
close()
mainText = sections[norm(mainName or "")] or ""
end
-- ------------------------------------------------------------------------------------------ files
local cache: { [string]: File | false } = {}
local missing: { [string]: boolean } = {}
local fetchFiles = o.files
local resolve = o.resolve
local function fetch(uri: string): string?
local v: any = if type(fetchFiles) == "table" then fetchFiles[uri] else nil
if v == nil and type(resolve) == "function" then
local ok, res = pcall(resolve, uri)
v = if ok then res else nil
end
return if type(v) == "buffer" then buffer.tostring(v) elseif type(v) == "string" then v else nil
end
local function lookup(name: string): File?
local key = norm(name)
local have = cache[key]
if have ~= nil then
return have or nil
end
local sec = sections[key]
if sec then
local f = parse(sec, name, colours, stats)
cache[key] = f
return f
end
local slash = string.gsub(string.match(name, "^%s*(.-)%s*$") or name, "\\", "/")
for _, prefix in PREFIXES do
for _, cand in { prefix .. slash, prefix .. key } do
local data = fetch(cand)
if data then
local f = parse((string.gsub(data, "\r", "")), name, colours, stats)
f.library = LIBRARY[prefix] == true
cache[key] = f
return f
end
end
end
missing[key] = true
cache[key] = false
return nil
end
local function isModel(f: File): boolean
local m = f.model
if m == nil then
local org = string.lower(f.org or "")
local orgPart = org ~= "" and not string.find(org, "model", 1, true)
if f.main then
m = not orgPart and f.refs > 0
else
local ext = string.match(f.key, "%.(%w+)$")
m = not orgPart and not f.library and (ext == "ldr" or ext == "mpd")
end
f.model = m
end
return m :: boolean
end
-- ------------------------------------------------------------------------------------------ colours, materials
local scene = Types.Scene.new()
local function edgeOf(c: number): number
local e = colours[c]
if e then
return e.edge
end
return if c >= 0x2000000 then 0x2000000 else 0x2333333
end
local function resolveColour(code: number, cur: number): number
if code == 16 then
return cur
elseif code == 24 then
return edgeOf(cur)
end
return code
end
local materialOf: { [string]: number } = {}
local function material(col: number, ds: boolean): number
local key = col .. (if ds then "d" else "")
local have = materialOf[key]
if have then
return have
end
local entry = colours[col]
local rgb, alpha, name, finish = 0x7F7F7F, 255, "Unknown_" .. col, nil
if entry then
rgb, alpha, name, finish = entry.rgb, entry.alpha, entry.name, entry.finish
elseif col >= 0x2000000 and col < 0x4000000 then
rgb = col % 0x1000000
alpha = if col >= 0x3000000 then 128 else 255
name = string.format("#%06X", rgb)
elseif col >= 0x4000000 and col < 0x8000000 then
-- dithered: two 12-bit colours, shown as their mean
local lo, hi = col % 0x1000, (col // 0x1000) % 0x1000
local function ch(v: number, s: number): number
return ((v // s) % 16) * 17
end
rgb = ((ch(lo, 256) + ch(hi, 256)) // 2) * 65536 + ((ch(lo, 16) + ch(hi, 16)) // 2) * 256 + (ch(lo, 1) + ch(hi, 1)) // 2
alpha = if col >= 0x7000000 then 0 elseif col >= 0x5000000 then 128 else 255
name = string.format("Dither_%X", col)
end
local m = Types.Scene.material(name)
m.baseColor = { srgbToLinear((rgb // 65536) / 255), srgbToLinear(((rgb // 256) % 256) / 255), srgbToLinear((rgb % 256) / 255), alpha / 255 }
if alpha < 255 then
m.alphaMode = "blend"
end
m.doubleSided = ds
m.metallic = 0
m.roughness = 0.35
if finish == "CHROME" or finish == "METAL" then
m.metallic, m.roughness = 1, if finish == "CHROME" then 0.15 else 0.4
elseif finish == "PEARLESCENT" or finish == "MATTE_METALLIC" then
m.metallic, m.roughness = 0.6, 0.45
elseif finish == "RUBBER" then
m.roughness = 0.9
end
m.extras = { ldraw = { code = col, name = name, edge = edgeOf(col), finish = finish, luminance = if entry and entry.luminance > 0 then entry.luminance else nil } }
table.insert(scene.materials, m)
materialOf[key] = #scene.materials
return #scene.materials
end
-- ------------------------------------------------------------------------------------------ baking
local failure: string?, failKind: string? = nil, nil
local triangles = 0
local cycles = 0
local function fail(msg: string, kind: string?)
if not failure then
failure, failKind = msg, kind
end
end
-- bake(file, m (3x4 row-major), colour, inv, certified, depth, stack, groups, order, direct)
local function bake(f: File, m: { number }, colour: number, inv: boolean, certified: boolean, depth: number, stack: { [File]: boolean }, groups: { [string]: Group }, order: { Group }, direct: boolean)
if failure then
return
end
if depth > maxDepth then
return fail("limit: sub-files nested deeper than " .. maxDepth, "limit")
end
stack[f] = true
local model = isModel(f)
local m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12 = table.unpack(m)
local det = m1 * (m6 * m11 - m7 * m10) - m2 * (m5 * m11 - m7 * m9) + m3 * (m5 * m10 - m6 * m9)
local cw, clip = false, true
local function group(mode: string, col: number, ds: boolean): Group
local key = mode .. col .. (if ds then "d" else "")
local g = groups[key]
if not g then
g = { mode = mode, colour = col, ds = ds, pos = {}, ctrl = if mode == "optional" then {} else nil }
groups[key] = g
table.insert(order, g)
end
return g
end
local function put(list: { number }, x: number, y: number, z: number)
local n = #list
list[n + 1] = m1 * x + m2 * y + m3 * z + m4
list[n + 2] = m5 * x + m6 * y + m7 * z + m8
list[n + 3] = m9 * x + m10 * y + m11 * z + m12
end
for _, cmd in f.cmds do
if failure then
break
end
local k = cmd.k
local v = cmd.v
if k == 0 then
if cmd.cw ~= nil then
cw = cmd.cw :: boolean
end
if cmd.clip ~= nil then
clip = cmd.clip :: boolean
end
elseif k == 1 then
if not direct then
local sub = lookup(cmd.name :: string)
if sub and stack[sub] then
cycles += 1
elseif sub then
local a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12 = table.unpack(v)
local child = {
m1 * a1 + m2 * a5 + m3 * a9, m1 * a2 + m2 * a6 + m3 * a10, m1 * a3 + m2 * a7 + m3 * a11, m1 * a4 + m2 * a8 + m3 * a12 + m4,
m5 * a1 + m6 * a5 + m7 * a9, m5 * a2 + m6 * a6 + m7 * a10, m5 * a3 + m6 * a7 + m7 * a11, m5 * a4 + m6 * a8 + m7 * a12 + m8,
m9 * a1 + m10 * a5 + m11 * a9, m9 * a2 + m10 * a6 + m11 * a10, m9 * a3 + m10 * a7 + m11 * a11, m9 * a4 + m10 * a8 + m11 * a12 + m12,
}
local childCert = if model then true else certified and f.certified and clip
bake(sub, child, resolveColour(cmd.c, colour), inv ~= (cmd.inv == true), childCert, depth + 1, stack, groups, order, false)
end
end
elseif k == 3 or k == 4 then
local col = resolveColour(cmd.c, colour)
local one = certified and f.certified and clip
local g = group("triangles", col, not one)
local rev = cw ~= inv ~= (det < 0)
local p = g.pos
local nt = if k == 3 then 1 else 2
triangles += nt
if triangles > maxTriangles then
return fail(string.format("limit: more than %d triangles", maxTriangles), "limit")
end
local function tri(a: number, b: number, c: number)
if rev then
a, c = c, a
end
put(p, v[a * 3 + 1], v[a * 3 + 2], v[a * 3 + 3])
put(p, v[b * 3 + 1], v[b * 3 + 2], v[b * 3 + 3])
put(p, v[c * 3 + 1], v[c * 3 + 2], v[c * 3 + 3])
end
tri(0, 1, 2)
if k == 4 then
tri(0, 2, 3)
end
elseif k == 2 and withLines then
local g = group("lines", resolveColour(cmd.c, colour), false)
put(g.pos, v[1], v[2], v[3])
put(g.pos, v[4], v[5], v[6])
elseif k == 5 and withOptional then
local g = group("optional", resolveColour(cmd.c, colour), false)
put(g.pos, v[1], v[2], v[3])
put(g.pos, v[4], v[5], v[6])
local ctrl = g.ctrl :: { number }
for _ = 1, 2 do
put(ctrl, v[7], v[8], v[9])
put(ctrl, v[10], v[11], v[12])
end
end
end
stack[f] = nil
end
local function f32(list: { number }, from: number, step: number, count: number): Types.Accessor
local b = buffer.create(count * 12)
for i = 0, count - 1 do
local s = from + i * step
buffer.writef32(b, i * 12, list[s])
buffer.writef32(b, i * 12 + 4, list[s + 1])
buffer.writef32(b, i * 12 + 8, list[s + 2])
end
return Types.Scene.accessor(b, "f32", 3, count)
end
-- the mesh of a file baked at the identity (nil when it has no geometry)
local meshOf: { [string]: number | false } = {}
local function meshFor(f: File, colour: number, inv: boolean, direct: boolean): number?
local key = f.key .. "|" .. colour .. "|" .. (if inv then "i" else "") .. (if direct then "d" else "")
local have = meshOf[key]
if have ~= nil then
return have or nil
end
local groups: { [string]: Group } = {}
local order: { Group } = {}
bake(f, IDENTITY12, colour, inv, true, 0, {}, groups, order, direct)
local mesh: Types.Mesh = { name = f.name, primitives = {} }
for _, g in order do
local count = #g.pos // 3
if count > 0 then
local prim: Types.Primitive = { attributes = { POSITION = f32(g.pos, 1, 3, count) }, mode = if g.mode == "triangles" then "triangles" else "lines" }
prim.material = material(g.colour, g.ds)
if g.mode == "optional" then
local ctrl = g.ctrl :: { number }
prim.attributes._CONTROL_0 = f32(ctrl, 1, 6, count)
prim.attributes._CONTROL_1 = f32(ctrl, 4, 6, count)
prim.extras = { ldraw = { optional = true } }
end
table.insert(mesh.primitives, prim)
end
end
if #mesh.primitives == 0 then
meshOf[key] = false
return nil
end
table.insert(scene.meshes, mesh)
meshOf[key] = #scene.meshes
return #scene.meshes
end
-- ------------------------------------------------------------------------------------------ the node tree
local mainFile = parse(mainText, mainName or "main", colours, stats)
mainFile.main = true
if stats.lines == 0 then
return nil, "no LDraw lines", nil
end
if mainName then
cache[norm(mainName)] = mainFile
end
local mainColour = o.color or 16
local function newNode(node: Types.Node): number
table.insert(scene.nodes, node)
if #scene.nodes > maxNodes then
fail(string.format("limit: more than %d nodes", maxNodes), "limit")
end
return #scene.nodes
end
local function expand(f: File, colour: number, inv: boolean, out: { number }, depth: number, stack: { [File]: boolean })
if failure then
return
end
if depth > maxDepth then
return fail("limit: sub-models nested deeper than " .. maxDepth, "limit")
end
stack[f] = true
local direct = meshFor(f, colour, inv, true)
if direct then
table.insert(out, newNode({ name = f.name, children = {}, mesh = direct }))
end
for _, cmd in f.cmds do
if failure then
break
end
if cmd.k == 1 then
local sub = lookup(cmd.name :: string)
if sub and stack[sub] then
cycles += 1
elseif sub then
local v = cmd.v
local c = resolveColour(cmd.c, colour)
local subInv = inv ~= (cmd.inv == true)
local node: Types.Node = {
name = cmd.name,
children = {},
matrix = { v[1], v[5], v[9], 0, v[2], v[6], v[10], 0, v[3], v[7], v[11], 0, v[4], v[8], v[12], 1 },
extras = { ldraw = { file = sub.name, color = c, step = cmd.step, invert = if subInv then true else nil } },
}
local index = newNode(node)
if isModel(sub) then
expand(sub, c, subInv, node.children, depth + 1, stack)
else
node.mesh = meshFor(sub, c, subInv, false)
end
table.insert(out, index)
end
end
end
stack[f] = nil
end
local top: { number } = {}
if o.flatten or not isModel(mainFile) then
local mesh = meshFor(mainFile, mainColour, false, false)
table.insert(top, newNode({ name = mainFile.name, children = {}, mesh = mesh }))
else
expand(mainFile, mainColour, false, top, 0, {})
end
if failure then
return nil, failure, failKind
end
if o.upright == false then
scene.roots = top
else
table.insert(scene.nodes, { name = "LDraw", children = top, matrix = table.clone(FLIP) })
scene.roots = { #scene.nodes }
scene.meta.up = "y"
end
scene.meta.unit = 0.0004
local missingList: { string } = {}
for k in missing do
table.insert(missingList, k)
end
table.sort(missingList)
local nfiles = 0
for _, f in cache do
if f then
nfiles += 1
end
end
scene.meta.source = {
format = "ldraw",
mpd = mpd,
name = mainName,
title = mainFile.title,
author = mainFile.author,
files = nfiles,
missing = missingList,
cycles = cycles,
badLines = stats.bad,
up = if o.upright == false then "-y" else nil,
}
return scene, nil, nil
end
return Read
+105
View File
@@ -0,0 +1,105 @@
--!strict
-- model/ldraw: LDraw (.ldr / .dat / .mpd), read. Written from the LDraw File Format specification 1.0.2, the MPD and
-- BFC (back face culling) language extensions and the colour definition (!COLOUR) extension (ldraw.org); checked
-- against an independent expansion in the fixture generator and LeoCAD's OBJ export of library parts and models.
-- Reads: line types 0 (meta: Name / Author / !LDRAW_ORG / STEP / !COLOUR / BFC), 1 (sub-file references: colour +
-- 3x4 matrix), 2 (lines), 3 (triangles), 4 (quads, split in two), 5 (optional lines: skipped, or opts.optionalLines
-- -> "lines" primitives with _CONTROL_0 / _CONTROL_1 attributes and prim.extras.ldraw.optional). MPD files split at
-- `0 FILE` / `0 NOFILE` (the first file is the model); other sub-files come through opts.files / opts.resolve, tried
-- as written (backslashes as slashes), then lower case, under "", "parts/", "p/", "parts/s/" and "models/". Missing
-- sub-files are skipped and listed (meta.source.missing); a file that places itself is skipped (meta.source.cycles).
-- Scene: parts (files whose !LDRAW_ORG type is not a model, library files, .dat sub-files, a main file without
-- references) are baked into one mesh per (part, colour, INVERTNEXT), shared by every placement; models (the main
-- file, .ldr / .mpd sub-models) become nodes: one node per reference with the reference's matrix (node.extras.ldraw =
-- { file, color, step, invert? }), a model's own geometry on an extra node. opts.flatten bakes the whole model into one
-- mesh. Primitives: one "triangles" primitive per colour (and per one- / double-sided), "lines" for type 2 (opts.lines
-- = false drops them); no normals, no indices (each triangle has its own three vertices).
-- BFC, inside a part: CERTIFY / NOCERTIFY, CW / CCW, CLIP / NOCLIP and INVERTNEXT; faces are written counter-clockwise
-- (glTF's front faces) after the reference matrices' mirroring; faces of uncertified files (and their sub-files) or
-- under NOCLIP get double-sided materials. Model files do not limit the certification of the parts they place.
-- Colours: 16 (the parent's colour; opts.color at the top, default 16 "Main_Colour"), 24 (the parent colour's edge
-- colour), codes from the built-in LDConfig.ldr table (model/ldraw/Colors; !COLOUR lines in the files and opts.ldconfig
-- text add or replace entries), direct colours 0x2RRGGBB (opaque) / 0x3RRGGBB (transparent) and the old dithered
-- 0x4-0x7 codes. One material per colour (baseColor linear, ALPHA -> blend, CHROME / METAL / PEARLESCENT / RUBBER ->
-- metallic / roughness; extras.ldraw = { code, name, edge, finish?, luminance? }).
-- Axes: LDraw is right-handed with -Y up, 1 LDU = 0.4 mm. The vertices and matrices keep LDraw's values; a root node
-- "LDraw" turns the model 180 degrees about X so the scene is Y up (meta.up = "y", meta.unit = 0.0004); opts.upright =
-- false leaves it out (meta.up = nil, meta.source.up = "-y").
-- meta.source = { format, mpd, name?, title?, author?, files, missing, cycles, badLines, up? }.
-- Not supported: writing; !TEXMAP and !DATA (texture mapping, embedded images: ignored); the LDCad / MLCad / LPub meta
-- commands (ignored); BFC in model files' references (models place parts as certified).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Sniff = require("@formats/core/Sniff")
local Types = require("@formats/Types")
local Read = require("@formats/model/ldraw/Read")
local Colors = require("@formats/model/ldraw/Colors")
-- ------------------------------------------------------------------------------------------------ contract
local Ldraw = {
name = "ldraw",
category = "model",
extensions = { "ldr", "mpd", "dat" },
mime = { "application/x-ldraw", "application/x-multi-part-ldraw" },
deps = { "core/Err", "core/Bytes", "core/Sniff", "Types" },
caps = { decode = true, encode = false, materials = true, lines = true, instancing = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
resolve: ((uri: string) -> any)?, -- sub-files (parts, primitives) by library path (the api sets it for paths)
files: { [string]: any }?, -- or: the files by library path ("parts/3001.dat", "p/stud.dat", ...)
ldconfig: string?, -- LDConfig.ldr text: its !COLOUR lines add to / replace the built-in colours
color: number?, -- the colour of code 16 at the top (default 16, "Main_Colour")
upright: boolean?, -- add the root node turning -Y up into Y up (default true)
flatten: boolean?, -- one mesh for the whole model instead of a node per reference (default false)
lines: boolean?, -- type 2 edge lines as "lines" primitives (default true)
optionalLines: boolean?, -- type 5 optional lines too (default false)
maxDepth: number?, -- sub-file nesting (default 64)
maxTriangles: number?, -- default 2^24
maxNodes: number?, -- default 2^20
}
-- ------------------------------------------------------------------------------------------------ sniff
function Ldraw.sniff(r: Bytes.Reader): number
local head = Sniff.text(r, 2048, true)
if string.find(head, "^0%s+FILE%s") then
return 0.9
end
if string.find(head, "\n%s*1%s+%S+" .. string.rep("%s+[-+%deE.]+", 12) .. "%s+[^\n]+%.[dDlL][aAdD][tTrR]%s*\r?\n") then
return 0.8
end
if string.find(head, "^0[ \t]+%a") and string.find(head, "\n%s*[1-5]%s+%S+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]+%s+[-+%d.]") then
return 0.4
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Ldraw.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local text = Sniff.dropBom(buffer.readstring(r.buf, r.base, r.limit - r.base))
-- the scene builder is plain (not native) code: a bug there must not escape as an error
local ok, scene, msg, kind = pcall(Read.scene, text, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "bad model: " .. tostring(scene))
end
if not scene then
return nil, Err.from(msg, nil, kind)
end
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- colors(ldconfig?) -> { [code] = { name, rgb (0xRRGGBB sRGB), edge (a code or 0x2RRGGBB), alpha (0..255), luminance,
-- finish? } }: the built-in LDConfig.ldr table, with the !COLOUR lines of ldconfig added
function Ldraw.colors(ldconfig: string?): { [number]: any }
local t = Colors.builtin()
if ldconfig then
Colors.parse(ldconfig, t)
end
return t
end
return Ldraw
+469
View File
@@ -0,0 +1,469 @@
--!strict
-- model/lwo/Build: a parsed LightWave object (model/lwo/Parse) -> Types.Scene. LightWave is left-handed (y up, z
-- away from the viewer, clockwise front faces): z is negated and the winding reversed, so the scene is glTF's
-- right-handed y-up with counter-clockwise front faces (assimp does the same). One node per layer (translation = its
-- pivot relative to the parent layer's pivot, geometry relative to the pivot, so world positions are the file's),
-- one mesh per layer, one primitive per surface (and per kind: polygons, lines, points; subdivision patches apart,
-- flagged extras.lwo.subdivision). Vertices are shared per point, split where a VMAD gives a corner its own value.
-- Plain code (the caller wraps it in pcall).
local Types = require("@formats/Types")
local Parse = require("@formats/model/lwo/Parse")
local Build = {}
local Scene = Types.Scene
local writef32, writeu32 = buffer.writef32, buffer.writeu32
type Group = { material: number, class: string, polys: { number } } -- class: "poly" / "patch" / "line" / "point"
local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", gif = "image/gif", tif = "image/tiff", tiff = "image/tiff", iff = "image/x-iff" }
-- ------------------------------------------------------------------------------------------------ materials
local function textureIndex(scene: Types.Scene, cache: { [string]: number }, path: string): number
local hit = cache[path]
if hit then
return hit
end
local norm = string.gsub(path, "\\", "/")
local base = string.match(norm, "([^/:]+)$") or norm
local ext = string.lower(string.match(base, "%.(%w+)$") or "")
table.insert(scene.textures, { name = base, uri = base, mime = MIME[ext], extras = { lwo = { path = path } } })
cache[path] = #scene.textures
return #scene.textures
end
local function material(scene: Types.Scene, m: Parse.Model, surf: Parse.Surface, uvSets: { [string]: number }, cache: { [string]: number }): Types.Material
local mat = Scene.material(surf.name)
local v = surf.values
local c = surf.color
local tran = math.clamp(v.TRAN or 0, 0, 1)
mat.baseColor = { c[1], c[2], c[3], 1 - tran }
if tran > 0 then
mat.alphaMode = "blend"
end
mat.metallic = 0
local gloss = v.GLOS
mat.roughness = if gloss and (v.SPEC or 0) > 0 then math.clamp(1 - gloss, 0, 1) else 1
local lumi = v.LUMI or 0
if lumi > 0 then
mat.emissive = { c[1] * lumi, c[2] * lumi, c[3] * lumi }
end
mat.doubleSided = surf.side == 3
local maps = {}
local blocks = table.clone(surf.blocks)
table.sort(blocks, function(a: Parse.Block, b: Parse.Block): boolean
return a.ordinal < b.ordinal
end)
for _, blk in blocks do
local path = if blk.file then blk.file elseif blk.clip then m.clips[blk.clip] else nil
local entry: { [string]: any } = { kind = blk.kind, channel = blk.channel, enabled = blk.enabled, opacity = blk.opacity, projection = blk.projection, axis = blk.axis, uvmap = blk.uvmap }
if path and (blk.kind == "IMAP" or blk.kind == "TEX") then
local ti = textureIndex(scene, cache, path)
entry.texture = ti
if blk.enabled then
local ref: Types.TextureRef = { texture = ti }
if blk.uvmap and uvSets[blk.uvmap] then
ref.texCoord = uvSets[blk.uvmap]
end
if blk.channel == "COLR" and not mat.baseColorTexture then
mat.baseColorTexture = ref
elseif blk.channel == "LUMI" and not mat.emissiveTexture then
mat.emissiveTexture = ref
if lumi <= 0 then
mat.emissive = { 1, 1, 1 }
end
end
end
end
table.insert(maps, entry)
end
local extras: { [string]: any } = { color = table.clone(c), side = surf.side, maps = maps, source = surf.source }
for k, x in v do
extras[string.lower(k)] = x
end
if surf.vcol then
extras.vcol = surf.vcol.name
end
mat.extras = { lwo = extras }
return mat
end
-- ------------------------------------------------------------------------------------------------ geometry
local function groupLayer(layer: Parse.Layer, surfaceOf: (number?) -> number): { Group }
local groups: { Group } = {}
local byKey: { [string]: Group } = {}
for i, poly in layer.polys do
local kind = poly.kind
local n = #poly.corners
if (kind == "FACE" or kind == "PTCH" or kind == "SUBD") and n > 0 then
local class = if n == 1 then "point" elseif n == 2 then "line" elseif kind == "FACE" then "poly" else "patch"
local mi = surfaceOf(poly.surf)
local key = mi .. class
local g = byKey[key]
if not g then
g = { material = mi, class = class, polys = {} }
byKey[key] = g
table.insert(groups, g)
end
table.insert(g.polys, i - 1)
end
end
local rank: { [string]: number } = { poly = 1, patch = 2, line = 3, point = 4 }
table.sort(groups, function(a: Group, b: Group): boolean
if a.material ~= b.material then
return a.material < b.material
end
return rank[a.class] < rank[b.class]
end)
return groups
end
-- the corners of a face in output order (winding reversed for the handedness change, first corner kept)
local function ordered(corners: { number }): { number }
local n = #corners
local out = table.create(n) :: { number }
out[1] = corners[1]
for k = 2, n do
out[k] = corners[n - k + 2]
end
return out
end
type Attr = { map: Parse.Map, name: string, comps: number }
local function primitive(layer: Parse.Layer, g: Group, attrs: { Attr }, morphs: { Parse.Map }, triangulate: boolean): Types.Primitive
local pts, pivot = layer.pts, layer.pivot
local vertOf: { [number]: number } = {}
local srcPoint: { number } = {} -- vertex (1-based) -> point
local srcPoly: { number } = {} -- vertex -> the polygon whose VMAD values it carries (-1: none)
local indices: { number } = {}
local faces: { number } = {}
local madMaps: { Parse.Map } = {}
for _, a in attrs do
if next(a.map.mad) then
table.insert(madMaps, a.map)
end
end
for _, m in morphs do
if next(m.mad) then
table.insert(madMaps, m)
end
end
local function vertex(f: number, p: number): number
local own = false
for _, m in madMaps do
local row = m.mad[f]
if row and row[p] then
own = true
break
end
end
if not own then
local v = vertOf[p]
if v then
return v
end
end
table.insert(srcPoint, p)
table.insert(srcPoly, if own then f else -1)
local v = #srcPoint - 1
if not own then
vertOf[p] = v
end
return v
end
for _, f in g.polys do
local corners = ordered(layer.polys[f + 1].corners)
local n = #corners
local vs = table.create(n) :: { number }
for k = 1, n do
vs[k] = vertex(f, corners[k])
end
if g.class == "poly" or g.class == "patch" then
if triangulate then
for k = 2, n - 1 do
table.insert(indices, vs[1])
table.insert(indices, vs[k])
table.insert(indices, vs[k + 1])
end
else
table.insert(faces, n)
table.move(vs, 1, n, #indices + 1, indices)
end
else
table.move(vs, 1, n, #indices + 1, indices)
end
end
local nv = #srcPoint
local pos = buffer.create(nv * 12)
for v = 1, nv do
local p = srcPoint[v] * 3
local o = (v - 1) * 12
writef32(pos, o, pts[p + 1] - pivot[1])
writef32(pos, o + 4, pts[p + 2] - pivot[2])
writef32(pos, o + 8, -(pts[p + 3] - pivot[3]))
end
local attributes: { [string]: Types.Accessor } = { POSITION = Scene.accessor(pos, "f32", 3, nv) }
-- the value of map m for vertex v (1-based), or nil
local function value(m: Parse.Map, v: number): ({ number }?, number?)
local f = srcPoly[v]
if f >= 0 then
local row = m.mad[f]
local hit = row and row[srcPoint[v]]
if hit then
return hit, nil
end
end
local p = srcPoint[v]
if m.has[p] then
return nil, p * m.dims
end
return nil, nil
end
local names: { [string]: string } = {}
for _, a in attrs do
local m, comps = a.map, a.comps
local data = buffer.create(nv * comps * 4)
for v = 1, nv do
local o = (v - 1) * comps * 4
local direct, at = value(m, v)
local x: { number } = if direct then direct elseif at then { m.vals[at + 1], m.vals[at + 2] or 0, m.vals[at + 3] or 0, m.vals[at + 4] or 1 } else {}
if m.kind == "uv" then
writef32(data, o, x[1] or 0)
writef32(data, o + 4, 1 - (x[2] or 0))
elseif m.kind == "color" then
writef32(data, o, x[1] or 1)
writef32(data, o + 4, x[2] or 1)
writef32(data, o + 8, x[3] or 1)
writef32(data, o + 12, if m.dims == 4 and x[4] then x[4] else 1)
elseif m.kind == "normal" then
writef32(data, o, x[1] or 0)
writef32(data, o + 4, x[2] or 0)
writef32(data, o + 8, -(x[3] or 0))
else
writef32(data, o, x[1] or 0)
end
end
attributes[a.name] = Scene.accessor(data, "f32", comps, nv)
names[a.name] = m.name
end
local prim: Types.Primitive = { attributes = attributes, mode = "triangles" }
if #morphs > 0 then
local targets: { { [string]: Types.Accessor } } = {}
local targetNames: { string } = {}
for _, m in morphs do
local d = buffer.create(nv * 12)
for v = 1, nv do
local direct, at = value(m, v)
local x: { number }? = if direct then direct elseif at then { m.vals[at + 1], m.vals[at + 2], m.vals[at + 3] } else nil
if x then
local p = srcPoint[v] * 3
local dx, dy, dz = x[1], x[2], x[3]
if m.kind == "spot" then
dx, dy, dz = dx - pts[p + 1], dy - pts[p + 2], dz - pts[p + 3]
end
writef32(d, (v - 1) * 12, dx)
writef32(d, (v - 1) * 12 + 4, dy)
writef32(d, (v - 1) * 12 + 8, -dz)
end
end
local tgt: { [string]: Types.Accessor } = { POSITION = Scene.accessor(d, "f32", 3, nv) }
table.insert(targets, tgt)
table.insert(targetNames, m.name)
end
prim.targets = targets
names._targets = table.concat(targetNames, "\n")
end
local ib = buffer.create(#indices * 4)
for k, x in indices do
writeu32(ib, (k - 1) * 4, x)
end
prim.indices = Scene.accessor(ib, "u32", 1, #indices)
if g.class == "line" then
prim.mode = "lines"
elseif g.class == "point" then
prim.mode = "points"
elseif not triangulate then
prim.mode = "polygons"
local fb = buffer.create(#faces * 4)
for k, x in faces do
writeu32(fb, (k - 1) * 4, x)
end
prim.faces = Scene.accessor(fb, "u32", 1, #faces)
end
prim.material = g.material
local extras: { [string]: any } = { maps = names }
if g.class == "patch" then
extras.subdivision = true
end
prim.extras = { lwo = extras }
return prim
end
-- ------------------------------------------------------------------------------------------------ scene
function Build.scene(m: Parse.Model, opts: { triangulate: boolean? }?): (Types.Scene?, string?)
local triangulate = not (opts and opts.triangulate == false)
local scene = Scene.new()
scene.meta.up = "y"
scene.meta.source = { format = "lwo", version = m.version, skipped = m.skipped }
-- texture coordinate sets: every TXUV map name, in order of first appearance, gets one TEXCOORD_n index
local uvSets: { [string]: number } = {}
local nuv = 0
for _, layer in m.layers do
for _, map in layer.maps do
if map.kind == "uv" and uvSets[map.name] == nil then
uvSets[map.name] = nuv
nuv += 1
end
end
end
-- materials: one per surface, then one per tag without a surface, then a default one
local texCache: { [string]: number } = {}
local bySurfName: { [string]: number } = {}
for i, surf in m.surfaces do
scene.materials[i] = material(scene, m, surf, uvSets, texCache)
if bySurfName[surf.name] == nil then
bySurfName[surf.name] = i
end
local low = string.lower(surf.name)
if bySurfName[low] == nil then
bySurfName[low] = i
end
end
local tagMat: { [number]: number } = {}
local default: number? = nil
local function surfaceOf(tag: number?): number
if tag ~= nil then
local hit = tagMat[tag]
if hit then
return hit
end
local name = m.tags[tag + 1]
if name then
local mi = bySurfName[name] or bySurfName[string.lower(name)]
if not mi then
table.insert(scene.materials, Scene.material(name))
mi = #scene.materials
bySurfName[name] = mi
end
tagMat[tag] = mi
return mi
end
end
if not default then
local mat = Scene.material("Default")
mat.baseColor = { 0.6, 0.6, 0.6, 1 }
mat.metallic = 0
table.insert(scene.materials, mat)
default = #scene.materials
end
return default :: number
end
-- nodes and meshes
local nodeOf: { [number]: number } = {}
local layerOfNode: { Parse.Layer } = {}
for _, layer in m.layers do
local hasGeometry = #layer.polys > 0
if not (layer.implicit and not hasGeometry) then
local node: Types.Node = { name = layer.name, children = {} }
table.insert(scene.nodes, node)
local ni = #scene.nodes
layerOfNode[ni] = layer
if nodeOf[layer.index] == nil then
nodeOf[layer.index] = ni
end
node.extras = { lwo = { index = layer.index, parent = layer.parent, pivot = table.clone(layer.pivot) } }
local groups = groupLayer(layer, surfaceOf)
if #groups > 0 then
local attrs: { Attr } = {}
local morphs: { Parse.Map } = {}
local hasUv = {}
local maxUv = -1
for _, map in layer.maps do
if map.kind == "uv" then
hasUv[uvSets[map.name]] = map
maxUv = math.max(maxUv, uvSets[map.name])
elseif map.kind == "morph" or map.kind == "spot" then
table.insert(morphs, map)
end
end
local empty: Parse.Map = { kind = "uv", name = "", dims = 2, vals = {}, has = {}, mad = {} }
for k = 0, maxUv do
table.insert(attrs, { map = hasUv[k] or empty, name = "TEXCOORD_" .. k, comps = 2 })
end
local nw, nc, hasNormal = 0, 0, false
for _, map in layer.maps do
if map.kind == "normal" and not hasNormal then
hasNormal = true
table.insert(attrs, { map = map, name = "NORMAL", comps = 3 })
elseif map.kind == "weight" then
table.insert(attrs, { map = map, name = "_WEIGHT_" .. nw, comps = 1 })
nw += 1
end
end
local prims = {}
for _, g in groups do
local mat = scene.materials[g.material]
local ex: any = mat and mat.extras
local vcol = ex and ex.lwo and ex.lwo.vcol
local pa = table.clone(attrs)
nc = 0
for _, map in layer.maps do
if map.kind == "color" then
if map.name == vcol then
table.insert(pa, { map = map, name = "COLOR_0", comps = 4 })
else
table.insert(pa, { map = map, name = "_COLOR_" .. nc, comps = 4 })
nc += 1
end
end
end
table.insert(prims, primitive(layer, g, pa, morphs, triangulate))
end
local mesh: Types.Mesh = { name = layer.name, primitives = prims }
if #morphs > 0 then
mesh.weights = table.create(#morphs, 0)
local tn = {}
for _, mp in morphs do
table.insert(tn, mp.name)
end
mesh.extras = { targetNames = tn }
end
table.insert(scene.meshes, mesh)
node.mesh = #scene.meshes
end
end
end
-- the layer hierarchy (parents by layer index; a link that would close a cycle is dropped)
local parentOf: { [number]: number } = {}
for ni, layer in layerOfNode do
local pi = if layer.parent ~= nil then nodeOf[layer.parent] else nil
if pi and pi ~= ni then
local up, steps = pi, 0
while up and up ~= ni and steps <= #scene.nodes do
up = parentOf[up]
steps += 1
end
if up ~= ni then
parentOf[ni] = pi
end
end
end
for ni = 1, #scene.nodes do
local layer = layerOfNode[ni]
local pi = parentOf[ni]
local pp = if pi then layerOfNode[pi].pivot else { 0, 0, 0 }
local t = { layer.pivot[1] - pp[1], layer.pivot[2] - pp[2], -(layer.pivot[3] - pp[3]) }
if t[1] ~= 0 or t[2] ~= 0 or t[3] ~= 0 then
scene.nodes[ni].translation = t
end
if pi then
table.insert(scene.nodes[pi].children, ni)
else
table.insert(scene.roots, ni)
end
end
return scene, nil
end
return Build
+551
View File
@@ -0,0 +1,551 @@
--!strict
-- model/lwo/Parse: the LightWave object chunks -> layers, tags, surfaces and clips (plain tables; model/lwo/Build
-- makes the Scene). From the LWO2 specification (LightWave 6 "Object Files", Ernie Wright) and the LWOB one (LightWave
-- 5.x), checked against what assimp's LWO importer reads (no code taken).
-- LWO2 / LXOB: TAGS, LAYR (index, pivot, name, parent), PNTS (more than one per layer: later POLS / VMAP indices are
-- relative to the latest), VMAP / VMAD (TXUV, RGB, RGBA, WGHT, MNVW, NORM (Modo), MORF, SPOT; others skipped), POLS
-- (FACE, PTCH, SUBD kept; CURV, BONE, MBAL and unknown types counted and skipped), PTAG (SURF, and MATR in Modo
-- files), SURF (COLR, DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SIDE, SMAN, RIND, VCOL, BLOK image / procedural
-- / gradient / shader blocks with their header and IMAP sub-chunks; derived surfaces), CLIP (STIL, ISEQ, XREF).
-- LWOB: SRFS, PNTS, POLS (detail polygons flattened), SURF (COLR, FLAG, the U2 and V* float values, GLOS, SMAN,
-- CTEX ... TTEX with TIMG / TFLG / TVAL). Not read: envelopes (ENVL), LWO3, Modo ITEM / ACTN chunks.
-- Plain code (the caller wraps it in pcall); bad data returns nil, message.
local Bytes = require("@formats/core/Bytes")
local Chunks = require("@formats/containers/Chunks")
local Parse = {}
export type Map = {
kind: string, -- "uv" | "color" | "normal" | "weight" | "morph" | "spot"
name: string,
dims: number,
vals: { number }, -- per point: vals[point * dims + c + 1]
has: { [number]: boolean },
mad: { [number]: { [number]: { number } } }, -- VMAD: mad[poly][point] = values
}
export type Poly = { kind: string, surf: number?, corners: { number } } -- corners: 0-based point indices
export type Layer = {
index: number,
name: string?,
parent: number?,
pivot: { number },
pts: { number }, -- x, y, z flat
polys: { Poly },
maps: { Map },
implicit: boolean?, -- the layer before any LAYR
}
export type Block = {
kind: string, -- IMAP / PROC / GRAD / SHDR, or "TEX" (LWOB)
ordinal: string,
channel: string, -- COLR, DIFF, LUMI, SPEC, GLOS, REFL, TRAN, RIND, TRNL, BUMP
enabled: boolean,
opacity: number,
projection: number?, -- 0 planar, 1 cylindrical, 2 spherical, 3 cubic, 4 front, 5 UV
axis: number?,
clip: number?,
file: string?, -- LWOB: the TIMG path
uvmap: string?,
wrap: { number }?,
negative: boolean?,
}
export type Surface = {
name: string,
values: { [string]: number }, -- COLR is separate; DIFF, LUMI, SPEC, REFL, TRAN, TRNL, GLOS, BUMP, SMAN, RIND
color: { number },
side: number,
vcol: { name: string, kind: string, intensity: number }?,
blocks: { Block },
source: string?,
}
export type Model = {
version: string, -- "LWO2" | "LWOB" | "LXOB"
tags: { string },
layers: { Layer },
surfaces: { Surface },
clips: { [number]: string }, -- clip index -> path
skipped: { [string]: number },
corners: number,
}
local MAP_KINDS: { [string]: string } = {
TXUV = "uv",
RGB = "color",
RGBA = "color",
WGHT = "weight",
MNVW = "weight",
NORM = "normal",
MORF = "morph",
SPOT = "spot",
}
-- ------------------------------------------------------------------------------------------------ primitives
-- S0: a NUL-terminated string padded to an even length
local function s0(r: Bytes.Reader): string
local start = r.pos
local s = r:cstring()
if (r.pos - start) % 2 == 1 and r.pos < r.limit then
r.pos += 1
end
return s
end
-- VX: a variable-length index (2 bytes, or 4 bytes after an 0xFF byte)
local function vx(r: Bytes.Reader): number
if r:peekU8() == 0xFF then
return r:u32be() - 0xFF000000
end
return r:u16be()
end
local function id4(r: Bytes.Reader): string
local s = r:string(4)
return (string.gsub(s, " +$", ""))
end
-- sub-chunks (LWO2: 4-byte id, 2-byte size, padded to even) of [p, e): calls f(id, reader over the body)
local function subchunks(buf: buffer, p: number, e: number, f: (string, Bytes.Reader) -> ())
while p + 6 <= e do
local id = buffer.readstring(buf, p, 4)
local n = buffer.readu8(buf, p + 4) * 256 + buffer.readu8(buf, p + 5)
local body = p + 6
local avail = math.min(n, e - body)
f((string.gsub(id, " +$", "")), Bytes.reader(buf, body, avail))
p = body + n + (n % 2)
end
end
-- ------------------------------------------------------------------------------------------------ geometry
local function newLayer(index: number): Layer
return { index = index, name = nil, parent = nil, pivot = { 0, 0, 0 }, pts = {}, polys = {}, maps = {} }
end
local function readPoints(r: Bytes.Reader, layer: Layer, limit: number): string?
local n = r:remaining() // 12
if #layer.pts // 3 + n > limit then
return "limit: more than " .. limit .. " points"
end
local pts = layer.pts
local k = #pts
for _ = 1, n * 3 do
k += 1
pts[k] = r:f32be()
end
return nil
end
-- POLS (LWO2): returns nil or an error
local function readPolys(r: Bytes.Reader, layer: Layer, kind: string, ptBase: number, budget: { number }): string?
local polys = layer.polys
local npts = #layer.pts // 3
while r:remaining() >= 2 do
local n = bit32.band(r:u16be(), 0x3FF)
local corners = table.create(n) :: { number }
for i = 1, n do
local p = vx(r) + ptBase
if p >= npts and not r.err then
return "polygon point index " .. p .. " out of range (" .. npts .. " points)"
end
corners[i] = p
end
if r.err then
return "truncated polygon list"
end
budget[1] -= n
if budget[1] < 0 then
return "limit: too many polygon corners"
end
table.insert(polys, { kind = kind, surf = nil, corners = corners })
end
return nil
end
-- POLS (LWOB): n, n x U2, surface I2 (negative: detail polygons follow, after a U2 count)
local function readPolysB(r: Bytes.Reader, layer: Layer, budget: { number }): string?
local polys = layer.polys
local npts = #layer.pts // 3
while r:remaining() >= 4 do
local n = r:u16be()
local corners = table.create(n) :: { number }
for i = 1, n do
local p = r:u16be()
if p >= npts and not r.err then
return "polygon point index " .. p .. " out of range (" .. npts .. " points)"
end
corners[i] = p
end
local surf = r:i16be()
if r.err then
return "truncated polygon list"
end
if surf < 0 then
surf = -surf
r:u16be() -- the detail polygon count: they follow as ordinary records
end
budget[1] -= n
if budget[1] < 0 then
return "limit: too many polygon corners"
end
if n > 0 then
table.insert(polys, { kind = "FACE", surf = surf - 1, corners = corners })
end
end
return nil
end
local function findMap(layer: Layer, kind: string, name: string, dims: number): Map
for _, m in layer.maps do
if m.kind == kind and m.name == name then
return m
end
end
local m: Map = { kind = kind, name = name, dims = dims, vals = {}, has = {}, mad = {} }
table.insert(layer.maps, m)
return m
end
local function readVmap(r: Bytes.Reader, layer: Layer, perPoly: boolean, ptBase: number, polyBase: number, skipped: { [string]: number })
local typ = id4(r)
local dims = r:u16be()
local name = s0(r)
local kind = MAP_KINDS[typ]
if r.err or not kind then
skipped["VMAP." .. typ] = (skipped["VMAP." .. typ] or 0) + 1
return
end
local want = if kind == "uv" then 2 elseif kind == "color" then 4 elseif kind == "weight" then 1 else 3
if dims < 1 or dims > 16 or (kind ~= "color" and dims < want) or (kind == "color" and dims < 3) then
skipped["VMAP." .. typ] = (skipped["VMAP." .. typ] or 0) + 1
return
end
local m = findMap(layer, kind, name, want)
local npts = #layer.pts // 3
local npolys = #layer.polys
local vals, has, mad = m.vals, m.has, m.mad
while r:remaining() >= 2 do
local p = vx(r) + ptBase
local f = if perPoly then vx(r) + polyBase else -1
local v = table.create(want, 1) :: { number }
for c = 1, dims do
local x = r:f32be()
if c <= want then
v[c] = x
end
end
if r.err then
break
end
if p < npts then
if perPoly then
if f < npolys then
local row = mad[f]
if not row then
row = {}
mad[f] = row
end
row[p] = v
end
else
has[p] = true
for c = 1, want do
vals[p * want + c] = v[c]
end
end
end
end
end
local function readPtag(r: Bytes.Reader, layer: Layer, polyBase: number)
local typ = id4(r)
if typ ~= "SURF" and typ ~= "MATR" then
return
end
local polys = layer.polys
while r:remaining() >= 4 do
local f = vx(r) + polyBase
local tag = r:u16be()
if r.err then
break
end
local poly = polys[f + 1]
if poly then
poly.surf = tag
end
end
end
-- ------------------------------------------------------------------------------------------------ surfaces
local function newSurface(name: string): Surface
return { name = name, values = {}, color = { 0.78, 0.78, 0.78 }, side = 1, vcol = nil, blocks = {}, source = nil }
end
local SURF_VALUES = { DIFF = true, LUMI = true, SPEC = true, REFL = true, TRAN = true, TRNL = true, GLOS = true, BUMP = true, SMAN = true, RIND = true }
local function readBlock(r: Bytes.Reader, surf: Surface)
-- the header sub-chunk: IMAP / PROC / GRAD / SHDR, ordinal string, header sub-chunks
if r:remaining() < 6 then
return
end
local kind = id4(r)
local hn = r:u16be()
local hend = math.min(r.pos + hn, r.limit)
local blk: Block = { kind = kind, ordinal = "", channel = "COLR", enabled = true, opacity = 1 }
local hr = Bytes.reader(r.buf, r.pos, hend - r.pos)
blk.ordinal = s0(hr)
subchunks(r.buf, hr.pos, hend, function(id: string, sr: Bytes.Reader)
if id == "CHAN" then
blk.channel = id4(sr)
elseif id == "ENAB" then
blk.enabled = sr:u16be() ~= 0
elseif id == "OPAC" then
sr:u16be()
blk.opacity = sr:f32be()
elseif id == "NEGA" then
blk.negative = sr:u16be() ~= 0
elseif id == "AXIS" then
blk.axis = sr:u16be()
end
end)
subchunks(r.buf, hend + (hn % 2), r.limit, function(id: string, sr: Bytes.Reader)
if id == "PROJ" then
blk.projection = sr:u16be()
elseif id == "AXIS" then
blk.axis = sr:u16be()
elseif id == "IMAG" then
blk.clip = vx(sr)
elseif id == "VMAP" then
blk.uvmap = s0(sr)
elseif id == "WRAP" then
blk.wrap = { sr:u16be(), sr:u16be() }
end
end)
table.insert(surf.blocks, blk)
end
local function readSurface(r: Bytes.Reader, surfaces: { Surface })
local name = s0(r)
local source = s0(r)
local surf = newSurface(name)
if source ~= "" then
for _, s in surfaces do
if s.name == source then
surf.values = table.clone(s.values)
surf.color = table.clone(s.color)
surf.side = s.side
surf.vcol = s.vcol
surf.blocks = table.clone(s.blocks)
break
end
end
surf.source = source
end
subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader)
if id == "COLR" then
local c = { sr:f32be(), sr:f32be(), sr:f32be() }
if not sr.err then
surf.color = c
end
elseif SURF_VALUES[id] then
local v = sr:f32be()
if not sr.err then
surf.values[id] = v
end
elseif id == "SIDE" then
surf.side = sr:u16be()
elseif id == "VCOL" then
local intensity = sr:f32be()
vx(sr)
local kind = id4(sr)
local vname = s0(sr)
if not sr.err then
surf.vcol = { name = vname, kind = kind, intensity = intensity }
end
elseif id == "BLOK" then
readBlock(sr, surf)
end
end)
table.insert(surfaces, surf)
end
-- LWOB surfaces: U2 percentages (256 = 100%), V* floats, texture sub-chunks
local B_VALUES = { DIFF = "DIFF", LUMI = "LUMI", SPEC = "SPEC", REFL = "REFL", TRAN = "TRAN" }
local B_FLOATS = { VDIF = "DIFF", VLUM = "LUMI", VSPC = "SPEC", VRFL = "REFL", VTRN = "TRAN" }
local B_TEX = { CTEX = "COLR", DTEX = "DIFF", STEX = "SPEC", RTEX = "REFL", TTEX = "TRAN", LTEX = "LUMI", BTEX = "BUMP" }
local B_PROJ: { [string]: number } = { Planar = 0, Cylindrical = 1, Spherical = 2, Cubic = 3, Front = 4 }
local function readSurfaceB(r: Bytes.Reader, surfaces: { Surface })
local surf = newSurface(s0(r))
local tex: Block? = nil
subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader)
if id == "COLR" then
local c = { sr:u8() / 255, sr:u8() / 255, sr:u8() / 255 }
if not sr.err then
surf.color = c
end
elseif B_VALUES[id] then
local v = sr:u16be()
if not sr.err and surf.values[B_VALUES[id] .. "!"] == nil then
surf.values[B_VALUES[id]] = v / 256
end
elseif B_FLOATS[id] then
local v = sr:f32be()
if not sr.err then
surf.values[B_FLOATS[id]] = v
surf.values[B_FLOATS[id] .. "!"] = 1 -- a float value wins over the U2 one
end
elseif id == "GLOS" then
local v = sr:u16be()
if not sr.err then
-- 16, 64, 256, 1024 = low .. very high: as LWO2's 0..1 glossiness
surf.values.GLOS = math.clamp(math.log(math.max(v, 1), 2) / 10, 0, 1)
end
elseif id == "SMAN" then
surf.values.SMAN = sr:f32be()
elseif id == "FLAG" then
local fl = sr:u16be()
if bit32.band(fl, 0x100) ~= 0 then
surf.side = 3
end
elseif B_TEX[id] then
local desc = sr:cstring()
local proj: number? = nil
for word, v in B_PROJ do
if string.find(desc, word, 1, true) then
proj = v
end
end
local blk: Block = { kind = if string.find(desc, "Image Map", 1, true) then "TEX" else "PROC", ordinal = tostring(#surf.blocks + 1), channel = B_TEX[id], enabled = true, opacity = 1, projection = proj }
table.insert(surf.blocks, blk)
tex = blk
elseif id == "TIMG" and tex then
local path = sr:cstring()
if path ~= "" and path ~= "(none)" then
tex.file = path
end
elseif id == "TFLG" and tex then
local fl = sr:u16be()
tex.axis = if bit32.band(fl, 1) ~= 0 then 0 elseif bit32.band(fl, 2) ~= 0 then 1 else 2
tex.negative = bit32.band(fl, 16) ~= 0
elseif id == "TVAL" and tex then
tex.opacity = sr:u16be() / 256
end
end)
for k in surf.values do
if string.sub(k, -1) == "!" then
surf.values[k] = nil
end
end
table.insert(surfaces, surf)
end
local function readClip(r: Bytes.Reader, clips: { [number]: string }, refs: { [number]: number })
local index = r:u32be()
if r.err then
return
end
subchunks(r.buf, r.pos, r.limit, function(id: string, sr: Bytes.Reader)
if id == "STIL" then
clips[index] = s0(sr)
elseif id == "ISEQ" then
local digits = sr:u8()
sr:u8()
local offset = sr:i16be()
sr:u16be()
local start = sr:i16be()
sr:u16be()
local prefix = s0(sr)
local suffix = s0(sr)
if not sr.err then
clips[index] = prefix .. string.format("%0" .. math.clamp(digits, 1, 9) .. "d", offset + start) .. suffix
end
elseif id == "XREF" then
refs[index] = sr:u32be()
end
end)
end
-- ------------------------------------------------------------------------------------------------ the file
-- parse(buf, from, limit, opts) -> Model | nil, message
function Parse.model(buf: buffer, from: number, limit: number, maxCorners: number): (Model?, string?)
local version = buffer.readstring(buf, from + 8, 4)
local declared = bit32.byteswap(buffer.readu32(buf, from + 4))
local e = math.min(limit, from + 8 + declared)
local model: Model = { version = version, tags = {}, layers = {}, surfaces = {}, clips = {}, skipped = {}, corners = 0 }
local layer = newLayer(0)
layer.implicit = true
table.insert(model.layers, layer)
local ptBase, polyBase = 0, 0
local budget = { maxCorners }
local refs: { [number]: number } = {}
local lwob = version == "LWOB"
local list = Chunks.walk(buf, from + 12, e, Chunks.IFF)
for _, c in list do
local id = c.id
local r = Bytes.reader(buf, c.offset, c.avail)
local err: string? = nil
if id == "TAGS" or id == "SRFS" then
while r:remaining() > 0 do
table.insert(model.tags, s0(r))
end
elseif id == "LAYR" and not lwob then
local index = r:u16be()
r:u16be() -- flags (hidden)
local px, py, pz = r:f32be(), r:f32be(), r:f32be()
local name = s0(r)
local parent: number? = if r:remaining() >= 2 then r:u16be() else nil
if r.err then
return nil, "truncated LAYR chunk"
end
if layer.implicit and #layer.pts == 0 and #layer.polys == 0 then
table.remove(model.layers, #model.layers)
end
layer = newLayer(index)
layer.name = name
layer.parent = if parent == 0xFFFF then nil else parent
layer.pivot = { px, py, pz }
table.insert(model.layers, layer)
ptBase, polyBase = 0, 0
elseif id == "PNTS" then
ptBase = #layer.pts // 3
err = readPoints(r, layer, maxCorners)
elseif id == "POLS" then
polyBase = #layer.polys
if lwob then
err = readPolysB(r, layer, budget)
else
local kind = id4(r)
if kind == "FACE" or kind == "PTCH" or kind == "SUBD" then
err = readPolys(r, layer, kind, ptBase, budget)
else
-- keep the polygon numbering (PTAG / VMAD refer to it) but skip the geometry
local before = #layer.polys
err = readPolys(r, layer, kind, ptBase, budget)
model.skipped[kind] = (model.skipped[kind] or 0) + #layer.polys - before
end
end
elseif id == "VMAP" or id == "VMAD" then
readVmap(r, layer, id == "VMAD", ptBase, polyBase, model.skipped)
elseif id == "PTAG" then
readPtag(r, layer, polyBase)
elseif id == "SURF" then
if lwob then
readSurfaceB(r, model.surfaces)
else
readSurface(r, model.surfaces)
end
elseif id == "CLIP" then
readClip(r, model.clips, refs)
end
if err then
return nil, err
end
end
for index, target in refs do
if model.clips[index] == nil and model.clips[target] then
model.clips[index] = model.clips[target]
end
end
model.corners = maxCorners - budget[1]
return model, nil
end
return Parse
+86
View File
@@ -0,0 +1,86 @@
--!strict
-- model/lwo: LightWave objects: LWO2 (LightWave 6+), LWOB (LightWave 5.x) and Modo's LXOB, read only. New code from
-- the LWO2 / LWOB specifications, checked against assimp's LWO importer and test models.
-- Reads layers (one node each: the pivot as translation, parents by layer index), points and polygons (FACE; PTCH /
-- SUBD subdivision cages kept as polygons and flagged extras.lwo.subdivision; CURV, BONE and metaballs skipped and
-- counted in meta.source.skipped; 1- and 2-point polygons as points / lines primitives), vertex maps (VMAP / VMAD:
-- TXUV -> TEXCOORD_n (one set per map name, flipped to glTF's top-left origin), RGB / RGBA -> COLOR_0 for the map the
-- surface's VCOL names and _COLOR_n for the others, Modo NORM -> NORMAL, WGHT / MNVW weight maps -> _WEIGHT_n (LWO has
-- no skeleton to bind them to), MORF / SPOT -> morph targets; the map names are in prim.extras.lwo.maps), surfaces
-- (one material each: COLR -> baseColor, TRAN -> alpha, GLOS / SPEC -> roughness, LUMI -> emissive, SIDE ->
-- doubleSided, every value and texture block in extras.lwo; the first enabled COLR image block -> baseColorTexture,
-- with its UV map as texCoord) and clips (textures keep the file name as uri and the full path in extras.lwo.path:
-- F.model.loadTextures reads them). LightWave's left-handed space becomes glTF's right-handed y up (z negated, winding
-- reversed), as assimp does. Polygons are fan-triangulated unless opts.triangulate = false.
-- Not supported: LWO3, envelopes, procedural / gradient textures (kept as entries in extras.lwo.maps), planar /
-- cylindrical / spherical projections (no UVs are generated), smoothing (no normals are computed).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Parse = require("@formats/model/lwo/Parse")
local Build = require("@formats/model/lwo/Build")
-- ------------------------------------------------------------------------------------------------ contract
local Lwo = {
name = "lwo",
category = "model",
extensions = { "lwo", "lxo" },
mime = { "image/x-lwo", "model/x-lwo" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Chunks" },
caps = { decode = true, encode = false, materials = true, polygons = true, vertexColors = true, morphTargets = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives
maxVertices: number?, -- refuse more points / polygon corners (default 2^25)
}
-- ------------------------------------------------------------------------------------------------ constants
local VERSIONS = { LWO2 = true, LWOB = true, LXOB = true }
-- ------------------------------------------------------------------------------------------------ sniff
function Lwo.sniff(r: Bytes.Reader): number
if r:peek(4) ~= "FORM" then
return 0
end
local v = r:peek(4, 8)
return if VERSIONS[v] then 1 elseif v == "LWO3" then 0.8 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Lwo.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
if r.limit - r.base < 12 then
return nil, Err.new(Err.TRUNCATED, "shorter than the FORM header", r.base)
end
if r:peek(4) ~= "FORM" then
return nil, Err.new(Err.CORRUPT, "not an IFF FORM", r.base)
end
local v = r:peek(4, 8)
if v == "LWO3" then
return nil, Err.new(Err.UNSUPPORTED, "LWO3 (LightWave 2018+) objects", r.base + 8)
end
if not VERSIONS[v] then
return nil, Err.new(Err.CORRUPT, "not a LightWave object (FORM type " .. string.format("%q", v) .. ")", r.base + 8)
end
local maxCorners = opts and opts.maxVertices or 2 ^ 25
local ok, model, msg = pcall(Parse.model, r.buf, r.base, r.limit, maxCorners)
if not ok then
return nil, Err.new(Err.CORRUPT, "bad chunk data: " .. tostring(model))
end
if not model then
return nil, Err.from(msg)
end
local ok2, scene, msg2 = pcall(Build.scene, model, opts)
if not ok2 then
return nil, Err.new(Err.CORRUPT, "bad object data: " .. tostring(scene))
end
if not scene then
return nil, Err.from(msg2)
end
return scene, nil
end
return Lwo
+464
View File
@@ -0,0 +1,464 @@
--!strict
-- model/ms3d/Read: MilkShape 3D 1.8 (.ms3d, version 3 / 4) -> Types.Scene. The layout from MilkShape's ms3dspec.h
-- (chUmbaLum soft): vertices (position, a bone), triangles (three vertex indices, per-corner normals and uvs, a
-- smoothing group, a group), groups (named triangle lists with a material), materials (Phong colours, shininess
-- 0..128, transparency, texture and alpha map file names), the animation header (fps, current time, frames) and
-- joints (name, parent name, local Euler XYZ rotation in radians and position, rotation / position keys in seconds
-- relative to that rest pose); then the optional sub-versioned blocks: comments (groups, materials, joints, model),
-- vertex extras (three more bones and weights in percent: subversion 1-3, with one or two extra u32s from 2 / 3),
-- joint extras (colours) and model extras (joint size, transparency mode, alpha reference).
-- Mapping: one node + mesh + primitive per group; joints -> nodes in their hierarchy, a skin (inverse bind matrices
-- of the rest pose; JOINTS_0 / WEIGHTS_0 when a vertex has a bone) and one animation (rest * key rotations, rest +
-- key positions). Never throws on bad data: returns nil, message, offset.
local Types = require("@formats/Types")
local Mat4 = require("@formats/codecs/model/Mat4")
local Read = {}
local S = Types.Scene
local readu8, readi8, readu16, readi32, readf32, readstring = buffer.readu8, buffer.readi8, buffer.readu16, buffer.readi32, buffer.readf32, buffer.readstring
local writef32, writeu8, writeu16, writeu32 = buffer.writef32, buffer.writeu8, buffer.writeu16, buffer.writeu32
Read.MAGIC = "MS3D000000"
export type Options = { maxVertices: number? }
-- ------------------------------------------------------------------------------------------------ helpers
local function fixed(b: buffer, p: number, n: number): string
local s = readstring(b, p, n)
local z = string.find(s, "\0", 1, true)
return if z then string.sub(s, 1, z - 1) else s
end
local function floats(values: { number }, comps: number): Types.Accessor
local n = #values // comps
local a = S.accessor(nil, "f32", comps, n)
for i = 1, n * comps do
writef32(a.data, (i - 1) * 4, values[i])
end
return a
end
local function color(b: buffer, p: number): { number }
return { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8), readf32(b, p + 12) }
end
-- the texture file name as a relative uri (MilkShape writes ".\name.jpg")
local function uri(s: string): string
local u = string.gsub(s, "\\", "/")
u = string.gsub(u, "^%./", "")
return u
end
-- the rotation of Euler XYZ radians (R = Rz * Ry * Rx) as a quaternion
local function euler(x: number, y: number, z: number): { number }
return Mat4.quat(Mat4.euler(math.deg(x), math.deg(y), math.deg(z)))
end
-- ------------------------------------------------------------------------------------------------ parse
type Vertex = { pos: { number }, bones: { number }, weights: { number } }
type Joint = {
name: string, parent: string, flags: number, rot: { number }, pos: { number },
rotKeys: { { number } }, posKeys: { { number } }, comment: string?, color: { number }?,
}
-- scene(b, base, limit, opts) -> Scene | nil, message, offset
function Read.scene(b: buffer, base: number, limit: number, opts: Options?): (Types.Scene?, string?, number?)
local p = base
local function need(n: number): boolean
return p + n <= limit
end
if not need(14) or readstring(b, p, 10) ~= Read.MAGIC then
return nil, "not a MilkShape 3D file", base
end
local version = readi32(b, p + 10)
if version ~= 3 and version ~= 4 then
return nil, "unsupported: version " .. version, p + 10
end
p += 14
local maxV = opts and opts.maxVertices or 2 ^ 20
-- vertices
if not need(2) then
return nil, "truncated vertex count", p
end
local nv = readu16(b, p)
p += 2
if not need(nv * 15) then
return nil, "truncated vertices", p
end
local verts: { Vertex } = {}
for i = 1, nv do
local q = p + (i - 1) * 15
verts[i] = { pos = { readf32(b, q + 1), readf32(b, q + 5), readf32(b, q + 9) }, bones = { readi8(b, q + 13), -1, -1, -1 }, weights = { 1, 0, 0, 0 } }
end
p += nv * 15
-- triangles
if not need(2) then
return nil, "truncated triangle count", p
end
local nt = readu16(b, p)
p += 2
if not need(nt * 70) then
return nil, "truncated triangles", p
end
if nt * 3 > maxV then
return nil, "limit: more than " .. maxV .. " triangle corners", p
end
local triAt = p
p += nt * 70
-- groups
if not need(2) then
return nil, "truncated group count", p
end
local ng = readu16(b, p)
p += 2
local groups = {}
for _ = 1, ng do
if not need(35) then
return nil, "truncated group", p
end
local g = { flags = readu8(b, p), name = fixed(b, p + 1, 32), tris = {} :: { number }, material = -1, comment = nil :: string? }
local n = readu16(b, p + 33)
p += 35
if not need(n * 2 + 1) then
return nil, "truncated group triangles", p
end
for k = 0, n - 1 do
local ti = readu16(b, p + k * 2)
if ti >= nt then
return nil, "group triangle " .. ti .. " out of range", p + k * 2
end
table.insert(g.tris, ti)
end
p += n * 2
g.material = readi8(b, p)
p += 1
table.insert(groups, g)
end
-- materials
if not need(2) then
return nil, "truncated material count", p
end
local nm = readu16(b, p)
p += 2
if not need(nm * 361) then
return nil, "truncated materials", p
end
local mats = {}
for i = 0, nm - 1 do
local q = p + i * 361
table.insert(mats, {
name = fixed(b, q, 32), ambient = color(b, q + 32), diffuse = color(b, q + 48), specular = color(b, q + 64),
emissive = color(b, q + 80), shininess = readf32(b, q + 96), transparency = readf32(b, q + 100),
mode = readi8(b, q + 104), texture = fixed(b, q + 105, 128), alphamap = fixed(b, q + 233, 128), comment = nil :: string?,
})
end
p += nm * 361
-- animation header and joints (version 3 files may end here)
local fps, current, frames = 24, 0, 0
local joints: { Joint } = {}
if need(12) then
fps, current, frames = readf32(b, p), readf32(b, p + 4), readi32(b, p + 8)
p += 12
if not need(2) then
return nil, "truncated joint count", p
end
local nj = readu16(b, p)
p += 2
for _ = 1, nj do
if not need(93) then
return nil, "truncated joint", p
end
local j: Joint = {
flags = readu8(b, p), name = fixed(b, p + 1, 32), parent = fixed(b, p + 33, 32),
rot = { readf32(b, p + 65), readf32(b, p + 69), readf32(b, p + 73) },
pos = { readf32(b, p + 77), readf32(b, p + 81), readf32(b, p + 85) },
rotKeys = {}, posKeys = {},
}
local nr, np = readu16(b, p + 89), readu16(b, p + 91)
p += 93
if not need((nr + np) * 16) then
return nil, "truncated joint keys", p
end
for k = 0, nr + np - 1 do
local q = p + k * 16
local key = { readf32(b, q), readf32(b, q + 4), readf32(b, q + 8), readf32(b, q + 12) }
table.insert(if k < nr then j.rotKeys else j.posKeys, key)
end
p += (nr + np) * 16
table.insert(joints, j)
end
end
-- sub-versioned blocks
local source: { [string]: any } = { format = "ms3d", version = version, fps = fps, currentTime = current, frames = frames }
local function comments(list: { any }): string?
if not need(4) then
return "truncated comments"
end
local n = readi32(b, p)
p += 4
for _ = 1, math.max(n, 0) do
if not need(8) then
return "truncated comment"
end
local index, len = readi32(b, p), readi32(b, p + 4)
p += 8
if len < 0 or not need(len) then
return "comment runs past the end"
end
if list[index + 1] then
list[index + 1].comment = readstring(b, p, len)
end
p += len
end
return nil
end
if need(4) then
local sub = readi32(b, p)
p += 4
source.commentVersion = sub
if sub == 1 then
for _, list in { groups, mats, joints } :: { { any } } do
local e = comments(list)
if e then
return nil, e, p
end
end
if not need(4) then
return nil, "truncated model comment", p
end
local has = readi32(b, p)
p += 4
if has ~= 0 then
if not need(4) then
return nil, "truncated model comment", p
end
local len = readi32(b, p)
p += 4
if len < 0 or not need(len) then
return nil, "model comment runs past the end", p
end
source.comment = readstring(b, p, len)
p += len
end
end
end
if need(4) then
local sub = readi32(b, p)
p += 4
source.vertexVersion = sub
local size = if sub == 1 then 6 elseif sub == 2 then 10 elseif sub == 3 then 14 else 0
if size > 0 and need(nv * size) then
for i = 1, nv do
local q = p + (i - 1) * size
local v = verts[i]
local w0, w1, w2 = readu8(b, q + 3), readu8(b, q + 4), readu8(b, q + 5)
if w0 + w1 + w2 > 0 then
local scale = if w0 > 100 or w1 > 100 or w2 > 100 or w0 + w1 + w2 > 100 then 255 else 100
v.bones = { v.bones[1], readi8(b, q), readi8(b, q + 1), readi8(b, q + 2) }
v.weights = { w0 / scale, w1 / scale, w2 / scale, math.max(0, 1 - (w0 + w1 + w2) / scale) }
end
end
p += nv * size
end
end
if need(4) then
local sub = readi32(b, p)
p += 4
if (sub == 1 or sub == 2) and need(#joints * 12) then
for _, j in joints do
j.color = { readf32(b, p), readf32(b, p + 4), readf32(b, p + 8) }
p += 12
end
end
end
if need(16) and readi32(b, p) >= 1 then
source.jointSize, source.transparencyMode, source.alphaRef = readf32(b, p + 4), readi32(b, p + 8), readf32(b, p + 12)
end
return Read.build(b, triAt, verts, groups, mats, joints, source), nil, nil
end
-- ------------------------------------------------------------------------------------------------ build
function Read.build(b: buffer, triAt: number, verts: { Vertex }, groups: { any }, mats: { any }, joints: { Joint }, source: { [string]: any }): Types.Scene
local scene = S.new()
scene.meta.up = "y"
scene.meta.source = source :: any
-- materials, textures
for _, m in mats do
local mat = S.material(m.name)
local d = m.diffuse
mat.baseColor = { d[1], d[2], d[3], math.clamp(m.transparency, 0, 1) }
mat.metallic = 0
mat.roughness = math.clamp(math.sqrt(2 / (math.clamp(m.shininess, 0, 128) + 2)), 0, 1)
mat.emissive = { m.emissive[1], m.emissive[2], m.emissive[3] }
mat.alphaMode = if m.transparency < 1 then "blend" else "opaque"
if m.texture ~= "" then
local tex: Types.Texture = { name = m.texture, uri = uri(m.texture) }
table.insert(scene.textures, tex)
mat.baseColorTexture = { texture = #scene.textures }
end
mat.extras = {
ms3d = {
ambient = m.ambient, diffuse = m.diffuse, specular = m.specular, emissive = m.emissive, shininess = m.shininess,
transparency = m.transparency, mode = m.mode, texture = m.texture, alphamap = m.alphamap, comment = m.comment,
},
}
table.insert(scene.materials, mat)
end
-- joints: nodes, rest pose, skin
local nj = #joints
local jointNode: { [number]: number } = {}
local byName: { [string]: number } = {}
local abs: { { number } } = {}
for i, j in joints do
local node: Types.Node = { name = j.name, children = {}, translation = j.pos, rotation = euler(j.rot[1], j.rot[2], j.rot[3]) }
node.extras = { ms3d = { flags = j.flags, comment = j.comment, color = j.color } }
table.insert(scene.nodes, node)
jointNode[i] = #scene.nodes
if byName[j.name] == nil then
byName[j.name] = i
end
end
for i, j in joints do
local pi = byName[j.parent]
-- parents must come first (MilkShape writes them in that order); others become roots
local local_ = S.nodeMatrix(scene.nodes[jointNode[i]])
if pi and pi < i then
table.insert(scene.nodes[jointNode[pi]].children, jointNode[i])
abs[i] = S.mul(abs[pi], local_)
else
table.insert(scene.roots, jointNode[i])
abs[i] = local_
end
end
local skinned = false
for _, v in verts do
for k = 1, 4 do
if v.bones[k] >= nj then
v.bones[k] = -1
end
end
skinned = skinned or (nj > 0 and v.bones[1] >= 0)
end
if nj > 0 then
local ibm = S.accessor(nil, "f32", 16, nj)
ibm.matrix = true
for i = 1, nj do
local inv = Mat4.inverse(abs[i]) or Mat4.identity()
for k = 1, 16 do
writef32(ibm.data, ((i - 1) * 16 + k - 1) * 4, inv[k])
end
end
local list = table.create(nj, 0)
for i = 1, nj do
list[i] = jointNode[i]
end
scene.skins[1] = { joints = list, inverseBindMatrices = ibm }
end
-- groups: one node + mesh each; vertices unwelded per (vertex, normal, uv) corner
local nv = #verts
for gi, g in groups do
local remap: { [string]: number } = {}
local P, N, U, J, W = {}, {}, {}, {}, {}
local idx: { number } = {}
local sgs: { number } = {}
local count = 0
for _, ti in g.tris do
local q = triAt + ti * 70
-- a triangle with an out-of-range vertex is dropped
if readu16(b, q + 2) >= nv or readu16(b, q + 4) >= nv or readu16(b, q + 6) >= nv then
continue
end
table.insert(sgs, readu8(b, q + 68))
for k = 0, 2 do
local vi = readu16(b, q + 2 + k * 2)
local key = vi .. readstring(b, q + 8 + k * 12, 12) .. readstring(b, q + 44 + k * 4, 4) .. readstring(b, q + 56 + k * 4, 4)
local o = remap[key]
if o == nil then
o = count
count += 1
remap[key] = o
local v = verts[vi + 1]
table.move(v.pos, 1, 3, o * 3 + 1, P)
N[o * 3 + 1], N[o * 3 + 2], N[o * 3 + 3] = readf32(b, q + 8 + k * 12), readf32(b, q + 12 + k * 12), readf32(b, q + 16 + k * 12)
U[o * 2 + 1], U[o * 2 + 2] = readf32(b, q + 44 + k * 4), readf32(b, q + 56 + k * 4)
-- influences: the valid bones, weights normalized
local sum = 0
for c = 1, 4 do
if v.bones[c] >= 0 then
sum += v.weights[c]
end
end
for c = 1, 4 do
local ok = v.bones[c] >= 0 and sum > 0
J[o * 4 + c] = if ok then v.bones[c] else 0
W[o * 4 + c] = if ok then v.weights[c] / sum else 0
end
end
table.insert(idx, o :: number)
end
end
local prim: Types.Primitive = {
attributes = { POSITION = floats(P, 3), NORMAL = floats(N, 3), TEXCOORD_0 = floats(U, 2) },
mode = "triangles",
material = if g.material >= 0 and g.material < #mats then g.material + 1 else nil,
extras = { ms3d = { smoothing = sgs } },
}
local ind = S.accessor(nil, "u32", 1, #idx)
for i, v in idx do
writeu32(ind.data, (i - 1) * 4, v)
end
prim.indices = ind
local node: Types.Node = { name = g.name, children = {}, extras = { ms3d = { flags = g.flags, comment = g.comment } } }
if skinned then
local ja = S.accessor(nil, if nj > 255 then "u16" else "u8", 4, count)
for i = 1, count * 4 do
if nj > 255 then
writeu16(ja.data, (i - 1) * 2, J[i])
else
writeu8(ja.data, i - 1, J[i])
end
end
prim.attributes.JOINTS_0 = ja
prim.attributes.WEIGHTS_0 = floats(W, 4)
node.skin = 1
end
local mesh: Types.Mesh = { name = g.name :: string, primitives = { prim } }
scene.meshes[gi] = mesh
node.mesh = gi
table.insert(scene.nodes, node)
table.insert(scene.roots, #scene.nodes)
end
-- the animation: rest * key rotations, rest + key positions
local channels: { Types.Channel } = {}
for i, j in joints do
if #j.rotKeys > 0 then
local times, vals = {}, {}
local rest = scene.nodes[jointNode[i]].rotation :: { number }
for _, k in j.rotKeys do
table.insert(times, k[1])
local q = Mat4.quat(Mat4.mul(Mat4.fromQuat(rest), Mat4.fromQuat(euler(k[2], k[3], k[4]))))
table.move(q, 1, 4, #vals + 1, vals)
end
local ch: Types.Channel = { node = jointNode[i], path = "rotation", input = floats(times, 1), output = floats(vals, 4), interpolation = "LINEAR" }
table.insert(channels, ch)
end
if #j.posKeys > 0 then
local times, vals = {}, {}
for _, k in j.posKeys do
table.insert(times, k[1])
table.insert(vals, j.pos[1] + k[2])
table.insert(vals, j.pos[2] + k[3])
table.insert(vals, j.pos[3] + k[4])
end
local ch: Types.Channel = { node = jointNode[i], path = "translation", input = floats(times, 1), output = floats(vals, 3), interpolation = "LINEAR" }
table.insert(channels, ch)
end
end
if #channels > 0 then
table.insert(scene.animations, { name = "ms3d", channels = channels })
end
return scene
end
return Read
+486
View File
@@ -0,0 +1,486 @@
--!strict
-- model/ms3d/Write: Types.Scene -> MilkShape 3D (version 4). One group per placed primitive (points / lines skipped,
-- polygons triangulated); vertices in world space, or in the skin's bind space for primitives skinned by the first
-- skin (JOINTS_0 / WEIGHTS_0 -> a bone and up to three more with weights in percent: vertex extras subversion 2);
-- meshes under a joint of that skin are bound rigidly to it. Joints: the first skin's joints in tree order, each
-- parented to its nearest joint ancestor, the rest pose from the inverse bind matrices; the first animation's
-- rotation / translation keys on them become keys relative to that rest pose (scale is not MilkShape's). Materials:
-- extras.ms3d when present, else from the PBR fields; texture file names from texture.uri (a texture with data and
-- no uri is named after opts.name and put into opts.files). Comments (extras.ms3d.comment, meta.source.comment),
-- joint colours and model extras are written in their sub-versioned blocks.
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Mat4 = require("@formats/codecs/model/Mat4")
local Flatten = require("@formats/codecs/model/MeshFlatten")
local Write = {}
local S = Types.Scene
local sqrt = math.sqrt
export type Options = { fps: number?, name: string?, files: { [string]: any }? }
local function fixedString(w: Bytes.Writer, s: string, n: number)
local v = string.sub(string.gsub(s, "%z", ""), 1, n - 1)
w:string(v)
for _ = #v + 1, n do
w:u8(0)
end
end
local function msg(s: any): string
return if type(s) == "string" then s else ""
end
-- ------------------------------------------------------------------------------------------------ tree
type Tree = { world: { [number]: { number } }, parent: { [number]: number }, order: { number } }
local function tree(scene: Types.Scene): Tree
local t: Tree = { world = {}, parent = {}, order = {} }
local function visit(i: number, p: number, pm: { number }, depth: number)
local n = scene.nodes[i]
if type(n) ~= "table" or t.world[i] or depth > 256 then
return
end
t.world[i] = S.mul(pm, S.nodeMatrix(n))
t.parent[i] = p
table.insert(t.order, i)
for _, c in n.children or {} do
visit(c, i, t.world[i], depth + 1)
end
end
for _, r in scene.roots do
visit(r, 0, S.IDENTITY, 0)
end
return t
end
-- ------------------------------------------------------------------------------------------------ joints
type Joint = { node: number, name: string, parent: string, pos: { number }, rot: { number }, quat: { number }, rotKeys: { { number } }, posKeys: { { number } } }
-- the rigid part (rotation and translation) of a matrix
local function rigid(m: { number }): { number }
local t, r = Mat4.decompose(m)
return Mat4.compose(t, r, nil)
end
-- the first skin's joints and every node the first animation moves (rigid meshes below them follow), in tree order;
-- skin joint index -> joint, node -> joint (0-based); the bind transform of the skinned vertices
local function joints(scene: Types.Scene, tr: Tree): ({ Joint }, { [number]: number }, { [number]: number }, { number })
local skin = scene.skins[1]
local anim = scene.animations[1]
local out: { Joint } = {}
local bySkin: { [number]: number } = {}
local byNode: { [number]: number } = {}
local skinIndex: { [number]: number } = {}
local isJoint: { [number]: boolean } = {}
for k, ni in (if skin then skin.joints else {}) :: { number } do
skinIndex[ni] = k - 1
isJoint[ni] = true
end
local chans: { [number]: { Types.Channel } } = {}
for _, ch in (if anim then anim.channels else {}) :: { Types.Channel } do
if (ch.path == "rotation" or ch.path == "translation") and tr.world[ch.node] then
isJoint[ch.node] = true
chans[ch.node] = chans[ch.node] or {}
table.insert(chans[ch.node], ch)
end
end
-- skinned vertices go to the space where the first joint's rest world undoes its inverse bind matrix
local B = S.IDENTITY
local IBM: any = if skin and skin.inverseBindMatrices then S.reader(skin.inverseBindMatrices) else nil
if skin and IBM and tr.world[skin.joints[1]] then
local m = table.create(16, 0)
for c = 1, 16 do
m[c] = (IBM :: any)(0, c - 1)
end
B = S.mul(tr.world[skin.joints[1]], m)
end
local names: { [string]: boolean } = {}
for _, ni in tr.order do
if not isJoint[ni] or #out >= 127 then
continue
end
local p = tr.parent[ni]
while p ~= 0 and byNode[p] == nil do
p = tr.parent[p]
end
-- MilkShape joints are rigid: rest = (parent's rigid world)^-1 * rigid world; the static nodes between the
-- joint and its joint parent (C) carry over to the keys
local invP = if p ~= 0 then Mat4.inverse(rigid(tr.world[p])) or Mat4.identity() else Mat4.identity()
local gp = tr.parent[ni]
local C = S.mul(invP, if gp ~= 0 then tr.world[gp] else S.IDENTITY)
local t, r = Mat4.decompose(S.mul(invP, rigid(tr.world[ni])))
local e = Mat4.eulerXYZ(r)
local base = string.sub(msg(scene.nodes[ni].name), 1, 27)
local name = if base ~= "" then base else "joint" .. #out
local n = 1
while names[name] do
n += 1
name = base .. "_" .. n
end
names[name] = true
local j: Joint = {
node = ni, name = name, parent = if p ~= 0 then out[byNode[p] + 1].name else "", pos = t,
rot = { math.rad(e[1]), math.rad(e[2]), math.rad(e[3]) }, quat = r, rotKeys = {}, posKeys = {},
}
table.insert(out, j)
byNode[ni] = #out - 1
if skinIndex[ni] then
bySkin[skinIndex[ni]] = #out - 1
end
-- keys relative to the rest pose: rotation rest^-1 * C * R(t), position C * T(t) - rest
local _, rc = Mat4.decompose(C)
local inv = Mat4.transpose3(Mat4.fromQuat(r))
for _, ch in chans[ni] or {} do
local IN, OUT = S.reader(ch.input) :: any, S.reader(ch.output) :: any
local cubic = ch.interpolation == "CUBICSPLINE"
for k = 0, ch.input.count - 1 do
local v = if cubic then k * 3 + 1 else k
local time = IN(k, 0)
if ch.path == "rotation" then
local q = { OUT(v, 0), OUT(v, 1), OUT(v, 2), OUT(v, 3) }
local l = sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4])
q = if l > 0 then { q[1] / l, q[2] / l, q[3] / l, q[4] / l } else { 0, 0, 0, 1 }
local d = Mat4.eulerXYZ(Mat4.quat(S.mul(inv, S.mul(Mat4.fromQuat(rc), Mat4.fromQuat(q)))))
table.insert(j.rotKeys, { time, math.rad(d[1]), math.rad(d[2]), math.rad(d[3]) })
else
local x, y, z = Mat4.point(C, OUT(v, 0), OUT(v, 1), OUT(v, 2))
table.insert(j.posKeys, { time, x - t[1], y - t[2], z - t[3] })
end
end
end
end
return out, bySkin, byNode, B
end
-- ------------------------------------------------------------------------------------------------ geometry
type Vertex = { x: number, y: number, z: number, bones: { number }, weights: { number } }
type Tri = { v: { number }, n: { number }, uv: { number }, sg: number, group: number }
type Group = { name: string, tris: { number }, material: number, flags: number, comment: string? }
-- every placed primitive as a group: vertices, triangles; or nil, message
local function geometry(scene: Types.Scene, tr: Tree, bySkin: { [number]: number }, byNode: { [number]: number }, B: { number }): ({ Vertex }, { Tri }, { Group }, string?)
local verts: { Vertex }, tris: { Tri }, groups: { Group } = {}, {}, {}
for _, pl in S.flatten(scene) do
local prim: any = pl.primitive
local node = scene.nodes[pl.node]
local merged, err = Flatten.merge({ kind = "scene", nodes = {}, roots = {}, meshes = { { primitives = { prim } } } }, function(): boolean
return false
end, { triangulate = true })
if not merged then
return verts, tris, groups, err
end
local corners = merged.corners
if #corners == 0 then
continue
end
local skinned = node.skin == 1 and prim.attributes.JOINTS_0 ~= nil and prim.attributes.WEIGHTS_0 ~= nil
-- a rigid mesh follows its nearest joint
local rigid = -1
if not skinned then
local p = pl.node
while p and p ~= 0 do
if byNode[p] then
rigid = byNode[p]
break
end
p = tr.parent[p]
end
end
local M = if skinned then B else pl.matrix
local NM = Mat4.normalMatrix(M)
local mirror = M[1] * (M[6] * M[11] - M[7] * M[10]) - M[5] * (M[2] * M[11] - M[3] * M[10]) + M[9] * (M[2] * M[7] - M[3] * M[6]) < 0
local A = prim.attributes
local POS = S.reader(A.POSITION) :: any
local zero = function(_: number, _: number): number
return 0
end
type Get = (number, number) -> number
local hasN, hasUV = A.NORMAL ~= nil, A.TEXCOORD_0 ~= nil
local NOR: Get = (if hasN then S.reader(A.NORMAL) else nil) or zero
local UV: Get = (if hasUV then S.reader(A.TEXCOORD_0) else nil) or zero
local JO: Get = (if skinned then S.reader(A.JOINTS_0) else nil) or zero
local WE: Get = (if skinned then S.reader(A.WEIGHTS_0) else nil) or zero
local base = #verts
local nv = A.POSITION.count
if base + nv > 65535 then
return verts, tris, groups, "more than 65535 vertices"
end
for v = 0, nv - 1 do
local x, y, z = Mat4.point(M, POS(v, 0), POS(v, 1), POS(v, 2))
local bones, weights = { rigid, -1, -1, -1 }, { 1, 0, 0, 0 }
if skinned then
local inf = {}
for c = 0, 3 do
local w = WE(v, c)
local j = bySkin[JO(v, c)]
if w > 0 and j then
table.insert(inf, { j, w })
end
end
table.sort(inf, function(a: { number }, b: { number }): boolean
return a[2] > b[2]
end)
local sum = 0
for _, e in inf do
sum += e[2]
end
for c = 1, 4 do
local e = inf[c]
bones[c] = if e then e[1] else -1
weights[c] = if e and sum > 0 then e[2] / sum else 0
end
end
table.insert(verts, { x = x, y = y, z = z, bones = bones, weights = weights })
end
local gi = #groups
if gi >= 255 then
return verts, tris, groups, "more than 255 groups"
end
local name = msg(node.name)
if name == "" then
name = msg(scene.meshes[pl.mesh] and scene.meshes[pl.mesh].name)
end
local x = node.extras and node.extras.ms3d
local g: Group = {
name = if name ~= "" then name else "group" .. gi, tris = {}, flags = if x and type(x.flags) == "number" then x.flags else 0,
material = if type(prim.material) == "number" and prim.material <= 127 then prim.material - 1 else -1,
comment = x and x.comment,
}
local saved = prim.extras and prim.extras.ms3d and prim.extras.ms3d.smoothing
if type(saved) ~= "table" or #saved ~= #corners // 3 then
saved = nil
end
for f = 0, #corners // 3 - 1 do
local a, b, c = corners[f * 3 + 1], corners[f * 3 + 2], corners[f * 3 + 3]
if mirror then
b, c = c, b
end
local t: Tri = { v = { base + a, base + b, base + c }, n = {}, uv = {}, sg = if saved then saved[f + 1] else 1, group = gi }
-- the face normal for primitives without normals
local va, vb, vc = verts[base + a + 1], verts[base + b + 1], verts[base + c + 1]
local e1x, e1y, e1z = vb.x - va.x, vb.y - va.y, vb.z - va.z
local e2x, e2y, e2z = vc.x - va.x, vc.y - va.y, vc.z - va.z
local fx, fy, fz = e1y * e2z - e1z * e2y, e1z * e2x - e1x * e2z, e1x * e2y - e1y * e2x
for _, v in { a, b, c } do
local nx, ny, nz = fx, fy, fz
if hasN then
local ox, oy, oz = NOR(v, 0), NOR(v, 1), NOR(v, 2)
nx = NM[1] * ox + NM[5] * oy + NM[9] * oz
ny = NM[2] * ox + NM[6] * oy + NM[10] * oz
nz = NM[3] * ox + NM[7] * oy + NM[11] * oz
end
local l = sqrt(nx * nx + ny * ny + nz * nz)
if l > 0 then
nx, ny, nz = nx / l, ny / l, nz / l
end
table.move({ nx, ny, nz }, 1, 3, #t.n + 1, t.n)
table.insert(t.uv, UV(v, 0))
table.insert(t.uv, UV(v, 1))
end
table.insert(tris, t)
table.insert(g.tris, #tris - 1)
end
if #tris > 65535 then
return verts, tris, groups, "more than 65535 triangles"
end
table.insert(groups, g)
end
return verts, tris, groups, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Write.encode(scene: Types.Scene, opts: Options?): (buffer?, string?)
local o: Options = opts or {}
local tr = tree(scene)
local js, bySkin, byNode, B = joints(scene, tr)
local verts, tris, groups, gerr = geometry(scene, tr, bySkin, byNode, B)
if gerr then
return nil, gerr
end
if #scene.materials > 127 then
return nil, "more than 127 materials"
end
local src: any = scene.meta.source
local fromMs3d = src ~= nil and src.format == "ms3d"
local w = Bytes.writer(65536)
w:string("MS3D000000")
w:u32le(4)
w:u16le(#verts)
for _, v in verts do
w:u8(0)
w:f32le(v.x)
w:f32le(v.y)
w:f32le(v.z)
w:i8(v.bones[1] % 256)
w:u8(1)
end
w:u16le(#tris)
for _, t in tris do
w:u16le(0)
for k = 1, 3 do
w:u16le(t.v[k])
end
for k = 1, 9 do
w:f32le(t.n[k])
end
for k = 1, 3 do
w:f32le(t.uv[k * 2 - 1])
end
for k = 1, 3 do
w:f32le(t.uv[k * 2])
end
w:u8(math.clamp(t.sg, 0, 255))
w:u8(t.group)
end
w:u16le(#groups)
for _, g in groups do
w:u8(g.flags % 256)
fixedString(w, g.name, 32)
w:u16le(#g.tris)
for _, ti in g.tris do
w:u16le(ti)
end
w:i8(g.material % 256)
end
-- materials
w:u16le(#scene.materials)
local base = string.match(o.name or "", "([^/\\]-)%.[^.]*$") or "texture"
for i, m in scene.materials do
local x = (m.extras and m.extras.ms3d or {}) :: { [string]: any }
local bc = m.baseColor or { 1, 1, 1, 1 }
fixedString(w, msg(m.name) ~= "" and msg(m.name) or ("material" .. i), 32)
local e = m.emissive or { 0, 0, 0 }
for _, c in { x.ambient or { 0.2, 0.2, 0.2, 1 }, { bc[1], bc[2], bc[3], bc[4] or 1 }, x.specular or { 0, 0, 0, 1 }, { e[1], e[2], e[3], 1 } } do
for k = 1, 4 do
w:f32le(c[k] or 1)
end
end
local r = math.max(m.roughness or 1, 0.1)
w:f32le(x.shininess or math.clamp(2 / (r * r) - 2, 0, 128))
w:f32le(bc[4] or 1)
w:i8((tonumber(x.mode) or 0) % 256)
local file = ""
local ref: any = m.baseColorTexture
local tex: any = ref and scene.textures[ref.texture]
if tex then
file = tex.uri or ""
if file == "" or string.sub(file, 1, 5) == "data:" then
file = base .. "_" .. ref.texture .. ".png"
if o.files and tex.data then
o.files[file] = tex.data
end
end
end
fixedString(w, file, 128)
fixedString(w, msg(x.alphamap), 128)
end
-- the animation header and joints
local fps = o.fps or (if fromMs3d and type(src.fps) == "number" and src.fps > 0 then src.fps else 24)
local last = 0
for _, j in js do
for _, k in j.rotKeys do
last = math.max(last, k[1])
end
for _, k in j.posKeys do
last = math.max(last, k[1])
end
end
w:f32le(fps)
w:f32le(0)
w:u32le(math.max(1, math.ceil(last * fps)))
w:u16le(#js)
for _, j in js do
local x = scene.nodes[j.node].extras
local jx = x and x.ms3d
w:u8(if jx and type(jx.flags) == "number" then jx.flags % 256 else 0)
fixedString(w, j.name, 32)
fixedString(w, j.parent, 32)
for k = 1, 3 do
w:f32le(j.rot[k])
end
for k = 1, 3 do
w:f32le(j.pos[k])
end
w:u16le(#j.rotKeys)
w:u16le(#j.posKeys)
for _, list in { j.rotKeys, j.posKeys } do
for _, k in list do
for c = 1, 4 do
w:f32le(k[c])
end
end
end
end
-- comments
w:u32le(1)
local function comments(list: { any }, get: (any) -> string?)
local found = {}
for i, item in list do
local c = get(item)
if type(c) == "string" and c ~= "" then
table.insert(found, { i - 1, c })
end
end
w:u32le(#found)
for _, f in found do
w:u32le(f[1])
w:u32le(#f[2])
w:string(f[2])
end
end
comments(groups, function(g: any): string?
return g.comment
end)
comments(scene.materials, function(m: any): string?
return m.extras and m.extras.ms3d and m.extras.ms3d.comment
end)
comments(js, function(j: any): string?
local x: any = scene.nodes[j.node].extras
return x and x.ms3d and x.ms3d.comment
end)
local mc = if fromMs3d then msg(src.comment) else ""
w:u32le(if mc ~= "" then 1 else 0)
if mc ~= "" then
w:u32le(#mc)
w:string(mc)
end
-- vertex extras: three more bones, the weights in percent (the last one implied), an extra u32
w:u32le(2)
for _, v in verts do
local p = table.create(3, 0)
local left = 100
for c = 1, 3 do
p[c] = math.clamp(math.floor(v.weights[c] * 100 + 0.5), 0, left)
left -= p[c]
end
if v.bones[2] < 0 and v.bones[1] >= 0 then
p = { 100, 0, 0 }
end
for c = 2, 4 do
w:i8(v.bones[c] % 256)
end
for c = 1, 3 do
w:u8(p[c])
end
w:u32le(0)
end
-- joint colours, model extras
w:u32le(1)
for _, j in js do
local x: any = scene.nodes[j.node].extras
local c = x and x.ms3d and x.ms3d.color or { 1, 1, 1 }
for k = 1, 3 do
w:f32le(c[k] or 1)
end
end
w:u32le(1)
w:f32le(if fromMs3d and type(src.jointSize) == "number" then src.jointSize else 1)
w:u32le(if fromMs3d and type(src.transparencyMode) == "number" then src.transparencyMode else 0)
w:f32le(if fromMs3d and type(src.alphaRef) == "number" then src.alphaRef else 0.5)
local out = buffer.create(w.pos)
buffer.copy(out, 0, w.buf, 0, w.pos)
return out, nil
end
return Write
+82
View File
@@ -0,0 +1,82 @@
--!strict
-- model/ms3d: MilkShape 3D (.ms3d, versions 3 and 4, with the comment / vertex / joint / model extra blocks of
-- MilkShape 1.8). New code from MilkShape's ms3dspec.h; assimp's MS3D importer (BSD-3) is the reference it is tested
-- against (no code ported).
-- Reads (model/ms3d/Read): groups -> one node, mesh and primitive each (POSITION, the per-corner NORMAL and
-- TEXCOORD_0: MilkShape's uv origin is already glTF's top left; vertices unwelded per corner; smoothing groups in
-- extras.ms3d.smoothing), materials (diffuse -> baseColor with transparency as alpha, shininess -> roughness, emissive;
-- ambient / specular / mode / alpha map in extras.ms3d; the texture file -> a Texture with `uri`, not loaded: use
-- F.model.loadTextures), joints -> nodes (hierarchy by parent name, Euler XYZ rest rotations), one skin (inverse
-- bind matrices of the rest pose, JOINTS_0 / WEIGHTS_0 from the vertex bone and the extra bones / weights), keyframes
-- -> one animation (rotation and translation channels, times in seconds), comments and joint colours in extras.ms3d,
-- the model comment / fps / frames / joint size in meta.source. meta.up = "y".
-- Writes (model/ms3d/Write): version 4 with subversion 1 comments, subversion 2 vertex extras (four bones per vertex),
-- joint colours and model extras. Limits of the format (Err.ARG): 65535 vertices / triangles, 255 groups, 127
-- materials, 127 joints. Not supported: scale keys (MilkShape has none), more than one skin (the first one is written).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Read = require("@formats/model/ms3d/Read")
local Write = require("@formats/model/ms3d/Write")
-- ------------------------------------------------------------------------------------------------ contract
local Ms3d = {
name = "ms3d",
category = "model",
extensions = { "ms3d" },
mime = { "application/x-ms3d" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Mat4", "codecs/model/MeshFlatten" },
caps = { decode = true, encode = true, materials = true, skins = true, animation = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxVertices: number?, -- refuse more triangle corners (default 2^20)
}
export type EncodeOptions = {
fps: number?, -- the animation's frames per second (default: the source's, else 24)
name: string?, -- the destination's file name (names textures that have no uri)
files: { [string]: any }?, -- receives the bytes of textures that have data but no uri
}
-- ------------------------------------------------------------------------------------------------ sniff
function Ms3d.sniff(r: Bytes.Reader): number
local h = r:peek(14)
if string.sub(h, 1, 10) ~= Read.MAGIC then
return 0
end
local v = string.byte(h, 11)
return if v == 3 or v == 4 then 1 else 0.6
end
-- ------------------------------------------------------------------------------------------------ decode
function Ms3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
-- the scene builder is plain (not native) code: a bug there must not escape as an error
local ok, scene, msg, at = pcall(Read.scene, r.buf, r.base, r.limit, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(scene))
end
if not scene then
return nil, Err.from(msg, at)
end
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Ms3d.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(scene) ~= "table" or scene.kind ~= "scene" then
return nil, Err.new(Err.ARG, "needs a Scene")
end
local ok, out, err = pcall(Write.encode, scene, opts)
if not ok then
return nil, Err.new(Err.ARG, "bad scene: " .. tostring(out))
end
if not out then
return nil, Err.new(Err.ARG, tostring(err))
end
return out, nil
end
return Ms3d
+307
View File
@@ -0,0 +1,307 @@
--!strict
-- model/pmx/Build: the parsed PMX / PMD model (model/pmx/Read, model/pmx/Pmd) to a Scene. MMD is left-handed (y up,
-- x right, z forward), so positions / normals / bone positions get z negated and every triangle its winding reversed
-- (glTF's right-handed, counter-clockwise front faces); UVs are already top-left. One primitive per material, with
-- the material's vertices only (JOINTS_0 / WEIGHTS_0, the additional UVs as _UVA1.._UVA4 vec4, SDEF C / R0 / R1 as
-- _SDEF_C / _SDEF_R0 / _SDEF_R1 and the deform type as _DEFORM when a vertex uses SDEF / QDEF, _EDGE_SCALE); vertex
-- morphs become morph targets (POSITION deltas, names in mesh.extras.targetNames); bones become nodes (a parent-relative
-- translation each) and one skin with translation-only inverse bind matrices.
local Types = require("@formats/Types")
local Build = {}
local readf32, writef32, readi32, readu32 = buffer.readf32, buffer.writef32, buffer.readi32, buffer.readu32
local S = Types.Scene
local SPHERE = { [0] = "off", "multiply", "add", "subtexture" }
local MORPH = { [0] = "group", "vertex", "bone", "uv", "uv1", "uv2", "uv3", "uv4", "material", "flip", "impulse" }
local MIME = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", spa = "image/bmp", sph = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" }
-- fetch(uri) -> buffer?: opts.files (by the name as written, with "/" separators, or the base name) / opts.resolve
local function fetcher(opts: any): (string) -> buffer?
return function(uri: string): buffer?
if not opts then
return nil
end
local v: any = nil
local slash = string.gsub(uri, "\\", "/")
if type(opts.files) == "table" then
v = opts.files[uri] or opts.files[slash] or opts.files[string.match(slash, "([^/]+)$") or slash]
end
if v == nil and type(opts.resolve) == "function" then
local ok, res = pcall(opts.resolve, slash)
v = if ok then res else nil
end
return if type(v) == "string" then buffer.fromstring(v) elseif type(v) == "buffer" then v else nil
end
end
local function lh(v: { number }?): { number }?
return if v then { v[1], v[2], -v[3] } else nil
end
-- the scene index of a file texture index (0-based, -1 = none)
local function texIndex(m: any, i: number?): number?
return if type(i) == "number" and i >= 0 and i < #m.textures then i + 1 else nil
end
local function material(m: any, mat: any): Types.Material
local out = S.material(mat.name)
local d = mat.diffuse
out.baseColor = { d[1], d[2], d[3], d[4] }
out.metallic = 0
out.roughness = math.clamp(math.sqrt(2 / (math.max(mat.power or 0, 0) + 2)), 0, 1)
out.doubleSided = bit32.btest(mat.flags, 0x01)
if d[4] < 1 then
out.alphaMode = "blend"
end
local t = texIndex(m, mat.texture)
if t then
out.baseColorTexture = { texture = t }
end
local x: { [string]: any } = {
nameEn = mat.nameEn, diffuse = d, specular = mat.specular, specularPower = mat.power, ambient = mat.ambient,
flags = mat.flags, edge = bit32.btest(mat.flags, 0x10), edgeColor = mat.edgeColor, edgeSize = mat.edgeSize,
sphereTexture = texIndex(m, mat.sphere), sphereMode = SPHERE[mat.sphereMode] or mat.sphereMode,
toonTexture = texIndex(m, mat.toon), memo = mat.memo, indexCount = mat.count,
}
if mat.toonShared then
x.toonShared = mat.toonShared
x.toonFile = string.format("toon%02d.bmp", mat.toonShared + 1)
end
out.extras = { pmx = x }
return out
end
-- bone parents that form a tree: an invalid index, the bone itself or a cycle makes a root
local function parents(bones: { any }): { number }
local nb = #bones
local par = table.create(nb, 0)
for i, b in bones do
local p = b.parent
if type(p) == "number" and p >= 0 and p < nb and p + 1 ~= i then
par[i] = p + 1
end
end
for i = 1, nb do
local seen, j, steps = {}, i, 0
while par[j] ~= 0 and steps <= nb do
seen[j] = true
j = par[j]
steps += 1
if seen[j] then
par[i] = 0
break
end
end
end
return par
end
-- the primitive of one material: indices [first, first + n) of the face list, its vertices renumbered
local function primitive(m: any, first: number, n: number, morphs: { any }, sdef: boolean): Types.Primitive
local map: { [number]: number } = {}
local verts: { number } = {}
local ind = S.accessor(nil, "u32", 1, n)
for t = 0, n // 3 - 1 do
-- reversed winding: a, c, b
for c = 0, 2 do
local src = readu32(m.indices, (first + t * 3 + c) * 4)
local v = map[src]
if not v then
v = #verts
verts[v + 1] = src
map[src] = v
end
buffer.writeu32(ind.data, (t * 3 + (if c == 0 then 0 elseif c == 1 then 2 else 1)) * 4, v)
end
end
local nv = #verts
local nb = #m.bones
local pos, nrm, uv = S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 2, nv)
local jo, we = S.accessor(nil, "u16", 4, nv), S.accessor(nil, "f32", 4, nv)
local edge = S.accessor(nil, "f32", 1, nv)
local attrs: { [string]: Types.Accessor } = { POSITION = pos, NORMAL = nrm, TEXCOORD_0 = uv, _EDGE_SCALE = edge }
if nb > 0 then
attrs.JOINTS_0, attrs.WEIGHTS_0 = jo, we
end
local uvas = {}
for a = 1, #m.uva do
uvas[a] = S.accessor(nil, "f32", 4, nv)
attrs["_UVA" .. a] = uvas[a]
end
local sd: { Types.Accessor }? = nil
local deform: Types.Accessor? = nil
if sdef then
sd = { S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv), S.accessor(nil, "f32", 3, nv) }
attrs._SDEF_C, attrs._SDEF_R0, attrs._SDEF_R1 = sd[1], sd[2], sd[3]
deform = S.accessor(nil, "u8", 1, nv)
attrs._DEFORM = deform
end
for v = 0, nv - 1 do
local src = verts[v + 1]
for c = 0, 2 do
local sgn = if c == 2 then -1 else 1
writef32(pos.data, (v * 3 + c) * 4, sgn * readf32(m.positions, (src * 3 + c) * 4))
writef32(nrm.data, (v * 3 + c) * 4, sgn * readf32(m.normals, (src * 3 + c) * 4))
end
buffer.copy(uv.data, v * 8, m.uvs, src * 8, 8)
buffer.copy(edge.data, v * 4, m.edge, src * 4, 4)
for a, acc in uvas do
buffer.copy(acc.data, v * 16, m.uva[a], src * 16, 16)
end
-- weights: invalid bones get weight 0, the rest is normalized
local sum = 0
local js, ws = table.create(4, 0), table.create(4, 0)
for c = 0, 3 do
local j = readi32(m.joints, src * 16 + c * 4)
local w = readf32(m.weights, src * 16 + c * 4)
if j >= 0 and j < nb and w > 0 and w == w then
js[c + 1], ws[c + 1] = j, w
sum += w
end
end
for c = 0, 3 do
buffer.writeu16(jo.data, (v * 4 + c) * 2, js[c + 1])
writef32(we.data, (v * 4 + c) * 4, if sum > 0 then ws[c + 1] / sum else (if c == 0 then 1 else 0))
end
if sd and deform then
buffer.writeu8(deform.data, v, buffer.readu8(m.deform, src))
if m.sdef then
for q = 0, 2 do
for c = 0, 2 do
local x = readf32(m.sdef, src * 36 + q * 12 + c * 4)
writef32(sd[q + 1].data, (v * 3 + c) * 4, if c == 2 then -x else x)
end
end
end
end
end
local prim: Types.Primitive = { attributes = attrs, indices = ind, mode = "triangles" }
if #morphs > 0 then
local targets: { { [string]: Types.Accessor } } = {}
for k, mo in morphs do
local d = S.accessor(nil, "f32", 3, nv)
for o, src in mo.vertices do
local v = map[src]
if v then
for c = 0, 2 do
local x = readf32(mo.deltas, ((o - 1) * 3 + c) * 4)
writef32(d.data, (v * 3 + c) * 4, if c == 2 then -x else x)
end
end
end
targets[k] = { POSITION = d }
end
prim.targets = targets
end
return prim
end
function Build.scene(m: any, opts: any): (any, ...any)
local scene = S.new()
scene.meta.up = "y"
local fetch = fetcher(opts)
for i, path in m.textures do
local uri = string.gsub(path, "\\", "/")
local tex: Types.Texture = { name = path, uri = uri }
local data = fetch(path)
if data then
tex.data = data
end
local ext = string.match(uri, "%.(%w+)$")
tex.mime = if ext then MIME[string.lower(ext)] else nil
scene.textures[i] = tex
end
for i, mat in m.materials do
scene.materials[i] = material(m, mat)
end
-- vertex morphs -> targets (others stay in mesh.extras.pmx.morphs)
local vmorphs, names, others = {}, {}, {}
local wantMorphs = not (opts and opts.morphs == false)
for _, mo in m.morphs do
if mo.type == 1 and wantMorphs then
table.insert(vmorphs, mo)
table.insert(names, mo.name)
elseif mo.type ~= 1 then
table.insert(others, { name = mo.name, nameEn = mo.nameEn, panel = mo.panel, type = MORPH[mo.type] or mo.type, offsets = mo.offsets })
end
end
local maxBytes = if opts and opts.maxBytes then opts.maxBytes else 2 ^ 28
if #vmorphs * m.vertexCount * 12 > maxBytes then
return nil, string.format("limit: %d vertex morphs on %d vertices (maxBytes; morphs = false skips them)", #vmorphs, m.vertexCount), "limit"
end
local sdef = false
for v = 0, m.vertexCount - 1 do
local k = buffer.readu8(m.deform, v)
if k == 3 or k == 4 then
sdef = true
break
end
end
local mesh: Types.Mesh = { name = m.name, primitives = {} }
local first = 0
for i, mat in m.materials do
local n = mat.count
if type(n) ~= "number" or n < 0 or n % 3 ~= 0 or first + n > m.indexCount then
return nil, string.format("material %d: %s face indices past the face list", i, tostring(n))
end
local prim = primitive(m, first, n, vmorphs, sdef)
prim.material = i
table.insert(mesh.primitives, prim)
first += n
end
if first < m.indexCount then
-- faces no material covers
table.insert(mesh.primitives, primitive(m, first, m.indexCount - first, vmorphs, sdef))
end
mesh.extras = { targetNames = if #names > 0 then names else nil, pmx = if #others > 0 then { morphs = others } else nil }
if #vmorphs > 0 then
mesh.weights = table.create(#vmorphs, 0)
end
scene.meshes[1] = mesh
-- nodes: 1 = the model, 2 = the mesh, then one per bone
scene.nodes[1] = { name = m.name, children = { 2 } }
scene.nodes[2] = { name = m.name .. "_mesh", children = {}, mesh = 1 }
scene.roots[1] = 1
local bones = m.bones
local nb = #bones
if nb > 0 then
local par = parents(bones)
local world: { { number } } = {}
for i, b in bones do
world[i] = lh(b.pos) or { 0, 0, 0 }
end
local ibm = S.accessor(nil, "f32", 16, nb)
ibm.matrix = true
local joints: { number } = {}
for i, b in bones do
local w, p = world[i], par[i]
local t = if p ~= 0 then { w[1] - world[p][1], w[2] - world[p][2], w[3] - world[p][3] } else { w[1], w[2], w[3] }
local x: { [string]: any } = { nameEn = b.nameEn, index = i - 1, layer = b.layer, flags = b.flags, position = b.pos }
x.tail, x.inherit, x.axis, x.localX, x.localZ, x.externalKey, x.ik = b.tail, b.inherit, b.axis, b.localX, b.localZ, b.externalKey, b.ik
scene.nodes[2 + i] = { name = b.name, children = {}, translation = t, extras = { pmx = x } }
joints[i] = 2 + i
for c = 0, 15 do
local val = if c % 5 == 0 then 1 elseif c >= 12 and c <= 14 then -w[c - 11] else 0
writef32(ibm.data, ((i - 1) * 16 + c) * 4, val)
end
end
for i = 1, nb do
local p = par[i]
table.insert(scene.nodes[if p ~= 0 then 2 + p else 1].children, 2 + i)
end
scene.skins[1] = { name = m.name, joints = joints, inverseBindMatrices = ibm }
scene.nodes[2].skin = 1
end
scene.meta.source = {
format = "pmx", version = m.version, encoding = m.encoding, name = m.name, nameEn = m.nameEn, comment = m.comment,
commentEn = m.commentEn, additionalUV = #m.uva, displayFrames = m.frames, rigidBodies = m.rigidBodies, joints = m.jointsList,
softBodies = m.softBodies, toonTextures = m.toonTextures,
}
return scene
end
return Build
+339
View File
@@ -0,0 +1,339 @@
--!strict
-- model/pmx/Pmd: the PMD 1.0 parser (MikuMikuDance's original model format), into the same model table as
-- model/pmx/Read so model/pmx/Build makes the Scene. Written from the PMD layout as documented by the MMD community
-- (MMDAgent / mmd_tools notes); no third-party code. Reads vertices (two bones, weight 0..100, edge flag), faces,
-- materials ("texture*sphere" names, toon index), bones, IK chains, skins (the base skin + vertex morphs relative to
-- it), display lists, the optional English names, toon texture names, rigid bodies and joints. Names are Shift-JIS in
-- the file: ASCII names are kept, others use the English name when there is one, else the raw bytes (in
-- extras / meta.source as `nameSjis`). Never throws: returns nil, message[, kind].
local Bytes = require("@formats/core/Bytes")
local Pmd = {}
local function vec(r: Bytes.Reader, n: number): { number }
local v: { number } = {}
for i = 1, n do
v[i] = r:f32le()
end
return v
end
local function ascii(s: string): boolean
return not string.find(s, "[\128-\255]")
end
local function counted(r: Bytes.Reader, n: number, size: number, what: string): (boolean, ...any)
if n * size > r.limit - r.pos then
return false, string.format("%d %s do not fit in the file", n, what)
end
return true
end
function Pmd.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...any)
if not r:match("Pmd") then
return nil, "not a PMD file"
end
local version = r:f32le()
if version ~= 1 then
return nil, "unsupported: PMD version " .. tostring(version), "unsupported"
end
local m: { [string]: any } = { version = 1.0, encoding = "shift_jis", uva = {}, sdef = nil }
m.nameSjis, m.commentSjis = r:fixed(20), r:fixed(256)
local buf = r.buf
-- vertices: 38 bytes each
local nv = r:u32le()
if r.err then
return nil, "truncated", "truncated"
end
local ok, e = counted(r, nv, 38, "vertices")
if not ok then
return nil, e, "truncated"
end
local maxV = if opts and opts.maxVertices then opts.maxVertices else 2 ^ 24
if nv > maxV then
return nil, string.format("limit: %d vertices (maxVertices %d)", nv, maxV), "limit"
end
local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8)
local deform, joints, weights, edge = buffer.create(nv), buffer.create(nv * 16), buffer.create(nv * 16), buffer.create(nv * 4)
for v = 0, nv - 1 do
local p = r.pos + v * 38
buffer.copy(pos, v * 12, buf, p, 12)
buffer.copy(nrm, v * 12, buf, p + 12, 12)
buffer.copy(uv, v * 8, buf, p + 24, 8)
local b0, b1 = buffer.readu16(buf, p + 32), buffer.readu16(buf, p + 34)
local w = math.clamp(buffer.readu8(buf, p + 36), 0, 100) / 100
local single = b0 == b1 or w == 1
buffer.writeu8(deform, v, if single then 0 else 1)
buffer.writei32(joints, v * 16, b0)
buffer.writei32(joints, v * 16 + 4, if single then -1 else b1)
buffer.writei32(joints, v * 16 + 8, -1)
buffer.writei32(joints, v * 16 + 12, -1)
buffer.writef32(weights, v * 16, if single then 1 else w)
buffer.writef32(weights, v * 16 + 4, if single then 0 else 1 - w)
buffer.writef32(edge, v * 4, if buffer.readu8(buf, p + 37) ~= 0 then 0 else 1)
end
r.pos += nv * 38
m.vertexCount, m.positions, m.normals, m.uvs, m.deform, m.joints, m.weights, m.edge = nv, pos, nrm, uv, deform, joints, weights, edge
-- faces: u16 indices
local ni = r:u32le()
ok, e = counted(r, ni, 2, "face indices")
if r.err or not ok then
return nil, e or "truncated", "truncated"
end
if ni % 3 ~= 0 then
return nil, ni .. " face indices (not triangles)"
end
local ind = buffer.create(ni * 4)
for i = 0, ni - 1 do
local x = buffer.readu16(buf, r.pos + i * 2)
if x >= nv then
return nil, string.format("face index %d out of range (%d vertices)", x, nv)
end
buffer.writeu32(ind, i * 4, x)
end
r.pos += ni * 2
m.indexCount, m.indices = ni, ind
-- materials: 70 bytes each; texture names collected into the texture list
local nm = r:u32le()
ok, e = counted(r, nm, 70, "materials")
if r.err or not ok then
return nil, e or "truncated", "truncated"
end
m.textures = {}
local texIndex: { [string]: number } = {}
local function tex(name: string): number
if name == "" then
return -1
end
local i = texIndex[name]
if not i then
table.insert(m.textures, name)
i = #m.textures - 1
texIndex[name] = i
end
return i
end
m.materials = table.create(nm)
local toonIdx = {}
for i = 1, nm do
local mat: { [string]: any } = { name = "material" .. (i - 1), nameEn = "material" .. (i - 1) }
local d = vec(r, 4)
mat.diffuse, mat.power, mat.specular, mat.ambient = d, r:f32le(), vec(r, 3), vec(r, 3)
local toon, edgeFlag = r:u8(), r:u8()
mat.count = r:u32le()
local file = r:fixed(20)
mat.flags = (if edgeFlag ~= 0 then 0x10 else 0) + (if d[4] < 1 then 0x01 else 0)
mat.edgeColor, mat.edgeSize, mat.memo = { 0, 0, 0, 1 }, 1, ""
mat.texture, mat.sphere, mat.sphereMode = -1, -1, 0
for part in string.gmatch(file, "[^*]+") do
local ext = string.lower(string.match(part, "%.(%w+)$") or "")
if ext == "sph" or ext == "spa" then
mat.sphere, mat.sphereMode = tex(part), if ext == "sph" then 1 else 2
else
mat.texture = tex(part)
end
end
toonIdx[i] = toon
m.materials[i] = mat
end
-- bones: 39 bytes each
local nb = r:u16le()
ok, e = counted(r, nb, 39, "bones")
if r.err or not ok then
return nil, e or "truncated", "truncated"
end
m.bones = table.create(nb)
for i = 1, nb do
local b: { [string]: any } = { nameSjis = r:fixed(20) }
local parent, tail, kind, ikParent = r:u16le(), r:u16le(), r:u8(), r:u16le()
b.pos = vec(r, 3)
b.parent = if parent == 0xFFFF then -1 else parent
b.tail = if tail ~= 0 and tail ~= 0xFFFF then tail else { 0, 0, 0 }
b.layer, b.pmdType, b.ikParent = 0, kind, ikParent
-- PMX-style flags: tail index, rotatable, translatable (type 1), visible (not type 7), enabled
b.flags = (if type(b.tail) == "number" then 0x1 else 0) + 0x2 + (if kind == 1 then 0x4 else 0) + (if kind ~= 7 then 0x8 else 0) + 0x10
m.bones[i] = b
end
-- IK chains
local nik = r:u16le()
for _ = 1, nik do
local bone, target, len, loops, limit = r:u16le(), r:u16le(), r:u8(), r:u16le(), r:f32le()
local links = table.create(len)
for l = 1, len do
links[l] = { bone = r:u16le() }
end
if r.err then
return nil, "truncated", "truncated"
end
local b = m.bones[bone + 1]
if b then
b.flags = bit32.bor(b.flags, 0x20)
-- PMD's limit is in units of 4 radians (PMX stores radians)
b.ik = { target = target, loops = loops, limit = limit * 4, links = links }
end
end
-- skins: the base (absolute positions of every vertex a morph moves), then morphs relative to it
local ns = r:u16le()
if r.err then
return nil, "truncated", "truncated"
end
m.morphs = {}
local base: { number } = {}
for s = 1, ns do
local name = r:fixed(20)
local n, panel = r:u32le(), r:u8()
ok, e = counted(r, n, 16, "skin vertices")
if r.err or not ok then
return nil, e or "truncated", "truncated"
end
if s == 1 and panel == 0 then
for o = 1, n do
base[o] = r:u32le()
r:skip(12)
end
else
local vi, deltas = table.create(n), buffer.create(n * 12)
for o = 1, n do
local k = r:u32le()
local v = base[k + 1]
if not v or v >= nv then
return nil, string.format("skin %d: base vertex %d out of range", s - 1, k)
end
vi[o] = v
buffer.copy(deltas, (o - 1) * 12, buf, r.pos, 12)
r:skip(12)
end
table.insert(m.morphs, { nameSjis = name, panel = panel, type = 1, vertices = vi, deltas = deltas })
end
end
-- display lists (skin list, bone group names, bone groups)
local nsd = r:u8()
r:skip(nsd * 2)
local ng = r:u8()
local groups: { { [string]: any } } = {}
for g = 1, ng do
groups[g] = { nameSjis = r:fixed(50), special = false, items = {} }
end
local nbd = r:u32le()
ok, e = counted(r, nbd, 3, "bone display entries")
if r.err or not ok then
return nil, e or "truncated", "truncated"
end
for _ = 1, nbd do
local bone, g = r:u16le(), r:u8()
local grp = groups[g]
if grp then
table.insert(grp.items, { bone = bone })
end
end
m.frames = groups
-- optional: English names, toon textures, physics
local function name(t: { [string]: any }, en: string?)
local raw = t.nameSjis or ""
t.nameEn = en
t.name = if ascii(raw) then raw elseif en and en ~= "" then en else raw
if ascii(raw) then
t.nameSjis = nil
end
end
local en: any = {}
if r.limit - r.pos >= 1 and r:u8() == 1 then
en.name, en.comment = r:fixed(20), r:fixed(256)
en.bones = table.create(nb)
for i = 1, nb do
en.bones[i] = r:fixed(20)
end
en.morphs = {}
for i = 1, #m.morphs do
en.morphs[i] = r:fixed(20)
end
en.groups = {}
for i = 1, ng do
en.groups[i] = r:fixed(50)
end
end
local model = { nameSjis = m.nameSjis }
name(model, en.name)
m.name, m.nameEn = model.name, en.name
m.comment, m.commentEn = if ascii(m.commentSjis) then m.commentSjis else (en.comment or m.commentSjis), en.comment
if ascii(m.nameSjis) then
m.nameSjis = nil
end
for i, b in m.bones do
name(b, en.bones and en.bones[i])
end
for i, mo in m.morphs do
name(mo, en.morphs and en.morphs[i])
end
for i, g in groups do
name(g, en.groups and en.groups[i])
end
local toons: { string } = {}
for i = 1, 10 do
toons[i] = string.format("toon%02d.bmp", i)
end
if r.limit - r.pos >= 1000 then
for i = 1, 10 do
toons[i] = r:fixed(100)
end
end
m.toonTextures = toons
for i, mat in m.materials do
local t = toonIdx[i]
if t < 10 then
if toons[t + 1] == string.format("toon%02d.bmp", t + 1) then
mat.toonShared = t
else
mat.toon = tex(toons[t + 1])
end
else
mat.toon = -1
end
end
m.rigidBodies, m.jointsList = {}, {}
if r.limit - r.pos >= 4 then
local nr = r:u32le()
ok, e = counted(r, nr, 83, "rigid bodies")
if not ok then
return nil, e, "truncated"
end
for i = 1, nr do
local b: { [string]: any } = { name = r:fixed(20), bone = r:u16le(), group = r:u8(), mask = r:u16le(), shape = r:u8() }
b.size, b.position, b.rotation = vec(r, 3), vec(r, 3), vec(r, 3)
b.mass, b.linearDamping, b.angularDamping, b.restitution, b.friction = r:f32le(), r:f32le(), r:f32le(), r:f32le(), r:f32le()
b.mode = r:u8()
if b.bone == 0xFFFF then
b.bone = -1
end
m.rigidBodies[i] = b
end
end
if r.limit - r.pos >= 4 then
local nj = r:u32le()
ok, e = counted(r, nj, 124, "joints")
if not ok then
return nil, e, "truncated"
end
for i = 1, nj do
local j: { [string]: any } = { name = r:fixed(20), type = 0, a = r:u32le(), b = r:u32le() }
j.position, j.rotation = vec(r, 3), vec(r, 3)
j.positionMin, j.positionMax, j.rotationMin, j.rotationMax = vec(r, 3), vec(r, 3), vec(r, 3), vec(r, 3)
j.positionSpring, j.rotationSpring = vec(r, 3), vec(r, 3)
m.jointsList[i] = j
end
end
if r.err then
return nil, "truncated", "truncated"
end
return m
end
return Pmd
+411
View File
@@ -0,0 +1,411 @@
--!strict
-- model/pmx/Read: the PMX 2.0 / 2.1 parser (MikuMikuDance / PmxEditor model files), into the plain model table that
-- model/pmx/Build turns into a Scene. Written from the PMX 2.0 / 2.1 specification notes that ship with PmxEditor.
-- Reads every section: header globals (UTF-16LE / UTF-8 text, additional UV count, index sizes 1 / 2 / 4), vertices
-- (BDEF1 / BDEF2 / BDEF4 / SDEF / QDEF), faces, textures, materials, bones (tail, inherit, fixed / local axes,
-- external parent, IK), morphs (group, vertex, bone, UV, UV1-4, material, flip, impulse), display frames, rigid bodies,
-- joints; 2.1 soft bodies are counted, not parsed. Values stay as in the file (left-handed, 0-based indices).
-- Never throws: returns nil, message[, kind].
local Bytes = require("@formats/core/Bytes")
local Text = require("@formats/codecs/text/Text")
local Read = {}
export type Model = { [string]: any }
local readu8, readu16, readi32 = buffer.readu8, buffer.readu16, buffer.readi32
-- index readers: vertex indices are unsigned for sizes 1 / 2, every other index is signed (-1 = none)
local function indexReader(r: Bytes.Reader, size: number, vertex: boolean): () -> number
if size == 1 then
return if vertex then function() return r:u8() end else function() return r:i8() end
elseif size == 2 then
return if vertex then function() return r:u16le() end else function() return r:i16le() end
end
return function() return r:i32le() end
end
local function vec(r: Bytes.Reader, n: number): { number }
local v: { number } = {}
for i = 1, n do
v[i] = r:f32le()
end
return v
end
-- a count field: i32 >= 0 and at most remaining / minSize records
local function count(r: Bytes.Reader, minSize: number, what: string): (any, ...any)
local n = r:i32le()
if r.err then
return nil, "truncated", "truncated"
end
if n < 0 then
return nil, "negative " .. what .. " count"
end
if n * minSize > r.limit - r.pos then
return nil, string.format("%d %s do not fit in the file", n, what), "truncated"
end
return n
end
function Read.parse(r: Bytes.Reader, opts: { maxVertices: number? }?): (any, ...any)
if not r:match("PMX ") then
return nil, "not a PMX file"
end
local version = r:f32le()
local nglobals = r:u8()
if r.err then
return nil, "truncated", "truncated"
end
if version < 1.95 or version > 2.15 then
return nil, "unsupported: PMX version " .. tostring(version), "unsupported"
end
version = if version > 2.05 then 2.1 else 2.0
if nglobals < 8 then
return nil, "only " .. nglobals .. " header globals"
end
local g: { number } = {}
for i = 1, nglobals do
g[i] = r:u8()
end
local utf8 = g[1] == 1
if g[1] > 1 then
return nil, "unknown text encoding " .. g[1]
end
local uva = g[2]
if uva > 4 then
return nil, uva .. " additional UVs (at most 4)"
end
for i = 3, 8 do
if g[i] ~= 1 and g[i] ~= 2 and g[i] ~= 4 then
return nil, "bad index size " .. g[i]
end
end
local vsize, tsize, msize, bsize, morsize, rsize = g[3], g[4], g[5], g[6], g[7], g[8]
local buf = r.buf
local function text(): string
local n = r:i32le()
if r.err or n < 0 or n > r.limit - r.pos then
r:need(r.limit - r.pos + 1)
return ""
end
local p = r.pos
r.pos += n
if utf8 then
return buffer.readstring(buf, p, n)
end
return Text.utf16(buf, p, n)
end
local vidx = indexReader(r, vsize, true)
local tidx = indexReader(r, tsize, false)
local midx = indexReader(r, msize, false)
local bidx = indexReader(r, bsize, false)
local moidx = indexReader(r, morsize, false)
local ridx = indexReader(r, rsize, false)
local m: Model = { version = version, encoding = if utf8 then "utf8" else "utf16", additionalUV = uva, indexSizes = { vsize, tsize, msize, bsize, morsize, rsize } }
m.name, m.nameEn, m.comment, m.commentEn = text(), text(), text(), text()
if r.err then
return nil, "truncated", "truncated"
end
-- vertices: position, normal, uv, additional uvs, deform, edge scale
local nv, e, k = count(r, 8 * 4 + 1 + bsize + 4 + uva * 16, "vertices")
if not nv then
return nil, e, k
end
local maxV = if opts and opts.maxVertices then opts.maxVertices else 2 ^ 24
if nv > maxV then
return nil, string.format("limit: %d vertices (maxVertices %d)", nv :: number, maxV), "limit"
end
local pos, nrm, uv = buffer.create(nv * 12), buffer.create(nv * 12), buffer.create(nv * 8)
local uvas = {}
for a = 1, uva do
uvas[a] = buffer.create(nv * 16)
end
local deform, joints, weights = buffer.create(nv), buffer.create(nv * 16), buffer.create(nv * 16)
local edge = buffer.create(nv * 4)
local sdef: buffer? = nil
local writef32, writei32 = buffer.writef32, buffer.writei32
for v = 0, nv - 1 do
if not r:need(32 + uva * 16 + 1) then
return nil, "truncated", "truncated"
end
local p = r.pos
for c = 0, 2 do
writef32(pos, (v * 3 + c) * 4, buffer.readf32(buf, p + c * 4))
writef32(nrm, (v * 3 + c) * 4, buffer.readf32(buf, p + 12 + c * 4))
end
writef32(uv, v * 8, buffer.readf32(buf, p + 24))
writef32(uv, v * 8 + 4, buffer.readf32(buf, p + 28))
p += 32
for a = 1, uva do
buffer.copy(uvas[a], v * 16, buf, p, 16)
p += 16
end
local kind = readu8(buf, p)
r.pos = p + 1
buffer.writeu8(deform, v, kind)
local o = v * 16
if kind == 0 then
writei32(joints, o, bidx())
writei32(joints, o + 4, -1)
writei32(joints, o + 8, -1)
writei32(joints, o + 12, -1)
writef32(weights, o, 1)
elseif kind == 1 or kind == 3 then
writei32(joints, o, bidx())
writei32(joints, o + 4, bidx())
writei32(joints, o + 8, -1)
writei32(joints, o + 12, -1)
local w = r:f32le()
writef32(weights, o, w)
writef32(weights, o + 4, 1 - w)
if kind == 3 then
local sd = sdef or buffer.create(nv * 36)
sdef = sd
for c = 0, 8 do
writef32(sd, v * 36 + c * 4, r:f32le())
end
end
elseif kind == 2 or kind == 4 then
for c = 0, 3 do
writei32(joints, o + c * 4, bidx())
end
for c = 0, 3 do
writef32(weights, o + c * 4, r:f32le())
end
else
return nil, "unknown vertex deform type " .. kind
end
writef32(edge, v * 4, r:f32le())
if r.err then
return nil, "truncated", "truncated"
end
end
m.vertexCount, m.positions, m.normals, m.uvs, m.uva = nv, pos, nrm, uv, uvas
m.deform, m.joints, m.weights, m.sdef, m.edge = deform, joints, weights, sdef, edge
-- faces: vertex index triples
local ni
ni, e, k = count(r, vsize, "face indices")
if not ni then
return nil, e, k
end
if ni % 3 ~= 0 then
return nil, ni .. " face indices (not triangles)"
end
local ind = buffer.create(ni * 4)
local p = r.pos
for i = 0, ni - 1 do
local x = if vsize == 1 then readu8(buf, p + i) elseif vsize == 2 then readu16(buf, p + i * 2) else readi32(buf, p + i * 4)
if x < 0 or x >= nv then
return nil, string.format("face index %d out of range (%d vertices)", x, nv :: number), nil
end
buffer.writeu32(ind, i * 4, x)
end
r.pos = p + ni * vsize
m.indexCount, m.indices = ni, ind
-- textures
local nt
nt, e, k = count(r, 4, "textures")
if not nt then
return nil, e, k
end
m.textures = table.create(nt)
for i = 1, nt do
m.textures[i] = text()
end
-- materials
local nm
nm, e, k = count(r, 8 + 16 + 12 + 4 + 12 + 1 + 16 + 4 + 2 * tsize + 2 + 1 + 4 + 4, "materials")
if not nm then
return nil, e, k
end
m.materials = table.create(nm)
for i = 1, nm do
local mat: { [string]: any } = { name = text(), nameEn = text() }
mat.diffuse, mat.specular, mat.power, mat.ambient = vec(r, 4), vec(r, 3), r:f32le(), vec(r, 3)
mat.flags = r:u8()
mat.edgeColor, mat.edgeSize = vec(r, 4), r:f32le()
mat.texture, mat.sphere, mat.sphereMode = tidx(), tidx(), r:u8()
if r:u8() == 1 then
mat.toonShared = r:u8()
else
mat.toon = tidx()
end
mat.memo, mat.count = text(), r:i32le()
if r.err then
return nil, "truncated", "truncated"
end
m.materials[i] = mat
end
-- bones
local nb
nb, e, k = count(r, 8 + 12 + bsize + 4 + 2 + bsize, "bones")
if not nb then
return nil, e, k
end
m.bones = table.create(nb)
for i = 1, nb do
local b: { [string]: any } = { name = text(), nameEn = text() }
b.pos, b.parent, b.layer = vec(r, 3), bidx(), r:i32le()
local fl = r:u16le()
b.flags = fl
b.tail = if bit32.btest(fl, 0x1) then bidx() else vec(r, 3)
if bit32.btest(fl, 0x300) then
b.inherit = { bone = bidx(), influence = r:f32le(), rotation = bit32.btest(fl, 0x100), translation = bit32.btest(fl, 0x200) }
end
if bit32.btest(fl, 0x400) then
b.axis = vec(r, 3)
end
if bit32.btest(fl, 0x800) then
b.localX, b.localZ = vec(r, 3), vec(r, 3)
end
if bit32.btest(fl, 0x2000) then
b.externalKey = r:i32le()
end
if bit32.btest(fl, 0x20) then
local ik: { [string]: any } = { target = bidx(), loops = r:i32le(), limit = r:f32le() }
local nl
nl, e, k = count(r, bsize + 1, "IK links")
if not nl then
return nil, e, k
end
ik.links = table.create(nl)
for l = 1, nl do
local link: { [string]: any } = { bone = bidx() }
if r:u8() == 1 then
link.min, link.max = vec(r, 3), vec(r, 3)
end
ik.links[l] = link
end
b.ik = ik
end
if r.err then
return nil, "truncated", "truncated"
end
m.bones[i] = b
end
-- morphs
local nmo
nmo, e, k = count(r, 8 + 2 + 4, "morphs")
if not nmo then
return nil, e, k
end
local SIZE = { [0] = morsize + 4, vsize + 12, bsize + 28, vsize + 16, vsize + 16, vsize + 16, vsize + 16, vsize + 16, msize + 1 + 112, morsize + 4, rsize + 25 }
m.morphs = table.create(nmo)
for i = 1, nmo do
local mo: { [string]: any } = { name = text(), nameEn = text(), panel = r:u8(), type = r:u8() }
local t = mo.type
local size = SIZE[t]
if not size then
return nil, "unknown morph type " .. t
end
local no
no, e, k = count(r, size, "morph offsets")
if not no then
return nil, e, k
end
if t == 1 then
-- vertex morphs: packed (index list + deltas), they become morph targets
local vi, d = table.create(no), buffer.create(no * 12)
for o = 1, no do
local x = vidx()
vi[o] = x
for c = 0, 2 do
writef32(d, ((o - 1) * 3 + c) * 4, r:f32le())
end
end
mo.vertices, mo.deltas = vi, d
else
local offs = table.create(no)
for o = 1, no do
local off: { [string]: any }
if t == 0 or t == 9 then
off = { morph = moidx(), weight = r:f32le() }
elseif t == 2 then
off = { bone = bidx(), translation = vec(r, 3), rotation = vec(r, 4) }
elseif t <= 7 then
off = { vertex = vidx(), value = vec(r, 4) }
elseif t == 8 then
off = { material = midx(), operation = r:u8() }
off.diffuse, off.specular, off.specularPower, off.ambient = vec(r, 4), vec(r, 3), r:f32le(), vec(r, 3)
off.edgeColor, off.edgeSize, off.textureTint, off.sphereTint, off.toonTint = vec(r, 4), r:f32le(), vec(r, 4), vec(r, 4), vec(r, 4)
else
off = { rigidBody = ridx(), localFrame = r:u8() == 1, velocity = vec(r, 3), torque = vec(r, 3) }
end
offs[o] = off
end
mo.offsets = offs
end
if r.err then
return nil, "truncated", "truncated"
end
m.morphs[i] = mo
end
-- display frames, rigid bodies, joints: optional at the end (some tools stop after the morphs)
m.frames, m.rigidBodies, m.jointsList = {}, {}, {}
if r.limit - r.pos >= 4 then
local nf
nf, e, k = count(r, 8 + 1 + 4, "display frames")
if not nf then
return nil, e, k
end
for i = 1, nf do
local f: { [string]: any } = { name = text(), nameEn = text(), special = r:u8() == 1 }
local nitem
nitem, e, k = count(r, 1 + math.min(bsize, morsize), "display frame items")
if not nitem then
return nil, e, k
end
f.items = table.create(nitem)
for q = 1, nitem do
local kind = r:u8()
f.items[q] = if kind == 0 then { bone = bidx() } else { morph = moidx() }
end
m.frames[i] = f
end
end
if r.limit - r.pos >= 4 then
local nr
nr, e, k = count(r, 8 + bsize + 4 + 36 + 20 + 1, "rigid bodies")
if not nr then
return nil, e, k
end
for i = 1, nr do
local b: { [string]: any } = { name = text(), nameEn = text(), bone = bidx(), group = r:u8(), mask = r:u16le(), shape = r:u8() }
b.size, b.position, b.rotation = vec(r, 3), vec(r, 3), vec(r, 3)
b.mass, b.linearDamping, b.angularDamping, b.restitution, b.friction = r:f32le(), r:f32le(), r:f32le(), r:f32le(), r:f32le()
b.mode = r:u8()
m.rigidBodies[i] = b
end
end
if r.limit - r.pos >= 4 then
local nj
nj, e, k = count(r, 8 + 1 + 2 * rsize + 96, "joints")
if not nj then
return nil, e, k
end
for i = 1, nj do
local j: { [string]: any } = { name = text(), nameEn = text(), type = r:u8(), a = ridx(), b = ridx() }
j.position, j.rotation = vec(r, 3), vec(r, 3)
j.positionMin, j.positionMax, j.rotationMin, j.rotationMax = vec(r, 3), vec(r, 3), vec(r, 3), vec(r, 3)
j.positionSpring, j.rotationSpring = vec(r, 3), vec(r, 3)
m.jointsList[i] = j
end
end
if version >= 2.1 and r.limit - r.pos >= 4 then
m.softBodies = r:i32le()
end
if r.err then
return nil, "truncated", "truncated"
end
return m
end
return Read
+77
View File
@@ -0,0 +1,77 @@
--!strict
-- model/pmx: MikuMikuDance models, PMX 2.0 / 2.1 (PmxEditor's specification notes) and PMD 1.0 (the original MMD
-- format, as documented by the MMD community). New code, no third-party code.
-- Reads: UTF-16 / UTF-8 text (PMD: Shift-JIS names kept when ASCII, else the English names), vertices with BDEF1 /
-- BDEF2 / BDEF4 / SDEF / QDEF weights -> JOINTS_0 / WEIGHTS_0 (normalized; SDEF C / R0 / R1 as _SDEF_C / _SDEF_R0 /
-- _SDEF_R1, the deform type as _DEFORM, additional UVs as _UVA1.._UVA4 vec4, edge scale as _EDGE_SCALE), faces (one
-- primitive per material), textures (uri, data through opts.files / opts.resolve), materials (diffuse -> baseColor,
-- specular power -> roughness, no-cull -> doubleSided; diffuse / specular / ambient, edge, sphere map and mode, toon
-- texture or shared toon index, memo in material.extras.pmx), bones (nodes with parent-relative translations, one skin;
-- tail, inherit, axes, IK in node.extras.pmx), vertex morphs -> morph targets (POSITION deltas, mesh.extras.targetNames),
-- the other morphs (group, bone, UV, material, flip, impulse), display frames, rigid bodies and joints as extras
-- (mesh.extras.pmx.morphs, meta.source). MMD's left-handed coordinates become right-handed: z is negated and the
-- winding reversed (extras keep the file's values and 0-based indices). meta.up = "y" (one unit is about 8 cm).
-- Not supported: writing, PMX 2.1 soft bodies (counted in meta.source.softBodies), VMD motions / VPD poses.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Read = require("@formats/model/pmx/Read")
local Pmd = require("@formats/model/pmx/Pmd")
local Build = require("@formats/model/pmx/Build")
-- ------------------------------------------------------------------------------------------------ contract
local Pmx = {
name = "pmx",
category = "model",
extensions = { "pmx", "pmd" },
mime = { "model/x-pmx", "model/x-pmd" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Text" },
caps = { decode = true, encode = false, materials = true, skins = true, morphTargets = true, pmd = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
files: { [string]: any }?, -- texture files by name (buffer or string; "/" or "\" separators, or the base name)
resolve: ((uri: string) -> any)?, -- or: reads a texture file (the api sets it for paths)
morphs: boolean?, -- vertex morphs as morph targets (default true)
maxVertices: number?, -- default 2^24
maxBytes: number?, -- morph target bytes (default 2^28)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Pmx.sniff(r: Bytes.Reader): number
local head = r:peek(8)
if string.sub(head, 1, 4) == "PMX " then
return 1
end
if string.sub(head, 1, 7) == "Pmd\0\0\128\63" then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Pmx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local pmd = r:peek(3) == "Pmd"
local m: any, msg: string?, kind: string?
if pmd then
m, msg, kind = Pmd.parse(r, opts)
else
m, msg, kind = Read.parse(r, opts)
end
if not m then
return nil, Err.from(msg, r.pos - r.base, kind)
end
local scene, berr, bkind = Build.scene(m, opts)
if not scene then
return nil, Err.from(berr, nil, bkind)
end
if pmd and scene.meta.source then
scene.meta.source.pmd = true
end
return scene, nil
end
return Pmx
+77
View File
@@ -0,0 +1,77 @@
--!strict
-- model/vrml: VRML97 (ISO/IEC 14772-1, `#VRML V2.0 utf8`) .wrl files, plain or gzipped (.wrz), a thin format over
-- codecs/model/Vrml (the scene-graph engine model/x3d shares). New code.
-- Reads: the scene graph (Transform with center / scaleOrientation, Group, Anchor, Billboard, Collision, Switch, LOD,
-- Inline through opts.files / opts.resolve), DEF / USE (shared meshes and materials), PROTO instances (expanded) and
-- EXTERNPROTO, Shape / Appearance / Material / ImageTexture / PixelTexture / TextureTransform, IndexedFaceSet (coord,
-- normal, color, texCoord with their own indices, per-vertex / per-face normals and colours, ccw, solid -> doubleSided),
-- IndexedLineSet, PointSet, ElevationGrid, Extrusion, the primitives Box / Sphere / Cone / Cylinder tessellated
-- (opts.segments), Viewpoint -> cameras, DirectionalLight / PointLight / SpotLight -> lights, TimeSensor ->
-- Position- / OrientationInterpolator -> Transform ROUTEs -> animations, WorldInfo -> meta.source.title / info. Polygons
-- are fan-triangulated unless opts.triangulate = false; texture t is flipped to glTF's top-left origin unless
-- opts.flipV = false. meta.up = "y", meta.unit = 1 (metres).
-- Writes: VRML97 text (see codecs/model/Vrml/Write: Transforms from the node tree, Shapes with IndexedFaceSet /
-- IndexedLineSet / PointSet, Appearance / Material / ImageTexture (texture files into opts.files), Viewpoints, lights,
-- TimeSensor + interpolator animations; DEF / USE for shared meshes and materials).
-- Not supported: VRML 1.0, Text / FontStyle (no glyphs), Script behaviour, sensors, sound, NURBS, morph targets and
-- skins on write (the rest pose is written).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Vrml = require("@formats/codecs/model/Vrml")
-- ------------------------------------------------------------------------------------------------ contract
local Wrl = {
name = "vrml",
category = "model",
extensions = { "wrl", "wrz", "vrml" },
mime = { "model/vrml", "x-world/x-vrml" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" },
caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string)
resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths)
triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives
flipV: boolean?, -- texture t -> 1 - t (default true: glTF's convention)
segments: number?, -- Sphere / Cone / Cylinder segments around (default 32)
maxVertices: number?, -- per geometry (default 2^24)
}
export type EncodeOptions = {
files: { [string]: any }?, -- receives the texture images (else url = texture.uri)
name: string?, -- the destination's file name (names the image files)
flipV: boolean?, -- default true (the inverse of decode)
}
-- ------------------------------------------------------------------------------------------------ sniff
function Wrl.sniff(r: Bytes.Reader): number
local head = r:peek(16)
if string.sub(head, 1, 3) == "\239\187\191" then
head = string.sub(head, 4)
end
return if string.sub(head, 1, 10) == "#VRML V2.0" then 1 elseif string.sub(head, 1, 6) == "#VRML " then 0.6 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Wrl.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local o: any = table.clone(opts or {})
o.format = "vrml"
return Vrml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), o)
end
-- ------------------------------------------------------------------------------------------------ encode
function Wrl.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: any = table.clone(opts or {})
o.encoding = "vrml97"
local text, err = Vrml.encode(scene, o)
if not text then
return nil, err
end
return buffer.fromstring(text), nil
end
return Wrl
+574
View File
@@ -0,0 +1,574 @@
--!strict
-- model/x/Build: the .x object tree (model/x/Parse) -> Types.Scene, from the DirectX templates' layouts. Direct3D is
-- left-handed (y up, row vectors): z is negated (positions, normals, matrices as S * M * S, keys) and the winding
-- reversed, so the scene is glTF's right-handed y-up with counter-clockwise front faces (assimp does the same).
-- A FrameTransformMatrix (row-vector order) is already column-major for column vectors. Texture coordinates keep
-- Direct3D's top-left origin (glTF's). Plain code (the caller wraps it in pcall).
local Types = require("@formats/Types")
local Mat4 = require("@formats/codecs/model/Mat4")
local Rig = require("@formats/codecs/model/Rig")
local Parse = require("@formats/model/x/Parse")
local Build = {}
local Scene = Types.Scene
local writef32, writeu32 = buffer.writef32, buffer.writeu32
type Node = Parse.Node
-- a cursor over an object's flattened values
type Vals = { v: { any }, i: number }
local function num(c: Vals): number
local x = c.v[c.i]
c.i += 1
if type(x) ~= "number" then
error("expected a number in the data", 0)
end
return x
end
local function str(c: Vals): string
local x = c.v[c.i]
c.i += 1
if type(x) ~= "string" then
error("expected a string in the data", 0)
end
return x
end
-- a non-negative integer (an index)
local function index(c: Vals, limit: number): number
local n = num(c)
if n < 0 or n ~= math.floor(n) or n > limit then
error("bad index " .. n, 0)
end
return n
end
-- a count of items that follow (each takes at least one value: a count past the data is refused before anything
-- is allocated for it)
local function count(c: Vals, limit: number): number
local n = num(c)
if n < 0 or n ~= math.floor(n) or n > limit then
error("bad count " .. n, 0)
end
if n > #c.v - c.i + 1 then
error("truncated: a count of " .. n .. " runs past the data", 0)
end
return n
end
-- z mirror of a column-major matrix: S * M * S, S = diag(1, 1, -1)
local function mirror(m: { number }): { number }
local o = table.clone(m)
for _, k in { 3, 7, 9, 10, 12, 15 } do
o[k] = -o[k]
end
return o
end
local function matrix(c: Vals): { number }
local m = table.create(16) :: { number }
for k = 1, 16 do
m[k] = num(c)
end
return mirror(m)
end
-- ------------------------------------------------------------------------------------------------ materials
local MIME: { [string]: string } = { png = "image/png", jpg = "image/jpeg", jpeg = "image/jpeg", bmp = "image/bmp", tga = "image/x-tga", dds = "image/vnd-ms.dds", gif = "image/gif" }
local function material(scene: Types.Scene, node: Node, texCache: { [string]: number }): Types.Material
local c: Vals = { v = node.vals, i = 1 }
local mat = Scene.material(node.name)
local r, g, b, a = num(c), num(c), num(c), num(c)
local power = num(c)
local sr, sg, sb = num(c), num(c), num(c)
local er, eg, eb = num(c), num(c), num(c)
mat.baseColor = { r, g, b, a }
if a < 1 then
mat.alphaMode = "blend"
end
mat.metallic = 0
mat.roughness = math.clamp(math.sqrt(2 / (math.max(power, 0) + 2)), 0, 1)
mat.emissive = { er, eg, eb }
local textures = {}
for _, k in node.kids do
local lt = string.lower(k.type)
if lt == "texturefilename" or lt == "normalmapfilename" then
local path = k.vals[1]
if type(path) == "string" and path ~= "" then
path = string.gsub(path, "\\\\", "\\")
local uri = string.gsub(path, "\\", "/")
local ti = texCache[uri]
if not ti then
local base = string.match(uri, "([^/]+)$") or uri
local ext = string.lower(string.match(base, "%.(%w+)$") or "")
table.insert(scene.textures, { name = base, uri = uri, mime = MIME[ext] })
ti = #scene.textures
texCache[uri] = ti
end
table.insert(textures, uri)
if lt == "normalmapfilename" then
mat.normalTexture = mat.normalTexture or { texture = ti }
else
mat.baseColorTexture = mat.baseColorTexture or { texture = ti }
end
end
end
end
mat.extras = { x = { diffuse = { r, g, b, a }, power = power, specular = { sr, sg, sb }, emissive = { er, eg, eb }, textures = textures } }
return mat
end
-- ------------------------------------------------------------------------------------------------ meshes
type Bones = { { name: string, matrix: { number } } }
type Ctx = {
scene: Types.Scene,
globalMats: { [string]: number },
texCache: { [string]: number },
nodeByName: { [string]: number },
pendingSkins: { { node: number, bones: Bones } },
maxVertices: number,
skippedFaces: number,
}
local function accessorF32(values: { number }, comps: number): Types.Accessor
local n = #values
local b = buffer.create(n * 4)
for i = 1, n do
writef32(b, (i - 1) * 4, values[i])
end
return Scene.accessor(b, "f32", comps, n // comps)
end
-- mesh(ctx, meshNode) -> mesh index, the skin's bones (nil: not skinned) | nil (no faces)
local function mesh(ctx: Ctx, m: Node, triangulate: boolean): (number?, Bones?)
local scene = ctx.scene
local c: Vals = { v = m.vals, i = 1 }
local nv = count(c, ctx.maxVertices)
local pos = table.create(nv * 3) :: { number }
for k = 1, nv * 3 do
pos[k] = num(c)
end
local nf = count(c, ctx.maxVertices)
local faces = table.create(nf) :: { { number } }
local corners = 0
for f = 1, nf do
local n = count(c, ctx.maxVertices)
corners += n
if corners > ctx.maxVertices then
error("limit: more than " .. ctx.maxVertices .. " face corners", 0)
end
local face = table.create(n) :: { number }
for k = 1, n do
local idx = index(c, 2 ^ 32)
if idx >= nv then
error("face index " .. idx .. " out of range", 0)
end
face[k] = idx
end
faces[f] = face
end
-- the optional data objects
local normals: { number }? = nil
local nfaces: { { number } }? = nil
local uvSets: { { number } } = {}
local colors: { { number } } = {}
local faceMat: { number } = {}
local mats: { number } = {}
local bones: { { name: string, verts: { number }, weights: { number }, matrix: { number } } } = {}
for _, k in m.kids do
local kc: Vals = { v = k.vals, i = 1 }
if k.type == "MeshNormals" then
local nn = count(kc, ctx.maxVertices)
local nr = table.create(nn * 3) :: { number }
for q = 1, nn * 3 do
nr[q] = num(kc)
end
local nnf = count(kc, ctx.maxVertices)
local nfs = table.create(nnf) :: { { number } }
for f = 1, nnf do
local n = count(kc, ctx.maxVertices)
local face = table.create(n) :: { number }
for q = 1, n do
face[q] = index(kc, 2 ^ 32)
end
nfs[f] = face
end
normals, nfaces = nr, nfs
elseif k.type == "MeshTextureCoords" then
local n = count(kc, ctx.maxVertices)
local uv = table.create(n * 2) :: { number }
for q = 1, n * 2 do
uv[q] = num(kc)
end
if n == nv then
table.insert(uvSets, uv)
end
elseif k.type == "MeshVertexColors" then
local n = count(kc, ctx.maxVertices)
local col = table.create(nv * 4, 1) :: { number }
for _ = 1, n do
local idx = index(kc, 2 ^ 32)
local r, g, b, a = num(kc), num(kc), num(kc), num(kc)
if idx < nv then
col[idx * 4 + 1], col[idx * 4 + 2], col[idx * 4 + 3], col[idx * 4 + 4] = r, g, b, a
end
end
table.insert(colors, col)
elseif k.type == "MeshMaterialList" then
num(kc) -- material count (the objects below are authoritative)
local ni = count(kc, ctx.maxVertices)
for q = 1, ni do
faceMat[q] = index(kc, 2 ^ 20)
end
for _, mk in k.kids do
if mk.type == "@ref" then
table.insert(mats, if mk.name then ctx.globalMats[mk.name] or 0 else 0)
elseif mk.type == "Material" then
table.insert(scene.materials, material(scene, mk, ctx.texCache))
table.insert(mats, #scene.materials)
end
end
elseif k.type == "SkinWeights" then
local name = str(kc)
local n = count(kc, ctx.maxVertices)
local verts = table.create(n) :: { number }
for q = 1, n do
verts[q] = index(kc, 2 ^ 32)
end
local weights = table.create(n) :: { number }
for q = 1, n do
weights[q] = num(kc)
end
table.insert(bones, { name = name, verts = verts, weights = weights, matrix = matrix(kc) })
end
end
-- material per face (a single index applies to every face)
local function matOf(f: number): number
local mi = if #faceMat == 1 then faceMat[1] else faceMat[f]
return if mi then mi + 1 else 1
end
-- unique vertices per (position, normal index)
local key: { [number]: number } = {}
local srcPos: { number } = {}
local srcNrm: { number } = {}
local groups: { [number]: { number } } = {}
local order: { number } = {}
local faceSizes: { [number]: { number } } = {}
local nNormals = if normals then #normals // 3 else 0
for f, face in faces do
local n = #face
if n < 3 then
ctx.skippedFaces += 1
else
local nface = nfaces and nfaces[f]
local vs = table.create(n) :: { number }
for k = 1, n do
local src = if k == 1 then 1 else n - k + 2 -- winding reversed, first corner kept
local p = face[src]
local q = if nface and nface[src] and nface[src] < nNormals then nface[src] else -1
local kk = p * (nNormals + 1) + q + 1
local v = key[kk]
if not v then
table.insert(srcPos, p)
table.insert(srcNrm, q)
v = #srcPos - 1
key[kk] = v
end
vs[k] = v
end
local mi = matOf(f)
local g = groups[mi]
if not g then
g = {}
groups[mi] = g
faceSizes[mi] = {}
table.insert(order, mi)
end
if triangulate then
for k = 2, n - 1 do
table.insert(g, vs[1])
table.insert(g, vs[k])
table.insert(g, vs[k + 1])
end
else
table.move(vs, 1, n, #g + 1, g)
table.insert(faceSizes[mi], n)
end
end
end
if #order == 0 then
return nil, nil
end
table.sort(order)
-- shared vertex attributes (one vertex buffer for every primitive of the mesh)
local nout = #srcPos
local P = table.create(nout * 3) :: { number }
for v = 1, nout do
local p = srcPos[v] * 3
P[v * 3 - 2], P[v * 3 - 1], P[v * 3] = pos[p + 1], pos[p + 2], -pos[p + 3]
end
local attributes: { [string]: Types.Accessor } = { POSITION = accessorF32(P, 3) }
if normals then
local N = table.create(nout * 3, 0) :: { number }
for v = 1, nout do
local q = srcNrm[v]
if q >= 0 then
N[v * 3 - 2], N[v * 3 - 1], N[v * 3] = normals[q * 3 + 1], normals[q * 3 + 2], -normals[q * 3 + 3]
end
end
attributes.NORMAL = accessorF32(N, 3)
end
for s, uv in uvSets do
local U = table.create(nout * 2) :: { number }
for v = 1, nout do
local p = srcPos[v] * 2
U[v * 2 - 1], U[v * 2] = uv[p + 1], uv[p + 2]
end
attributes["TEXCOORD_" .. (s - 1)] = accessorF32(U, 2)
end
for s, col in colors do
local C = table.create(nout * 4) :: { number }
for v = 1, nout do
local p = srcPos[v] * 4
C[v * 4 - 3], C[v * 4 - 2], C[v * 4 - 1], C[v * 4] = col[p + 1], col[p + 2], col[p + 3], col[p + 4]
end
attributes["COLOR_" .. (s - 1)] = accessorF32(C, 4)
end
if #bones > 0 then
local lists = table.create(nout) :: { { number } }
local byPos: { [number]: { number } } = {}
for j, bone in bones do
for q, vi in bone.verts do
local l = byPos[vi]
if not l then
l = {}
byPos[vi] = l
end
table.insert(l, j - 1)
table.insert(l, bone.weights[q] or 0)
end
end
for v = 1, nout do
lists[v] = byPos[srcPos[v]] or {}
end
attributes.JOINTS_0, attributes.WEIGHTS_0 = Rig.influences(lists)
end
local skinBones: Bones? = nil
if #bones > 0 then
local list: Bones = {}
for _, bone in bones do
table.insert(list, { name = bone.name, matrix = bone.matrix })
end
skinBones = list
end
local prims: { Types.Primitive } = {}
for _, mi in order do
local idx = groups[mi]
local ib = buffer.create(#idx * 4)
for k, x in idx do
writeu32(ib, (k - 1) * 4, x)
end
local prim: Types.Primitive = { attributes = attributes, indices = Scene.accessor(ib, "u32", 1, #idx), mode = "triangles" }
local mat = mats[mi]
prim.material = if mat and mat > 0 then mat else nil
if not triangulate then
prim.mode = "polygons"
local fs = faceSizes[mi]
local fb = buffer.create(#fs * 4)
for k, x in fs do
writeu32(fb, (k - 1) * 4, x)
end
prim.faces = Scene.accessor(fb, "u32", 1, #fs)
end
table.insert(prims, prim)
end
table.insert(scene.meshes, { name = m.name, primitives = prims })
return #scene.meshes, skinBones
end
-- ------------------------------------------------------------------------------------------------ frames
local function frame(ctx: Ctx, f: Node, parent: number?, triangulate: boolean, depth: number)
if depth > 200 then
error("frames nested too deep", 0)
end
local scene = ctx.scene
local node: Types.Node = { name = f.name, children = {} }
table.insert(scene.nodes, node)
local ni = #scene.nodes
if f.name and ctx.nodeByName[f.name] == nil then
ctx.nodeByName[f.name] = ni
end
if parent then
table.insert(scene.nodes[parent].children, ni)
else
table.insert(scene.roots, ni)
end
local first = true
for _, k in f.kids do
if k.type == "FrameTransformMatrix" then
local m = matrix({ v = k.vals, i = 1 })
local t, r, s = Mat4.decomposeStrict(m)
if t and r and s then
node.translation, node.rotation, node.scale = t, r, s
else
node.matrix = m
end
elseif k.type == "Mesh" then
-- the first mesh on the frame's node, more as child nodes
local mi, bones = mesh(ctx, k, triangulate)
if mi then
local holder = ni
if first then
node.mesh = mi
first = false
else
table.insert(scene.nodes, { name = k.name, children = {}, mesh = mi })
holder = #scene.nodes
table.insert(node.children, holder)
end
if bones then
table.insert(ctx.pendingSkins, { node = holder, bones = bones })
end
end
elseif k.type == "Frame" then
frame(ctx, k, ni, triangulate, depth + 1)
end
end
end
-- ------------------------------------------------------------------------------------------------ animations
local function channel(input: { number }, output: { number }, comps: number, node: number, path: string): Types.Channel
return { node = node, path = path :: any, input = accessorF32(input, 1), output = accessorF32(output, comps), interpolation = "LINEAR" }
end
local function animationSet(ctx: Ctx, set: Node, tps: number): Types.Animation?
local channels: { Types.Channel } = {}
for _, a in set.kids do
if a.type == "Animation" then
local target: string? = nil
for _, k in a.kids do
if k.type == "@ref" then
target = k.name
end
end
local node = target and ctx.nodeByName[target]
if node then
for _, k in a.kids do
if k.type == "AnimationKey" then
local c: Vals = { v = k.vals, i = 1 }
local kind = num(c)
local nk = count(c, ctx.maxVertices)
local times = table.create(nk) :: { number }
local T, R, S = {}, {}, {}
for q = 1, nk do
times[q] = num(c) / tps
local nvals = count(c, 16)
if kind == 0 and nvals == 4 then
local w, x, y, z = num(c), num(c), num(c), num(c)
-- the file's quaternion is the conjugate (row vectors); mirroring z negates x and y
table.move({ x, y, -z, w }, 1, 4, #R + 1, R)
elseif (kind == 1 or kind == 2) and nvals == 3 then
local x, y, z = num(c), num(c), num(c)
if kind == 1 then
table.move({ x, y, z }, 1, 3, #S + 1, S)
else
table.move({ x, y, -z }, 1, 3, #T + 1, T)
end
elseif (kind == 3 or kind == 4) and nvals == 16 then
local t, r, s = Mat4.decompose(matrix(c))
table.move(t, 1, 3, #T + 1, T)
table.move(r, 1, 4, #R + 1, R)
table.move(s, 1, 3, #S + 1, S)
else
error("bad animation key (type " .. kind .. ", " .. nvals .. " values)", 0)
end
end
if #T == nk * 3 and nk > 0 then
table.insert(channels, channel(times, T, 3, node, "translation"))
end
if #R == nk * 4 and nk > 0 then
table.insert(channels, channel(times, R, 4, node, "rotation"))
end
if #S == nk * 3 and nk > 0 then
table.insert(channels, channel(times, S, 3, node, "scale"))
end
end
end
end
end
end
if #channels == 0 then
return nil
end
return { name = set.name, channels = channels }
end
-- ------------------------------------------------------------------------------------------------ scene
function Build.scene(root: Node, opts: { triangulate: boolean?, maxVertices: number? }?): (Types.Scene?, string?)
local triangulate = not (opts and opts.triangulate == false)
local scene = Scene.new()
scene.meta.up = "y"
local ctx: Ctx = { scene = scene, globalMats = {}, texCache = {}, nodeByName = {}, pendingSkins = {}, maxVertices = opts and opts.maxVertices or 2 ^ 25, skippedFaces = 0 }
local tps = 4800
for _, k in root.kids do
if k.type == "Material" then
table.insert(scene.materials, material(scene, k, ctx.texCache))
if k.name then
ctx.globalMats[k.name] = #scene.materials
end
elseif k.type == "AnimTicksPerSecond" then
local v = k.vals[1]
if type(v) == "number" and v > 0 then
tps = v
end
end
end
for _, k in root.kids do
if k.type == "Frame" then
frame(ctx, k, nil, triangulate, 0)
elseif k.type == "Mesh" then
local mi, bones = mesh(ctx, k, triangulate)
table.insert(scene.nodes, { name = k.name, children = {}, mesh = mi })
table.insert(scene.roots, #scene.nodes)
if bones then
table.insert(ctx.pendingSkins, { node = #scene.nodes, bones = bones })
end
end
end
-- skins: bone names -> frames
for _, ps in ctx.pendingSkins do
local joints: { number } = {}
local ibm = buffer.create(#ps.bones * 64)
for j, bone in ps.bones do
local ni = ctx.nodeByName[bone.name]
if not ni then
-- a bone without a frame: an extra root node keeps the joint numbering
table.insert(scene.nodes, { name = bone.name, children = {} })
ni = #scene.nodes
table.insert(scene.roots, ni)
ctx.nodeByName[bone.name] = ni
end
joints[j] = ni
for k = 1, 16 do
writef32(ibm, ((j - 1) * 16 + k - 1) * 4, bone.matrix[k])
end
end
local acc = Scene.accessor(ibm, "f32", 16, #ps.bones)
acc.matrix = true
table.insert(scene.skins, { joints = joints, inverseBindMatrices = acc })
scene.nodes[ps.node].skin = #scene.skins
end
for _, k in root.kids do
if k.type == "AnimationSet" then
local anim = animationSet(ctx, k, tps)
if anim then
table.insert(scene.animations, anim)
end
end
end
scene.meta.source = { format = "x", ticksPerSecond = tps, skippedFaces = ctx.skippedFaces }
return scene, nil
end
return Build
+306
View File
@@ -0,0 +1,306 @@
--!strict
-- model/x/Parse: DirectX .x data -> a generic object tree, for the text ("txt ") and binary ("bin ") encodings (the
-- caller inflates "tzip" / "bzip" first). From Microsoft's "DirectX File Format Specification" (text grammar and
-- binary tokens), checked against what assimp's XFileParser accepts (no code taken).
-- Every data object becomes { type, name?, vals, kids }: vals holds its members flattened in order (numbers and
-- strings; separators, array brackets and member structure are not kept: model/x/Build knows each template's layout),
-- kids its nested data objects and references ({ name } -> { type = "@ref", name }). Templates are skipped.
-- Text: ; and , separators, // and # comments, quoted strings, <guid>s, Blender's "1.#IND00" / "1.#QNAN0" (read as 0).
-- Binary: NAME, STRING, INTEGER, GUID, INTEGER_LIST, FLOAT_LIST (32- or 64-bit floats) and the punctuation and
-- keyword tokens. Plain code (the caller wraps it in pcall); bad data returns nil, message.
local Parse = {}
export type Node = { type: string, name: string?, vals: { any }, kids: { Node } }
local readu16, readu32, readf32, readf64, readstring = buffer.readu16, buffer.readu32, buffer.readf32, buffer.readf64, buffer.readstring
-- a token source: next() -> kind, value. kinds: "{", "}", "id", "num", "str", "guid", "list" (value: { number }),
-- "punct", "eof"; err holds a message after a bad token
type Lexer = { next: () -> (string, any), err: string? }
local KEYWORDS: { [number]: string } = {
[0x1F] = "template",
[0x28] = "WORD",
[0x29] = "DWORD",
[0x2A] = "FLOAT",
[0x2B] = "DOUBLE",
[0x2C] = "CHAR",
[0x2D] = "UCHAR",
[0x2E] = "SWORD",
[0x2F] = "SDWORD",
[0x30] = "void",
[0x31] = "string",
[0x32] = "unicode",
[0x33] = "cstring",
[0x34] = "array",
}
-- ------------------------------------------------------------------------------------------------ text
local function textLexer(s: string): Lexer
local lex: Lexer = { next = nil :: any, err = nil }
local p = 1
local n = #s
lex.next = function(): (string, any)
while true do
local _, e = string.find(s, "^[%s,;]+", p)
if e then
p = e + 1
end
if p > n then
return "eof", nil
end
local c = string.byte(s, p)
if c == 47 and string.byte(s, p + 1) == 47 or c == 35 then -- // or #
local nl = string.find(s, "[\r\n]", p)
p = if nl then nl + 1 else n + 1
else
break
end
end
local c = string.byte(s, p)
if c == 123 then
p += 1
return "{", nil
elseif c == 125 then
p += 1
return "}", nil
elseif c == 34 then
local q = string.find(s, '"', p + 1, true)
if not q then
lex.err = "unterminated string"
p = n + 1
return "eof", nil
end
local v = string.sub(s, p + 1, q - 1)
p = q + 1
return "str", v
elseif c == 60 then
local q = string.find(s, ">", p + 1, true) or n
local v = string.sub(s, p + 1, q - 1)
p = q + 1
return "guid", v
end
local _, e = string.find(s, '^[^%s,;{}"]+', p)
local tok = string.sub(s, p, e :: number)
p = (e :: number) + 1
if (c >= 48 and c <= 57) or c == 45 or c == 43 or c == 46 then
return "num", tonumber(tok) or 0
end
return "id", tok
end
return lex
end
-- ------------------------------------------------------------------------------------------------ binary
local function binaryLexer(b: buffer, from: number, limit: number, floatSize: number): Lexer
local lex: Lexer = { next = nil :: any, err = nil }
local p = from
local function fail(msg: string): (string, any)
lex.err = msg
p = limit
return "eof", nil
end
lex.next = function(): (string, any)
if p + 2 > limit then
return "eof", nil
end
local tok = readu16(b, p)
p += 2
if tok == 0x0A then
return "{", nil
elseif tok == 0x0B then
return "}", nil
elseif tok == 1 or tok == 2 then -- NAME / STRING: u32 count, bytes (STRING: then a ; or , token)
if p + 4 > limit then
return fail("truncated name")
end
local len = readu32(b, p)
p += 4
if len > limit - p then
return fail("truncated name")
end
local v = readstring(b, p, len)
p += len
if tok == 2 then
p = math.min(p + 2, limit)
return "str", v
end
return "id", v
elseif tok == 3 then
if p + 4 > limit then
return fail("truncated integer")
end
local v = readu32(b, p)
p += 4
return "num", v
elseif tok == 5 then
if p + 16 > limit then
return fail("truncated guid")
end
p += 16
return "guid", ""
elseif tok == 6 or tok == 7 then
if p + 4 > limit then
return fail("truncated list")
end
local count = readu32(b, p)
p += 4
local size = if tok == 6 then 4 else floatSize
if count > (limit - p) // size then
return fail("truncated list")
end
local out = table.create(count) :: { number }
if tok == 6 then
for i = 1, count do
out[i] = readu32(b, p)
p += 4
end
elseif size == 8 then
for i = 1, count do
out[i] = readf64(b, p)
p += 8
end
else
for i = 1, count do
out[i] = readf32(b, p)
p += 4
end
end
return "list", out
elseif tok >= 0x0C and tok <= 0x14 then
return "punct", nil
elseif KEYWORDS[tok] then
return "id", KEYWORDS[tok]
end
return fail(string.format("unknown binary token 0x%x", tok))
end
return lex
end
-- ------------------------------------------------------------------------------------------------ tree
local function tree(lex: Lexer, maxValues: number): (Node?, string?)
local queue: { { any } } = {}
local function take(): (string, any)
local q = table.remove(queue, 1)
if q then
return q[1], q[2]
end
return lex.next()
end
local function peek(k: number): string
while #queue < k do
local kind, v = lex.next()
table.insert(queue, { kind, v })
if kind == "eof" then
break
end
end
local q = queue[k]
return if q then q[1] else "eof"
end
local budget = maxValues
-- skips a template / unknown block whose "{" was just read
local function skipBlock(): string?
local depth = 1
while depth > 0 do
local kind = take()
if kind == "eof" then
return "unexpected end of file in a template"
elseif kind == "{" then
depth += 1
elseif kind == "}" then
depth -= 1
end
end
return nil
end
local body: (Node, number) -> string?
-- an object whose type token was read: [name] { ... }
local function object(parent: Node, typ: string, depth: number): string?
local name: string? = nil
local kind, v = take()
if kind ~= "{" then
name = if v ~= nil then tostring(v) else nil
kind = take()
if kind ~= "{" then
return "expected { after " .. typ
end
end
if typ == "template" then
return skipBlock()
end
local node: Node = { type = typ, name = name, vals = {}, kids = {} }
table.insert(parent.kids, node)
return body(node, depth + 1)
end
body = function(node: Node, depth: number): string?
if depth > 200 then
return "objects nested too deep"
end
local vals = node.vals
while true do
local kind, v = take()
if kind == "}" then
return nil
elseif kind == "eof" then
return if depth == 0 then nil else "unexpected end of file in " .. node.type
elseif kind == "num" or kind == "str" then
budget -= 1
if budget < 0 then
return "limit: more than " .. maxValues .. " values"
end
vals[#vals + 1] = v
elseif kind == "list" then
budget -= #v
if budget < 0 then
return "limit: more than " .. maxValues .. " values"
end
table.move(v, 1, #v, #vals + 1, vals)
elseif kind == "{" then
-- a reference: { name [guid] }
local ref: Node = { type = "@ref", name = nil, vals = {}, kids = {} }
while true do
local k2, v2 = take()
if k2 == "}" then
break
elseif k2 == "eof" then
return "unexpected end of file in a reference"
elseif (k2 == "id" or k2 == "num") and ref.name == nil then
ref.name = tostring(v2)
end
end
table.insert(node.kids, ref)
elseif kind == "id" then
local k1 = peek(1)
if k1 == "{" or (k1 ~= "eof" and k1 ~= "}" and peek(2) == "{") then
local err = object(node, v, depth)
if err then
return err
end
end
-- a lone identifier (an enum value): ignored
end
-- guid / punct: ignored
if lex.err then
return lex.err
end
end
end
local root: Node = { type = "@root", name = nil, vals = {}, kids = {} }
local err = body(root, 0)
if err then
return nil, err
end
if lex.err then
return nil, lex.err
end
return root, nil
end
-- parse(b, from, limit, binary, floatSize, maxValues) -> root Node | nil, message
function Parse.tree(b: buffer, from: number, limit: number, binary: boolean, floatSize: number, maxValues: number): (Node?, string?)
local lex = if binary then binaryLexer(b, from, limit, floatSize) else textLexer(readstring(b, from, limit - from))
return tree(lex, maxValues)
end
return Parse
+152
View File
@@ -0,0 +1,152 @@
--!strict
-- model/x: DirectX .x files, read only: text ("txt "), binary ("bin ") and MSZIP-compressed ("tzip" / "bzip",
-- through codecs/compress/Deflate), 32- and 64-bit floats. New code from Microsoft's DirectX file format
-- specification and the standard templates, checked against assimp's X importer and test models.
-- Reads the Frame hierarchy (FrameTransformMatrix -> TRS, or a matrix when it has shear), meshes (one primitive per
-- material of MeshMaterialList; MeshNormals with their own face indices (vertices split per position / normal
-- pair), MeshTextureCoords -> TEXCOORD_n, MeshVertexColors -> COLOR_n), materials (inline or referenced global
-- Material objects: face colour -> baseColor, power -> roughness, emissive; TextureFilename -> baseColorTexture,
-- NormalmapFilename -> normalTexture, as uris: F.model.loadTextures reads them; the Phong values in extras.x),
-- SkinWeights (-> a skin per mesh: joints = the named frames, offset matrices as inverse bind matrices, the four
-- strongest influences as JOINTS_0 / WEIGHTS_0) and AnimationSet / Animation / AnimationKey (rotation, scale,
-- position and matrix keys -> channels, AnimTicksPerSecond (default 4800) -> seconds). Templates are skipped.
-- Direct3D's left-handed space becomes glTF's right-handed y up (z negated, winding reversed), as assimp does.
-- Polygons are fan-triangulated unless opts.triangulate = false. Faces of fewer than 3 corners are skipped (counted in
-- meta.source.skippedFaces).
-- Not supported: DeclData / FVFData vertex streams, progressive meshes, patch meshes, 3- and 2-corner key
-- interpolation options (keys are linear).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Deflate = require("@formats/codecs/compress/Deflate")
local Parse = require("@formats/model/x/Parse")
local Build = require("@formats/model/x/Build")
-- ------------------------------------------------------------------------------------------------ contract
local X = {
name = "x",
category = "model",
extensions = { "x" },
mime = { "model/x-directx", "text/x-directx" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/compress/Deflate", "codecs/model/Mat4", "codecs/model/Rig" },
caps = { decode = true, encode = false, text = true, binary = true, compressed = true, materials = true, skins = true, animation = true, polygons = true, vertexColors = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives
maxVertices: number?, -- refuse more vertices / face corners per mesh (default 2^25)
maxValues: number?, -- refuse files with more numbers than this (default 2^27)
maxBytes: number?, -- refuse compressed files inflating to more (default 2^30)
}
-- ------------------------------------------------------------------------------------------------ constants
local ENCODINGS = { ["txt "] = "text", ["bin "] = "binary", tzip = "text", bzip = "binary" }
local WINDOW = 32768
-- ------------------------------------------------------------------------------------------------ sniff
function X.sniff(r: Bytes.Reader): number
if r:peek(4) ~= "xof " then
return 0
end
return if ENCODINGS[r:peek(4, 8)] then 1 else 0.5
end
-- ------------------------------------------------------------------------------------------------ decode
-- MSZIP: a u32 total size (with the header), then blocks (u16 uncompressed size, u16 compressed size, "CK", deflate data); each block
-- may refer back into the previous block's output. That history is handed to the inflater as a stored block in
-- front of the compressed one (both start on a byte boundary), and cut off the output again.
local function mszip(b: buffer, p: number, limit: number, maxBytes: number): (buffer?, Err.Err?)
if p + 4 > limit then
return nil, Err.new(Err.TRUNCATED, "no MSZIP header", p)
end
local total = math.max(buffer.readu32(b, p) - 16, 0) -- the size counts the 16-byte header
if total > maxBytes then
return nil, Err.new(Err.LIMIT, "inflates to " .. total .. " bytes", p)
end
p += 4
local out = buffer.create(total)
local o = 0
while p + 6 <= limit and o < total do
local usize, csize = buffer.readu16(b, p), buffer.readu16(b, p + 2)
if buffer.readstring(b, p + 4, 2) ~= "CK" or csize < 2 then
return nil, Err.new(Err.CORRUPT, "bad MSZIP block", p)
end
local data, dlen = p + 6, math.min(csize - 2, limit - p - 6)
local hist = math.min(o, WINDOW)
local src = buffer.create(5 + hist + dlen)
buffer.writeu8(src, 0, 0) -- BFINAL 0, stored
buffer.writeu16(src, 1, hist)
buffer.writeu16(src, 3, bit32.bxor(hist, 0xFFFF))
buffer.copy(src, 5, out, o - hist, hist)
buffer.copy(src, 5 + hist, b, data, dlen)
local inflated, err = Deflate.inflate(src)
if not inflated then
return nil, Err.new(err.code, "MSZIP block: " .. err.message, p)
end
local got = buffer.len(inflated) - hist
if got ~= usize or o + got > total then
return nil, Err.new(Err.CORRUPT, "MSZIP block size mismatch", p)
end
buffer.copy(out, o, inflated, hist, got)
o += got
p = data + csize - 2
end
if o < total then
return nil, Err.new(Err.TRUNCATED, "MSZIP data ends early", p)
end
return out, nil
end
function X.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local b, base, limit = r.buf, r.base, r.limit
if limit - base < 16 then
return nil, Err.new(Err.TRUNCATED, "shorter than the header", base)
end
if buffer.readstring(b, base, 4) ~= "xof " then
return nil, Err.new(Err.CORRUPT, "no xof header", base)
end
local enc = buffer.readstring(b, base + 8, 4)
local kind = ENCODINGS[enc]
if not kind then
return nil, Err.new(Err.UNSUPPORTED, "encoding " .. string.format("%q", enc), base + 8)
end
local bits = buffer.readstring(b, base + 12, 4)
local floatSize = if bits == "0064" then 8 elseif bits == "0032" then 4 else 0
if floatSize == 0 then
return nil, Err.new(Err.CORRUPT, "float size " .. string.format("%q", bits), base + 12)
end
local data: buffer, from: number, to: number = b, base + 16, limit
if enc == "tzip" or enc == "bzip" then
local inflated, err = mszip(b, base + 16, limit, opts and opts.maxBytes or 2 ^ 30)
if not inflated then
return nil, err
end
data, from, to = inflated, 0, buffer.len(inflated)
end
local maxValues: number = opts and opts.maxValues or 2 ^ 27
local ok, root, msg = pcall(Parse.tree, data, from, to :: number, kind == "binary", floatSize, maxValues)
if not ok then
return nil, Err.new(Err.CORRUPT, "bad data: " .. tostring(root))
end
if not root then
return nil, Err.from(msg)
end
local ok2, scene, msg2 = pcall(Build.scene, root, opts)
if not ok2 then
return nil, Err.from(tostring(scene))
end
if not scene then
return nil, Err.from(msg2)
end
local src = scene.meta.source :: { [string]: any }
src.version = buffer.readstring(b, base + 4, 4)
src.encoding = kind
src.compressed = enc == "tzip" or enc == "bzip"
src.floatSize = floatSize * 8
return scene, nil
end
return X
+85
View File
@@ -0,0 +1,85 @@
--!strict
-- model/x3d: X3D (ISO/IEC 19775-1) in its XML encoding (.x3d, ISO/IEC 19776-1) and its classic VRML encoding (.x3dv,
-- 19776-2), plain or gzipped (.x3dz / .x3dvz), a thin format over codecs/model/Vrml (the engine model/vrml shares).
-- New code.
-- Reads: everything model/vrml reads, plus the X3D nodes: IndexedTriangleSet, TriangleSet, IndexedTriangleFanSet,
-- TriangleFanSet, IndexedTriangleStripSet, TriangleStripSet, IndexedQuadSet, QuadSet, LineSet, ColorRGBA,
-- CoordinateDouble, MultiTexture / MultiTextureCoordinate (the first), PhysicalMaterial / UnlitMaterial /
-- TwoSidedMaterial, OrthoViewpoint, CAD groups; XML ProtoDeclare / ProtoInstance, ROUTE elements, containerField;
-- head meta, components and UNIT length (-> meta.unit).
-- Writes: X3D 3.3 XML (default) or the classic encoding (opts.encoding = "x3dv"; the api passes the extension), the
-- same scene graph as model/vrml writes (ColorRGBA for colours with alpha, OrthoViewpoint for orthographic cameras).
-- Not supported: the binary encodings (.x3db Fast Infoset / EXI: UNSUPPORTED), X3D JSON, Text, NURBS, shaders,
-- H-Anim skinning, scripts.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Vrml = require("@formats/codecs/model/Vrml")
-- ------------------------------------------------------------------------------------------------ contract
local X3d = {
name = "x3d",
category = "model",
extensions = { "x3d", "x3dv", "x3dz", "x3dvz", "x3db" },
mime = { "model/x3d+xml", "model/x3d-vrml", "model/x3d+fastinfoset" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/model/Vrml" },
caps = { decode = true, encode = true, materials = true, polygons = true, animation = true, cameras = true, lights = true, lines = true, points = true, xml = true, classic = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
files: { [string]: any }?, -- textures / Inline files by uri or base name (buffer or string)
resolve: ((uri: string) -> any)?, -- or: reads them (the api sets it for paths)
triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives
flipV: boolean?, -- texture t -> 1 - t (default true: glTF's convention)
segments: number?, -- Sphere / Cone / Cylinder segments around (default 32)
maxVertices: number?, -- per geometry (default 2^24)
}
export type EncodeOptions = {
encoding: ("xml" | "x3dv")?, -- default "xml"
format: string?, -- the api passes the extension: "x3dv" / "x3dvz" select the classic encoding
files: { [string]: any }?, -- receives the texture images (else url = texture.uri)
name: string?, -- the destination's file name (names the image files)
flipV: boolean?, -- default true (the inverse of decode)
}
-- ------------------------------------------------------------------------------------------------ sniff
function X3d.sniff(r: Bytes.Reader): number
local head = r:peek(1024)
if string.sub(head, 1, 3) == "\239\187\191" then
head = string.sub(head, 4)
end
if string.sub(head, 1, 5) == "#X3D " then
return 1
end
if string.sub(head, 1, 4) == "\224\0\0\1" and string.find(head, "x3d", 1, true) then
return 0.9
end
if string.find(head, "<X3D[%s>]") or string.find(head, "<!DOCTYPE X3D", 1, true) then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function X3d.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local o: any = table.clone(opts or {})
o.format = "x3d"
return Vrml.decode(buffer.readstring(r.buf, r.base, r.limit - r.base), o)
end
-- ------------------------------------------------------------------------------------------------ encode
function X3d.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
local o: any = table.clone(opts or {})
local classic = o.encoding == "x3dv" or o.format == "x3dv" or o.format == "x3dvz"
o.encoding = if classic then "x3dv" else "xml"
local text, err = Vrml.encode(scene, o)
if not text then
return nil, err
end
return buffer.fromstring(text), nil
end
return X3d