Files
rosetta/src/Formats/codecs/model/Draco/init.luau
T
4DBug 4f2a388a6d ws-3d3: codecs/model/Draco: kd-tree point clouds (bitstream 2.3, levels 0 - 6)
Byte-exact against libdraco on all 206 test files, kd-tree point clouds included.
2026-10-31 14:34:06 -05:00

354 lines
11 KiB
Luau

--!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