740 lines
27 KiB
Luau
740 lines
27 KiB
Luau
--!strict
|
|
-- model/gltf/Read: a parsed glTF 2.0 JSON document (+ its buffers) -> Scene. glTF extras and unhandled extensions are
|
|
-- kept in <object>.extras.gltf = { extras, extensions }.
|
|
local Err = require("@rosetta/core/Err")
|
|
local Types = require("@rosetta/Types")
|
|
local Base64 = require("@rosetta/core/Base64")
|
|
local Pack = require("@rosetta/model/gltf/Pack")
|
|
local Draco = require("@rosetta/codecs/model/Draco")
|
|
|
|
local Read = {}
|
|
|
|
local COMPONENT: { [number]: { string } } = {
|
|
[5120] = { "i8", "snorm8" },
|
|
[5121] = { "u8", "unorm8" },
|
|
[5122] = { "i16", "snorm16" },
|
|
[5123] = { "u16", "unorm16" },
|
|
[5125] = { "u32", "" },
|
|
[5126] = { "f32", "" },
|
|
}
|
|
local SIZE = { [5120] = 1, [5121] = 1, [5122] = 2, [5123] = 2, [5125] = 4, [5126] = 4 }
|
|
local TYPE_COMPONENTS = { SCALAR = 1, VEC2 = 2, VEC3 = 3, VEC4 = 4, MAT2 = 4, MAT3 = 9, MAT4 = 16 }
|
|
local TYPE_COLUMNS = { MAT2 = 2, MAT3 = 3, MAT4 = 4 }
|
|
local MODES = { [0] = "points", [1] = "lines", [2] = "line_loop", [3] = "line_strip", [4] = "triangles", [5] = "triangle_strip", [6] = "triangle_fan" }
|
|
local WRAP: { [number]: "clamp" | "mirror" | "repeat" } = { [33071] = "clamp", [33648] = "mirror", [10497] = "repeat" }
|
|
local MIN_FILTER = { [9728] = "nearest", [9729] = "linear", [9984] = "nearest_mipmap_nearest", [9985] = "linear_mipmap_nearest", [9986] = "nearest_mipmap_linear", [9987] = "linear_mipmap_linear" }
|
|
-- the extensions this reader understands (any other required one -> UNSUPPORTED)
|
|
local KNOWN = {
|
|
KHR_lights_punctual = true,
|
|
KHR_mesh_quantization = true,
|
|
KHR_texture_transform = true,
|
|
KHR_materials_emissive_strength = true,
|
|
KHR_materials_unlit = true,
|
|
KHR_materials_clearcoat = true,
|
|
KHR_materials_transmission = true,
|
|
KHR_materials_volume = true,
|
|
KHR_materials_ior = true,
|
|
KHR_materials_specular = true,
|
|
KHR_materials_sheen = true,
|
|
KHR_materials_iridescence = true,
|
|
KHR_materials_anisotropy = true,
|
|
KHR_materials_dispersion = true,
|
|
KHR_materials_diffuse_transmission = true,
|
|
KHR_materials_variants = true,
|
|
KHR_materials_pbrSpecularGlossiness = true,
|
|
KHR_texture_basisu = true, -- the image stays encoded (image/ktx2)
|
|
EXT_texture_webp = true,
|
|
EXT_texture_avif = true,
|
|
KHR_node_visibility = true,
|
|
KHR_xmp_json_ld = true,
|
|
KHR_draco_mesh_compression = true,
|
|
}
|
|
Read.KNOWN = KNOWN
|
|
|
|
export type Fetch = (uri: string) -> buffer?
|
|
type View = { buf: buffer, offset: number, length: number, stride: number? }
|
|
type Img = { data: buffer?, mime: string?, uri: string?, name: string? }
|
|
|
|
local function num(v: any, default: number): number
|
|
return if type(v) == "number" then v else default
|
|
end
|
|
local function int(v: any): number?
|
|
return if type(v) == "number" and v == math.floor(v) and v >= 0 then v else nil
|
|
end
|
|
local function arr(v: any): { any }
|
|
return if type(v) == "table" then v else {}
|
|
end
|
|
local function str(v: any): string?
|
|
return if type(v) == "string" then v else nil
|
|
end
|
|
local function numbers(v: any, n: number): { number }?
|
|
if type(v) ~= "table" or #v ~= n then
|
|
return nil
|
|
end
|
|
for i = 1, n do
|
|
if type(v[i]) ~= "number" then
|
|
return nil
|
|
end
|
|
end
|
|
return table.move(v, 1, n, 1, {} :: { number })
|
|
end
|
|
|
|
local function keep(obj: any, handled: { [string]: boolean }?): { [string]: any }?
|
|
local extras = obj.extras
|
|
local ext: { [string]: any }? = nil
|
|
if type(obj.extensions) == "table" then
|
|
for k, v in obj.extensions do
|
|
if not (handled and handled[k]) then
|
|
ext = ext or {}
|
|
local e: any = ext
|
|
e[k] = v
|
|
end
|
|
end
|
|
end
|
|
if extras == nil and ext == nil then
|
|
return nil
|
|
end
|
|
return { gltf = { extras = extras, extensions = ext } }
|
|
end
|
|
|
|
-- a Draco attribute as its glTF accessor's type: bytes as they are when the layouts agree, else value by value
|
|
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
|
|
return nil, Err.new(Err.CORRUPT, "the JSON is not an object")
|
|
end
|
|
local asset = doc.asset
|
|
if type(asset) ~= "table" or type(asset.version) ~= "string" then
|
|
return nil, Err.new(Err.CORRUPT, "no asset.version")
|
|
end
|
|
if string.sub(asset.version, 1, 1) ~= "2" then
|
|
return nil, Err.new(Err.UNSUPPORTED, "glTF version " .. asset.version .. " (only 2.x)")
|
|
end
|
|
for _, e in arr(doc.extensionsRequired) do
|
|
if type(e) == "string" and not KNOWN[e] then
|
|
return nil, Err.new(Err.UNSUPPORTED, "required extension " .. e)
|
|
end
|
|
end
|
|
local scene = Types.Scene.new()
|
|
local buffers: { buffer } = {}
|
|
local total = 0
|
|
for i, b in arr(doc.buffers) do
|
|
if type(b) ~= "table" then
|
|
return nil, Err.new(Err.CORRUPT, "bad buffer " .. (i - 1))
|
|
end
|
|
local len = int(b.byteLength)
|
|
if not len then
|
|
return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. " without byteLength")
|
|
end
|
|
total += len
|
|
if total > maxBytes then
|
|
return nil, Err.new(Err.LIMIT, "buffers over " .. maxBytes .. " bytes")
|
|
end
|
|
local data: buffer? = nil
|
|
local uri = str(b.uri)
|
|
if uri == nil then
|
|
if i == 1 and bin then
|
|
data = bin
|
|
else
|
|
return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. " has no uri and no GLB BIN chunk")
|
|
end
|
|
elseif string.sub(uri, 1, 5) == "data:" then
|
|
local d, derr = Base64.decodeDataUri(uri)
|
|
if not d then
|
|
return nil, Err.new(Err.CORRUPT, "buffer " .. (i - 1) .. ": " .. tostring(derr))
|
|
end
|
|
data = d
|
|
else
|
|
data = fetch(uri)
|
|
if not data then
|
|
return nil, Err.new(Err.IO, "buffer file " .. uri .. " not found (pass opts.resolve or opts.files)")
|
|
end
|
|
end
|
|
if buffer.len(data :: buffer) < len then
|
|
return nil, Err.new(Err.TRUNCATED, "buffer " .. (i - 1) .. " is shorter than its byteLength")
|
|
end
|
|
buffers[i] = data :: buffer
|
|
end
|
|
-- buffer views -> { buf, offset, length, stride }
|
|
local views: { View } = {}
|
|
for i, v in arr(doc.bufferViews) do
|
|
if type(v) ~= "table" then
|
|
return nil, Err.new(Err.CORRUPT, "bad bufferView " .. (i - 1))
|
|
end
|
|
local bi, off, len = int(v.buffer), int(v.byteOffset or 0), int(v.byteLength)
|
|
local b = bi and buffers[bi + 1]
|
|
if not b or not off or not len or off + len > buffer.len(b) then
|
|
return nil, Err.new(Err.CORRUPT, "bufferView " .. (i - 1) .. " out of range")
|
|
end
|
|
local stride = v.byteStride
|
|
if stride ~= nil and (not int(stride) or stride < 4 or stride > 252) then
|
|
return nil, Err.new(Err.CORRUPT, "bufferView " .. (i - 1) .. ": bad byteStride")
|
|
end
|
|
views[i] = { buf = b, offset = off, length = len, stride = stride }
|
|
end
|
|
local accessors: { Types.Accessor } = {}
|
|
for i, a in arr(doc.accessors) do
|
|
local label = "accessor " .. (i - 1)
|
|
if type(a) ~= "table" then
|
|
return nil, Err.new(Err.CORRUPT, "bad " .. label)
|
|
end
|
|
local ct, count, typ = a.componentType, int(a.count), a.type
|
|
local names = COMPONENT[ct]
|
|
local comps = TYPE_COMPONENTS[typ]
|
|
if not names or not count or not comps then
|
|
return nil, Err.new(Err.CORRUPT, label .. ": bad componentType, count or type")
|
|
end
|
|
local normalized = a.normalized == true
|
|
local tname = if normalized then names[2] else names[1]
|
|
if tname == "" then
|
|
return nil, Err.new(Err.CORRUPT, label .. ": normalized " .. names[1])
|
|
end
|
|
local size = SIZE[ct]
|
|
local cols = TYPE_COLUMNS[typ] or 1
|
|
local rows = comps // cols
|
|
local colBytes = rows * size
|
|
local colStride = if cols > 1 then (colBytes + 3) // 4 * 4 else colBytes
|
|
local elem = comps * size
|
|
local padded = cols * colStride
|
|
if count * elem > maxBytes then
|
|
return nil, Err.new(Err.LIMIT, label .. " is over " .. maxBytes .. " bytes")
|
|
end
|
|
local data = buffer.create(count * elem)
|
|
local vi = a.bufferView
|
|
if vi ~= nil then
|
|
local view = int(vi) and views[vi + 1]
|
|
if not view then
|
|
return nil, Err.new(Err.CORRUPT, label .. ": bad bufferView")
|
|
end
|
|
local off = int(a.byteOffset or 0)
|
|
if not off then
|
|
return nil, Err.new(Err.CORRUPT, label .. ": bad byteOffset")
|
|
end
|
|
local stride = view.stride or padded
|
|
if stride < padded and count > 1 then
|
|
return nil, Err.new(Err.CORRUPT, label .. ": byteStride smaller than an element")
|
|
end
|
|
if count > 0 and off + (count - 1) * stride + padded > view.length then
|
|
return nil, Err.new(Err.CORRUPT, label .. " runs past its bufferView")
|
|
end
|
|
if count > 0 then
|
|
Pack.gather(data, view.buf, view.offset + off, count, elem, stride, cols, colBytes, colStride)
|
|
end
|
|
end
|
|
local sp = a.sparse
|
|
if type(sp) == "table" then
|
|
local n = int(sp.count)
|
|
local si, sv = sp.indices, sp.values
|
|
if not n or type(si) ~= "table" or type(sv) ~= "table" then
|
|
return nil, Err.new(Err.CORRUPT, label .. ": bad sparse")
|
|
end
|
|
local isz = SIZE[si.componentType]
|
|
local iv, vv = int(si.bufferView) and views[si.bufferView + 1], int(sv.bufferView) and views[sv.bufferView + 1]
|
|
local io, vo = int(si.byteOffset or 0), int(sv.byteOffset or 0)
|
|
local okType = si.componentType == 5121 or si.componentType == 5123 or si.componentType == 5125
|
|
if not okType or not isz or not iv or not vv or not io or not vo then
|
|
return nil, Err.new(Err.CORRUPT, label .. ": bad sparse indices / values")
|
|
end
|
|
if io + n * isz > iv.length or vo + n * elem > vv.length then
|
|
return nil, Err.new(Err.CORRUPT, label .. ": sparse data runs past its bufferView")
|
|
end
|
|
-- sparse values are tightly packed (matrices: padded columns)
|
|
local vals, valOff = vv.buf, vv.offset + vo
|
|
if cols > 1 and colBytes ~= colStride then
|
|
vals = buffer.create(n * elem)
|
|
Pack.gather(vals, vv.buf, vv.offset + vo, n, elem, padded, cols, colBytes, colStride)
|
|
valOff = 0
|
|
end
|
|
if not Pack.sparse(data, count, elem, iv.buf, iv.offset + io, isz, vals, valOff, n) then
|
|
return nil, Err.new(Err.CORRUPT, label .. ": sparse index out of range")
|
|
end
|
|
end
|
|
local acc = Types.Scene.accessor(data, tname, comps, count)
|
|
if cols > 1 then
|
|
acc.matrix = true
|
|
end
|
|
acc.name = str(a.name)
|
|
accessors[i] = acc
|
|
end
|
|
local function accessor(v: any): Types.Accessor?
|
|
local k = int(v)
|
|
return if k then accessors[k + 1] else nil
|
|
end
|
|
local images: { Img } = {}
|
|
for i, im in arr(doc.images) do
|
|
if type(im) ~= "table" then
|
|
return nil, Err.new(Err.CORRUPT, "bad image " .. (i - 1))
|
|
end
|
|
local img: Img = { mime = str(im.mimeType), name = str(im.name) }
|
|
if im.bufferView ~= nil then
|
|
local view = int(im.bufferView) and views[im.bufferView + 1]
|
|
if not view then
|
|
return nil, Err.new(Err.CORRUPT, "image " .. (i - 1) .. ": bad bufferView")
|
|
end
|
|
local d = buffer.create(view.length)
|
|
buffer.copy(d, 0, view.buf, view.offset, view.length)
|
|
img.data = d
|
|
elseif type(im.uri) == "string" then
|
|
if string.sub(im.uri, 1, 5) == "data:" then
|
|
local d, mime = Base64.decodeDataUri(im.uri)
|
|
if d then
|
|
img.data = d
|
|
img.mime = img.mime or mime
|
|
end
|
|
else
|
|
img.uri = im.uri
|
|
img.data = fetch(im.uri)
|
|
if not img.mime then
|
|
local ext = string.lower(string.match(im.uri, "%.(%w+)$") or "")
|
|
img.mime = if ext == "png" then "image/png" elseif ext == "jpg" or ext == "jpeg" then "image/jpeg" elseif ext == "webp" then "image/webp" elseif ext == "ktx2" then "image/ktx2" else nil
|
|
end
|
|
end
|
|
end
|
|
images[i] = img
|
|
end
|
|
local samplers: { Types.Sampler } = {}
|
|
for i, s in arr(doc.samplers) do
|
|
if type(s) == "table" then
|
|
samplers[i] = {
|
|
wrapS = WRAP[s.wrapS] or (if s.wrapS == nil then nil else "repeat") :: any,
|
|
wrapT = WRAP[s.wrapT] or (if s.wrapT == nil then nil else "repeat") :: any,
|
|
filter = if s.magFilter == 9728 then "nearest" elseif s.magFilter == 9729 then "linear" else nil,
|
|
minFilter = MIN_FILTER[s.minFilter],
|
|
}
|
|
else
|
|
samplers[i] = {}
|
|
end
|
|
end
|
|
local TEX_SOURCE_EXT = { "KHR_texture_basisu", "EXT_texture_webp", "EXT_texture_avif" }
|
|
for i, t in arr(doc.textures) do
|
|
if type(t) ~= "table" then
|
|
return nil, Err.new(Err.CORRUPT, "bad texture " .. (i - 1))
|
|
end
|
|
local src = t.source
|
|
local handled = {}
|
|
if type(t.extensions) == "table" then
|
|
for _, e in TEX_SOURCE_EXT do
|
|
local x = t.extensions[e]
|
|
if type(x) == "table" and int(x.source) then
|
|
src = x.source
|
|
handled[e] = true
|
|
break
|
|
end
|
|
end
|
|
end
|
|
local img = int(src) and images[src + 1]
|
|
local tex: Types.Texture = { name = str(t.name) }
|
|
if img then
|
|
tex.data, tex.mime, tex.uri = img.data, img.mime, img.uri
|
|
tex.name = tex.name or img.name
|
|
end
|
|
local si = int(t.sampler)
|
|
if si and samplers[si + 1] then
|
|
tex.sampler = table.clone(samplers[si + 1])
|
|
end
|
|
tex.extras = keep(t, handled)
|
|
if next(handled) then
|
|
-- the fallback image (t.source) and the extension name, for writing the texture back the same way
|
|
tex.extras = tex.extras or { gltf = {} }
|
|
local g = (tex.extras :: any).gltf
|
|
g.sourceExtension = next(handled)
|
|
local fb = int(t.source) and images[t.source + 1]
|
|
if fb then
|
|
g.fallback = { data = fb.data, mime = fb.mime, uri = fb.uri }
|
|
end
|
|
end
|
|
table.insert(scene.textures, tex)
|
|
end
|
|
local function texRef(info: any): Types.TextureRef?
|
|
if type(info) ~= "table" or not int(info.index) or info.index >= #scene.textures then
|
|
return nil
|
|
end
|
|
local r: Types.TextureRef = { texture = info.index + 1, texCoord = int(info.texCoord), scale = if type(info.scale) == "number" then info.scale else nil, strength = if type(info.strength) == "number" then info.strength else nil }
|
|
local tt = type(info.extensions) == "table" and info.extensions.KHR_texture_transform
|
|
if type(tt) == "table" then
|
|
r.transform = { offset = numbers(tt.offset, 2), scale = numbers(tt.scale, 2), rotation = if type(tt.rotation) == "number" then tt.rotation else nil, texCoord = int(tt.texCoord) }
|
|
end
|
|
return r
|
|
end
|
|
-- a textureInfo: a table with an index, under a key ending in Texture
|
|
local function convertExt(v: any): any
|
|
if type(v) ~= "table" then
|
|
return v
|
|
end
|
|
local out = if Types.isObject(v) or next(v) == nil then Types.object() else {}
|
|
for k, x in v do
|
|
if type(k) == "string" and string.sub(k, -7) == "Texture" and type(x) == "table" and int(x.index) then
|
|
out[k] = texRef(x)
|
|
else
|
|
out[k] = convertExt(x)
|
|
end
|
|
end
|
|
return out
|
|
end
|
|
for i, m in arr(doc.materials) do
|
|
if type(m) ~= "table" then
|
|
return nil, Err.new(Err.CORRUPT, "bad material " .. (i - 1))
|
|
end
|
|
local mat = Types.Scene.material(str(m.name))
|
|
local pbr = if type(m.pbrMetallicRoughness) == "table" then m.pbrMetallicRoughness else {}
|
|
mat.baseColor = numbers(pbr.baseColorFactor, 4) or { 1, 1, 1, 1 }
|
|
mat.baseColorTexture = texRef(pbr.baseColorTexture)
|
|
mat.metallic = num(pbr.metallicFactor, 1)
|
|
mat.roughness = num(pbr.roughnessFactor, 1)
|
|
mat.metallicRoughnessTexture = texRef(pbr.metallicRoughnessTexture)
|
|
mat.normalTexture = texRef(m.normalTexture)
|
|
mat.occlusionTexture = texRef(m.occlusionTexture)
|
|
mat.emissive = numbers(m.emissiveFactor, 3) or { 0, 0, 0 }
|
|
mat.emissiveTexture = texRef(m.emissiveTexture)
|
|
mat.alphaMode = if m.alphaMode == "MASK" then "mask" elseif m.alphaMode == "BLEND" then "blend" else "opaque"
|
|
mat.alphaCutoff = num(m.alphaCutoff, 0.5)
|
|
mat.doubleSided = m.doubleSided == true
|
|
if type(m.extensions) == "table" then
|
|
local ext = {}
|
|
for k, v in m.extensions do
|
|
ext[k] = convertExt(v)
|
|
end
|
|
mat.extensions = ext
|
|
end
|
|
local kept = keep(m, mat.extensions and (mat.extensions :: any) or {})
|
|
local pk = keep(pbr, nil)
|
|
if pk then
|
|
kept = kept or { gltf = {} }
|
|
local kk: any = kept
|
|
kk.gltf.pbr = pk.gltf
|
|
end
|
|
mat.extras = kept
|
|
table.insert(scene.materials, mat)
|
|
end
|
|
for i, m in arr(doc.meshes) do
|
|
if type(m) ~= "table" then
|
|
return nil, Err.new(Err.CORRUPT, "bad mesh " .. (i - 1))
|
|
end
|
|
local mesh: Types.Mesh = { name = str(m.name), primitives = {}, weights = if type(m.weights) == "table" then table.clone(m.weights) else nil, extras = keep(m, nil) }
|
|
-- morph target names: the extras.targetNames convention (Blender's exporter, three.js, Babylon)
|
|
local tn = type(m.extras) == "table" and m.extras.targetNames
|
|
if type(tn) == "table" and #tn > 0 then
|
|
local names = {}
|
|
for k, v in tn do
|
|
names[k] = if type(v) == "string" then v else tostring(v)
|
|
end
|
|
mesh.extras = mesh.extras or {}
|
|
;(mesh.extras :: any).targetNames = names
|
|
end
|
|
for k, p in arr(m.primitives) do
|
|
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
|
|
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
|
|
if count >= 0 and a.count ~= count then
|
|
return nil, Err.new(Err.CORRUPT, string.format("mesh %d: attributes with different counts", i - 1))
|
|
end
|
|
count = a.count
|
|
attrs[name] = a
|
|
end
|
|
local mode = MODES[if p.mode == nil then 4 else p.mode]
|
|
if not mode then
|
|
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 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")
|
|
end
|
|
local get = Types.Scene.reader(ind :: Types.Accessor) :: any
|
|
for q = 0, ind.count - 1 do
|
|
if get(q, 0) >= count then
|
|
return nil, Err.new(Err.CORRUPT, "index out of range")
|
|
end
|
|
end
|
|
prim.indices = ind :: Types.Accessor
|
|
end
|
|
if type(p.targets) == "table" then
|
|
local targets = {}
|
|
for ti, t in p.targets do
|
|
local tt = {}
|
|
for name, ai in (if type(t) == "table" then t else {}) do
|
|
local a = accessor(ai)
|
|
if not a or a.count ~= count then
|
|
return nil, Err.new(Err.CORRUPT, "bad morph target accessor")
|
|
end
|
|
tt[name] = a
|
|
end
|
|
targets[ti] = tt
|
|
end
|
|
prim.targets = targets
|
|
end
|
|
prim.extras = keep(p, DRACO_HANDLED)
|
|
table.insert(mesh.primitives, prim)
|
|
end
|
|
table.insert(scene.meshes, mesh)
|
|
end
|
|
for _, c in arr(doc.cameras) do
|
|
if type(c) ~= "table" then
|
|
return nil, Err.new(Err.CORRUPT, "bad camera")
|
|
end
|
|
if c.type == "orthographic" and type(c.orthographic) == "table" then
|
|
local o = c.orthographic
|
|
table.insert(scene.cameras, { name = str(c.name), type = "orthographic" :: "orthographic", xmag = num(o.xmag, 1), ymag = num(o.ymag, 1), znear = num(o.znear, 0), zfar = num(o.zfar, 100) } :: Types.Camera)
|
|
else
|
|
local p = if type(c.perspective) == "table" then c.perspective else {}
|
|
table.insert(scene.cameras, { name = str(c.name), type = "perspective" :: "perspective", yfov = num(p.yfov, 0.8), aspect = if type(p.aspectRatio) == "number" then p.aspectRatio else nil, znear = num(p.znear, 0.01), zfar = if type(p.zfar) == "number" then p.zfar else nil } :: Types.Camera)
|
|
end
|
|
end
|
|
local lp = type(doc.extensions) == "table" and doc.extensions.KHR_lights_punctual
|
|
for _, l in arr(lp and lp.lights) do
|
|
if type(l) == "table" then
|
|
local spot = if type(l.spot) == "table" then l.spot else {}
|
|
table.insert(scene.lights, {
|
|
name = str(l.name),
|
|
type = if l.type == "spot" or l.type == "point" then l.type else "directional",
|
|
color = numbers(l.color, 3) or { 1, 1, 1 },
|
|
intensity = num(l.intensity, 1),
|
|
range = if type(l.range) == "number" then l.range else nil,
|
|
innerCone = if l.type == "spot" then num(spot.innerConeAngle, 0) else nil,
|
|
outerCone = if l.type == "spot" then num(spot.outerConeAngle, math.pi / 4) else nil,
|
|
})
|
|
end
|
|
end
|
|
local nodes = arr(doc.nodes)
|
|
for i, n in nodes do
|
|
if type(n) ~= "table" then
|
|
return nil, Err.new(Err.CORRUPT, "bad node " .. (i - 1))
|
|
end
|
|
local node: Types.Node = { name = str(n.name), children = {} }
|
|
for _, c in arr(n.children) do
|
|
if not int(c) or c >= #nodes then
|
|
return nil, Err.new(Err.CORRUPT, "node " .. (i - 1) .. ": bad child")
|
|
end
|
|
table.insert(node.children, c + 1)
|
|
end
|
|
if int(n.mesh) and n.mesh < #scene.meshes then
|
|
node.mesh = n.mesh + 1
|
|
end
|
|
if int(n.camera) and n.camera < #scene.cameras then
|
|
node.camera = n.camera + 1
|
|
end
|
|
if int(n.skin) and n.skin < #arr(doc.skins) then
|
|
node.skin = n.skin + 1
|
|
end
|
|
node.matrix = numbers(n.matrix, 16)
|
|
node.translation = numbers(n.translation, 3)
|
|
node.rotation = numbers(n.rotation, 4)
|
|
node.scale = numbers(n.scale, 3)
|
|
node.weights = if type(n.weights) == "table" then table.clone(n.weights) else nil
|
|
local handled = {}
|
|
local le = type(n.extensions) == "table" and n.extensions.KHR_lights_punctual
|
|
if type(le) == "table" and int(le.light) and le.light < #scene.lights then
|
|
node.light = le.light + 1
|
|
handled.KHR_lights_punctual = true
|
|
end
|
|
node.extras = keep(n, handled)
|
|
scene.nodes[i] = node
|
|
end
|
|
-- a node may have one parent only, and no cycles
|
|
local parent: { [number]: number } = {}
|
|
for i, node in scene.nodes do
|
|
for _, c in node.children do
|
|
if parent[c] or c == i then
|
|
return nil, Err.new(Err.CORRUPT, "node " .. (c - 1) .. " has two parents or is its own child")
|
|
end
|
|
parent[c] = i
|
|
end
|
|
end
|
|
for i in scene.nodes do
|
|
local seen, p = 0, parent[i]
|
|
while p do
|
|
seen += 1
|
|
if seen > #scene.nodes then
|
|
return nil, Err.new(Err.CORRUPT, "the node hierarchy has a cycle")
|
|
end
|
|
p = parent[p]
|
|
end
|
|
end
|
|
for _, s in arr(doc.skins) do
|
|
if type(s) ~= "table" then
|
|
return nil, Err.new(Err.CORRUPT, "bad skin")
|
|
end
|
|
local joints = {}
|
|
for _, j in arr(s.joints) do
|
|
if not int(j) or j >= #scene.nodes then
|
|
return nil, Err.new(Err.CORRUPT, "skin: bad joint")
|
|
end
|
|
table.insert(joints, j + 1)
|
|
end
|
|
table.insert(scene.skins, { name = str(s.name), joints = joints, inverseBindMatrices = accessor(s.inverseBindMatrices), skeleton = if int(s.skeleton) and s.skeleton < #scene.nodes then s.skeleton + 1 else nil })
|
|
end
|
|
for _, a in arr(doc.animations) do
|
|
if type(a) ~= "table" then
|
|
return nil, Err.new(Err.CORRUPT, "bad animation")
|
|
end
|
|
local anim: Types.Animation = { name = str(a.name), channels = {} }
|
|
local samplersA = arr(a.samplers)
|
|
local skipped = {}
|
|
for _, c in arr(a.channels) do
|
|
local s = type(c) == "table" and int(c.sampler) and samplersA[c.sampler + 1]
|
|
local target = type(c) == "table" and c.target
|
|
if not s or type(target) ~= "table" then
|
|
return nil, Err.new(Err.CORRUPT, "animation: bad channel")
|
|
end
|
|
local input, output = accessor(s.input), accessor(s.output)
|
|
if not input or not output then
|
|
return nil, Err.new(Err.CORRUPT, "animation: bad sampler accessors")
|
|
end
|
|
local path = target.path
|
|
if int(target.node) and target.node < #scene.nodes and (path == "translation" or path == "rotation" or path == "scale" or path == "weights") then
|
|
table.insert(anim.channels, {
|
|
node = target.node + 1,
|
|
path = path,
|
|
input = input,
|
|
output = output,
|
|
interpolation = if s.interpolation == "STEP" or s.interpolation == "CUBICSPLINE" then s.interpolation else "LINEAR",
|
|
})
|
|
else
|
|
table.insert(skipped, c) -- KHR_animation_pointer and friends
|
|
end
|
|
end
|
|
if #skipped > 0 then
|
|
local aa: any = anim
|
|
aa.extras = { gltf = { skippedChannels = #skipped } }
|
|
end
|
|
table.insert(scene.animations, anim)
|
|
end
|
|
local scenes = arr(doc.scenes)
|
|
local list = {}
|
|
for _, s in scenes do
|
|
local roots = {}
|
|
for _, n in arr(type(s) == "table" and s.nodes) do
|
|
if int(n) and n < #scene.nodes and not parent[n + 1] then
|
|
table.insert(roots, n + 1)
|
|
end
|
|
end
|
|
table.insert(list, { name = type(s) == "table" and str(s.name) or nil, nodes = roots, extras = if type(s) == "table" then keep(s, nil) else nil })
|
|
end
|
|
local which = int(doc.scene) or 0
|
|
if list[which + 1] then
|
|
scene.roots = list[which + 1].nodes
|
|
elseif #list == 0 then
|
|
for i in scene.nodes do
|
|
if not parent[i] then
|
|
table.insert(scene.roots, i)
|
|
end
|
|
end
|
|
end
|
|
local rootExt = nil
|
|
if type(doc.extensions) == "table" then
|
|
for k, v in doc.extensions do
|
|
if k ~= "KHR_lights_punctual" then
|
|
rootExt = rootExt or {}
|
|
rootExt[k] = v
|
|
end
|
|
end
|
|
end
|
|
scene.meta.up = "y"
|
|
scene.meta.unit = 1
|
|
scene.meta.gltf = {
|
|
asset = asset,
|
|
scenes = list,
|
|
scene = if doc.scene ~= nil then which + 1 else nil,
|
|
extensionsUsed = doc.extensionsUsed,
|
|
extensionsRequired = doc.extensionsRequired,
|
|
extensions = rootExt,
|
|
extras = doc.extras,
|
|
}
|
|
return scene, nil
|
|
end
|
|
|
|
return Read
|