Files
rosetta/src/Rosetta/model/gltf/init.luau
T

236 lines
8.0 KiB
Luau

--!strict
-- model/gltf: glTF 2.0 (Khronos specification 2.0.1), .gltf JSON and .glb. Supports: the core spec, KHR_materials_*,
-- KHR_texture_transform, KHR_lights_punctual, KHR_mesh_quantization, KHR_draco_mesh_compression (written uncompressed).
-- Not supported: EXT_meshopt_compression (UNSUPPORTED), KHR_animation_pointer channels (skipped).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Sniff = require("@rosetta/core/Sniff")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Json = require("@rosetta/codecs/text/Json")
local Base64 = require("@rosetta/core/Base64")
local Read = require("@rosetta/model/gltf/Read")
local Write = require("@rosetta/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/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
export type DecodeOptions = {
resolve: ((uri: string) -> any)?, -- external .bin / image files (buffer or string)
files: { [string]: any }?,
maxBytes: number?, -- default 2^30 bytes of buffers / accessors
}
export type EncodeOptions = {
binary: boolean?, -- default: when opts.format is "glb"
format: string?,
external: boolean?, -- default false: data: URIs
files: { [string]: any }?, -- receives <name>.bin and images with external = true
name: string?,
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 = Sniff.dropBom(head)
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
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: { [string]: string } = { ["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
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