Files
rosetta/src/Formats/model/gltf/init.luau
T
4DBugandClaude Opus 5.5 a25b7c0caa ws-cleanup: one base64 (core/Base64)
core/Base64 takes over codecs/Base64's API (encode(buf | string, { url, pad, wrap }, offset, length), decode of both
alphabets, decodeDataUri, dataUri) plus line wrapping (opts.wrap) for plist; codecs/Base64 is removed and glTF /
DAE require core/Base64. The private copies in data/plist (Base64.luau), data/yaml (Parse / Emit) and codecs/Brotli
(the static tables) are gone. tests/codecs/base64 merged into tests/core/base64.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-31 10:50:40 -05:00

249 lines
9.5 KiB
Luau

--!strict
-- model/gltf: glTF 2.0 (Khronos specification 2.0.1), JSON (.gltf with embedded data: URIs or external files) and
-- binary (.glb). New code.
-- Reads: scenes, the node tree (TRS / matrix), meshes (every primitive mode, morph targets), accessors of every
-- component type (normalized -> unorm / snorm, sparse, byte strides, padded matrix columns, no bufferView), PBR
-- materials + the KHR_materials_* extensions (emissive_strength, unlit, clearcoat, transmission, volume, ior,
-- specular, sheen, iridescence, anisotropy, dispersion, diffuse_transmission, pbrSpecularGlossiness: their fields kept,
-- textureInfo objects as TextureRefs), KHR_texture_transform, textures + samplers + images (kept encoded: bytes + mime,
-- or the uri; KHR_texture_basisu / EXT_texture_webp / EXT_texture_avif sources), cameras, KHR_lights_punctual, skins,
-- animations, KHR_mesh_quantization, extras and unknown extensions (written back). Images are never decoded here (a
-- format does not require another format): F.model.loadTextures(scene) decodes them at the api layer.
-- 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).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Json = require("@formats/codecs/Json")
local Base64 = require("@formats/core/Base64")
local Read = require("@formats/model/gltf/Read")
local Write = require("@formats/model/gltf/Write")
-- ------------------------------------------------------------------------------------------------ contract
local Gltf = {
name = "gltf",
category = "model",
extensions = { "gltf", "glb" },
mime = { "model/gltf+json", "model/gltf-binary" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Json", "core/Base64" },
caps = { decode = true, encode = true, binary = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
resolve: ((uri: string) -> any)?, -- external .bin / image files (buffer or string); the api sets it for paths
files: { [string]: any }?, -- or: the files by uri
maxBytes: number?, -- refuse buffers / accessors over this many bytes in total (default 2^30)
}
export type EncodeOptions = {
binary: boolean?, -- write GLB (default: when opts.format is "glb")
format: string?, -- "glb" -> binary (set by the api from the destination's extension)
external: boolean?, -- .gltf: write the buffer and images as files into opts.files (default false: data: URIs)
files: { [string]: any }?, -- receives <name>.bin and images with external = true
name: string?, -- the destination's file name (names the external files)
embedImages: boolean?, -- default true (false with external = true)
}
-- ------------------------------------------------------------------------------------------------ constants
local GLB_MAGIC = 0x46546C67 -- "glTF"
local CHUNK_JSON = 0x4E4F534A
local CHUNK_BIN = 0x004E4942
-- ------------------------------------------------------------------------------------------------ sniff
function Gltf.sniff(r: Bytes.Reader): number
if r:peek(4) == "glTF" then
return 1
end
local head = r:peek(1024)
local s = string.gsub(head, "^\239\187\191", "")
if string.find(s, "^%s*{") and string.find(s, "\"asset\"", 1, true) then
return 0.9
end
if string.find(s, "^%s*{") and (string.find(s, "\"accessors\"", 1, true) or string.find(s, "\"bufferViews\"", 1, true)) then
return 0.6
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function fetcher(opts: DecodeOptions?): Read.Fetch
return function(uri: string): buffer?
if not opts then
return nil
end
local decoded = string.gsub(uri, "%%(%x%x)", function(h: string): string
return string.char(tonumber(h, 16) :: number)
end)
local v: any = nil
if type(opts.files) == "table" then
v = opts.files[uri] or opts.files[decoded]
end
if v == nil and type(opts.resolve) == "function" then
local ok, res = pcall(opts.resolve, uri)
v = if ok then res else nil
end
if type(v) == "string" then
return buffer.fromstring(v)
end
return if type(v) == "buffer" then v else nil
end
end
-- the JSON text and BIN chunk of a GLB
local function glb(r: Bytes.Reader): (string?, buffer?, Err.Err?)
local magic, version, length = r:u32le(), r:u32le(), r:u32le()
if r.err then
return nil, nil, r.err
end
if magic ~= GLB_MAGIC then
return nil, nil, Err.new(Err.CORRUPT, "bad GLB magic")
end
if version ~= 2 then
return nil, nil, Err.new(Err.UNSUPPORTED, "GLB version " .. version)
end
if length > r:size() then
return nil, nil, Err.new(Err.TRUNCATED, "the GLB is shorter than its header says", r.base + 8)
end
local json: string? = nil
local bin: buffer? = nil
while r:tell() + 8 <= length do
local clen, ctype = r:u32le(), r:u32le()
if clen > length - r:tell() then
return nil, nil, Err.new(Err.TRUNCATED, "a GLB chunk runs past the end", r.base + r:tell() - 8)
end
if ctype == CHUNK_JSON and json == nil then
json = r:string(clen)
elseif ctype == CHUNK_BIN and bin == nil and json ~= nil then
bin = r:bytes(clen)
else
r:skip(clen)
end
if r.err then
return nil, nil, r.err
end
end
if not json then
return nil, nil, Err.new(Err.CORRUPT, "GLB without a JSON chunk")
end
return json, bin, nil
end
function Gltf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local binary = r:peek(4) == "glTF"
local text: string?, bin: buffer?
if binary then
local t, b, err = glb(r)
if not t then
return nil, err
end
text, bin = t, b
else
text = buffer.readstring(r.buf, r.base, r.limit - r.base)
end
local doc, jerr = Json.decode(text :: string)
if doc == nil then
return nil, jerr
end
local scene, err = Read.scene(doc, bin, fetcher(opts), opts)
if not scene then
return nil, err
end
scene.meta.source = { format = "gltf", binary = binary, generator = type(doc.asset) == "table" and doc.asset.generator or nil }
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif" }
function Gltf.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 binary = opts and (opts.binary or opts.format == "glb") or false
local external = opts and opts.external == true and type(opts.files) == "table" and not binary
local embedImages = if opts and opts.embedImages ~= nil then opts.embedImages else not external
local out, err = Write.build(scene, { binary = binary, embedImages = embedImages })
if not out then
return nil, err
end
local doc = out.doc
local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model"
local files = opts and opts.files
-- images: data: URIs, or files
if doc.images then
local n = 0
for _, im in doc.images do
if type(im.uri) == "string" and string.sub(im.uri, 1, 1) == "\0" then
for _, o in out.images do
if o.name == im.uri then
if string.sub(im.uri, 1, 6) == "\0image" or type(files) ~= "table" then
im.uri = Base64.dataUri(o.data, o.mime or "image/png")
else
n += 1
local fname = base .. "_" .. n .. "." .. (EXT[o.mime or ""] or "png")
files[fname] = o.data
im.uri = fname
end
break
end
end
elseif type(im.uri) == "string" and type(files) == "table" and not embedImages then
for _, o in out.images do
if o.name == im.uri then
files[im.uri] = o.data
end
end
end
end
end
local binLen = buffer.len(out.bin)
if binLen > 0 then
local b = Types.object()
b.byteLength = binLen
if not binary then
if external then
local fname = base .. ".bin"
b.uri = fname
local ff: any = files
ff[fname] = out.bin
else
b.uri = Base64.dataUri(out.bin, "application/octet-stream")
end
end
doc.buffers = { b }
end
local text, jerr = Json.encode(doc, if binary then nil else { indent = 2 })
if not text then
return nil, Err.new(Err.ARG, "JSON: " .. tostring(jerr and jerr.message or jerr))
end
if not binary then
return buffer.fromstring(text :: string), nil
end
local jpad = (4 - #(text :: string) % 4) % 4
local bpad = (4 - binLen % 4) % 4
local w = Bytes.writer(12 + 8 + #(text :: string) + jpad + 8 + binLen + bpad)
w:u32le(GLB_MAGIC)
w:u32le(2)
local lenAt = w:tell()
w:u32le(0)
w:u32le(#(text :: string) + jpad)
w:u32le(CHUNK_JSON)
w:string(text :: string)
w:string(string.rep(" ", jpad))
if binLen > 0 then
w:u32le(binLen + bpad)
w:u32le(CHUNK_BIN)
w:bytes(out.bin)
w:fill(0, bpad)
end
w:setU32le(lenAt, w:tell())
return w:finish(), nil
end
return Gltf