ws-3d3: model/gltf: KHR_draco_mesh_compression through codecs/model/Draco

Draco primitives decode on load (attributes as their accessors declare them,
u32 indices), written back uncompressed without the extension; meshopt stays
UNSUPPORTED. Tests: transcoded Khronos samples (two quantizations), Draco's and
assimp's Draco glTF files, each Draco primitive byte for byte against libdraco,
against the uncompressed sources, round trips. Draco bench line; scene.md section.
This commit is contained in:
4DBug committed 2026-10-31 14:29:54 -05:00
1 parent 9a6ddd5c16
commit c3711a7ab1
10 files changed
+455 -14

No files matched your search

+1 -1
View File
@@ -37,7 +37,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` |
| model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` |
| model | fbx | .fbx | yes | yes | binary: true, ascii: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, polygons: true | `tests/model/fbx.luau` |
| model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` |
| model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true, draco: true | `tests/model/gltf.luau` |
| model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` |
| model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` |
| model | ply | .ply | yes | yes | ascii: true, binary: true, polygons: true, points: true, colors: true | `tests/model/ply.luau` |
+20 -1
View File
@@ -218,6 +218,25 @@ assert(cube.materials[1].baseColor[1] == 0.8) -- from Kd 0.8 0.1 0.1
A missing **image** is not an error: the texture keeps its `uri` and no `data`.
### Compressed glTF (Draco)
Primitives compressed with `KHR_draco_mesh_compression` decode on load (through `codecs/model/Draco`, a port of Google's
Draco decoder: Edgebreaker and sequential connectivity, every prediction scheme, quantized attributes, bit-exact with
libdraco). The attributes come out as their accessors declare them, and the indices as `u32`. Saving writes the
geometry back uncompressed, without the extension. `EXT_meshopt_compression` is not supported.
```luau
local scene = assert(F.load(dracoGlbBytes)) -- Box.glb through draco_transcoder
local prim = scene.meshes[1].primitives[1]
assert(prim.indices.count == 36 and prim.attributes.POSITION.type == "f32")
local plain = assert(F.save(scene, nil, { format = "glb" }))
assert(not string.find(buffer.tostring(plain), "KHR_draco", 1, true))
```
Raw `.drc` files (and Draco data inside other formats) go through the codec itself:
`require(Formats.codecs.model.Draco).decode(bytes)` returns `{ kind, numPoints, numFaces, indices, attributes }` with
each attribute's values per point (`name`, `uniqueId`, `components`, `type`, `normalized`, `data`).
## Editing: `F.ops.mesh`
Every function accepts any accessor type and writes `f32` attributes and `u32` indices. Bad arguments return
@@ -382,7 +401,7 @@ assert(F.load(vox).voxels[1].size[1] == 4)
| Format | Read | Write | Notes |
|---|---|---|---|
| glTF 2.0 / GLB | yes | yes | everything above, `KHR_*` material extensions, `KHR_mesh_quantization`; no Draco / meshopt |
| glTF 2.0 / GLB | yes | yes | everything above, `KHR_*` material extensions, `KHR_mesh_quantization`, Draco (read); no meshopt |
| OBJ + MTL | yes | yes | polygons, vertex colours, Phong + PBR MTL |
| STL | yes | yes | ASCII / binary, colour conventions; a triangle soup |
| PLY | yes | yes | ASCII / binary, point clouds, custom `_` attributes |
+2 -2
View File
@@ -404,8 +404,8 @@ 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,
+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
+2 -2
View File
@@ -313,8 +313,8 @@ do
t:check(e and (e.code == Err.CORRUPT or e.code == Err.TRUNCATED), "bad JSON: " .. tostring(e))
local _, e2 = decode('{"asset": {"version": "1.0"}}')
t:check(e2 and e2.code == Err.UNSUPPORTED, "glTF 1: " .. tostring(e2))
local _, e3 = decode('{"asset": {"version": "2.0"}, "extensionsRequired": ["KHR_draco_mesh_compression"]}')
t:check(e3 and e3.code == Err.UNSUPPORTED, "Draco: " .. tostring(e3))
local _, e3 = decode('{"asset": {"version": "2.0"}, "extensionsRequired": ["EXT_meshopt_compression"]}')
t:check(e3 and e3.code == Err.UNSUPPORTED, "meshopt: " .. tostring(e3))
local c = byName["Box/glTF"]
local _, e4 = decode(c.data)
t:check(e4 and e4.code == Err.IO, "missing .bin: " .. tostring(e4))
+164
View File
@@ -0,0 +1,164 @@
-- model/gltf KHR_draco_mesh_compression tests: the Khronos samples compressed by draco_transcoder (two quantizations),
-- Draco's and assimp's Draco glTF files. Every Draco primitive against libdraco's decode of its buffer view (points,
-- faces, index and attribute CRCs); the transcoded files against their uncompressed sources (meshes, primitives,
-- nodes, materials, skins, animations, triangles, world bounds within the quantization step); the scene saved back
-- (uncompressed, without the extension) and reloaded; the fuzz no-throw pass. Fixtures: tools/fixtures/gltf_draco.py.
local T = require("@tests/T")
local Gltf = require("@formats/model/gltf")
local MeshOps = require("@formats/ops/MeshOps")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Cases = require("@tests/gen/gltf_draco")
local t = T.suite("gltf_draco")
local DT = { [1] = "i8", [2] = "u8", [3] = "i16", [4] = "u16", [5] = "i32", [6] = "u32", [9] = "f32" }
local SAME = { i8 = "i8", snorm8 = "i8", u8 = "u8", unorm8 = "u8", i16 = "i16", snorm16 = "i16", u16 = "u16", unorm16 = "u16", i32 = "i32", u32 = "u32", f32 = "f32" }
local function decode(data: string, files: any): (any, any)
return Gltf.decode(Bytes.reader(buffer.fromstring(data)), { files = files })
end
local function triangles(scene: any): number
local n = 0
for _, m in scene.meshes do
for _, p in m.primitives do
if p.mode == "triangles" then
n += if p.indices then p.indices.count // 3 else p.attributes.POSITION.count // 3
end
end
end
return n
end
local checked = { prims = 0, attrs = 0, converted = 0, originals = 0, roundTrips = 0 }
local samples = {}
for _, c in Cases do
local scene, err = decode(c.data, c.files)
t:check(scene, c.name .. ": decode: " .. tostring(err))
if scene then
for _, ref in c.prims do
local label = string.format("%s: mesh %d primitive %d", c.name, ref.mesh, ref.prim)
local prim = scene.meshes[ref.mesh] and scene.meshes[ref.mesh].primitives[ref.prim]
t:check(prim, label .. ": present")
if prim then
t:eq(prim.attributes.POSITION.count, ref.points, label .. ": points")
if ref.faces then
t:eq(prim.indices.count, ref.faces * 3, label .. ": indices")
t:eq(Crc32.of(prim.indices.data), ref.indices, label .. ": index CRC")
end
for name, a in ref.attrs do
local acc = prim.attributes[name]
t:check(acc, label .. ": " .. name)
if acc then
if SAME[acc.type] == DT[a.dataType] then
t:eq(Crc32.of(acc.data), a.crc, label .. ": " .. name .. " values")
checked.attrs += 1
else
checked.converted += 1
end
end
end
checked.prims += 1
end
end
-- against the uncompressed source
local o = c.original
if o then
local orig, oerr = decode(o.data, o.files)
t:check(orig, c.name .. ": original: " .. tostring(oerr))
if orig then
t:eq(#scene.meshes, #orig.meshes, c.name .. ": meshes")
for i, m in orig.meshes do
t:eq(#scene.meshes[i].primitives, #m.primitives, c.name .. ": mesh " .. i .. " primitives")
end
t:eq(#scene.nodes, #orig.nodes, c.name .. ": nodes")
-- draco_transcoder adds a default material to files without one
t:check(#scene.materials == #orig.materials or (#orig.materials == 0 and #scene.materials == 1), c.name .. ": materials")
t:eq(#scene.skins, #orig.skins, c.name .. ": skins")
t:eq(#scene.animations, #orig.animations, c.name .. ": animations")
t:eq(triangles(scene), triangles(orig), c.name .. ": triangles")
local lo, hi = MeshOps.bounds(MeshOps.merge(scene))
local olo, ohi = MeshOps.bounds(MeshOps.merge(orig))
if lo and olo then
-- the quantization step relative to the scene: 11-bit positions by default, 16-bit for "fine"
local rel = if string.find(c.name, "fine", 1, true) then 1e-4 else 5e-3
local ok = true
for k = 1, 3 do
local eps = math.max(ohi[k] - olo[k], 1e-6) * rel
if math.abs(lo[k] - olo[k]) > eps or math.abs(hi[k] - ohi[k]) > eps then
ok = false
end
end
t:check(ok, c.name .. ": world bounds within the quantization step")
end
checked.originals += 1
end
end
-- saved back without the extension
local glb = Gltf.encode(scene, { binary = true })
t:check(glb, c.name .. ": encode")
if glb then
t:check(not string.find(buffer.tostring(glb), "KHR_draco_mesh_compression", 1, true), c.name .. ": no Draco extension written")
local again = Gltf.decode(Bytes.reader(glb))
t:check(again and triangles(again) == triangles(scene), c.name .. ": round trip")
checked.roundTrips += 1
end
if #c.data < 6000 and next(c.files) == nil then
table.insert(samples, c.data)
end
end
end
t:note("%d Draco primitives like libdraco (%d attributes byte for byte, %d converted to their accessor type), %d against the uncompressed sources, %d round trips", checked.prims, checked.attrs, checked.converted, checked.originals, checked.roundTrips)
-- an accessor type other than the Draco attribute's: u8 normalized colours declared as f32
do
local Draco = require("@formats/codecs/model/Draco")
local Base64 = require("@formats/core/Base64")
local DracoCases = require("@tests/gen/draco_cases")
local drc
for _, dc in DracoCases do
if dc.name == "enc/test_generic.ply.cl7" then
drc = dc.data
end
end
local g = drc and Draco.decode(drc)
t:check(g, "colour .drc fixture")
if g then
local pos, col
for _, a in g.attributes do
if a.name == "POSITION" then
pos = a
elseif a.name == "COLOR" then
col = a
end
end
local n = g.numPoints
local doc = string.format(
'{"asset":{"version":"2.0"},"extensionsUsed":["KHR_draco_mesh_compression"],"extensionsRequired":["KHR_draco_mesh_compression"],'
.. '"buffers":[{"byteLength":%d,"uri":"data:application/octet-stream;base64,%s"}],"bufferViews":[{"buffer":0,"byteLength":%d}],'
.. '"accessors":[{"componentType":5126,"count":%d,"type":"VEC3"},{"componentType":5126,"count":%d,"type":"VEC%d"},{"componentType":5125,"count":%d,"type":"SCALAR"}],'
.. '"meshes":[{"primitives":[{"attributes":{"POSITION":0,"COLOR_0":1},"indices":2,"extensions":{"KHR_draco_mesh_compression":{"bufferView":0,"attributes":{"POSITION":%d,"COLOR_0":%d}}}}]}],'
.. '"nodes":[{"mesh":0}],"scenes":[{"nodes":[0]}]}',
#drc, Base64.encode(buffer.fromstring(drc)), #drc, n, n, col.components, g.numFaces * 3, pos.uniqueId, col.uniqueId)
local scene, err = decode(doc, {})
t:check(scene, "converted accessor: " .. tostring(err))
if scene then
local acc = scene.meshes[1].primitives[1].attributes.COLOR_0
t:eq(acc.type, "f32", "colour accessor type")
local ok = true
for i = 0, n * col.components - 1 do
local want = buffer.readu8(col.data, i) / 255
if math.abs(buffer.readf32(acc.data, i * 4) - want) > 1e-6 then
ok = false
end
end
t:check(ok, "u8 normalized colours -> f32 / 255")
end
end
end
t:fuzz("decode", function(b: buffer)
return Gltf.decode(Bytes.reader(b))
end, samples, { mutations = 6, garbage = 50 })
t:done()
+20
View File
@@ -1078,3 +1078,23 @@ do
jitTune(false)
end
end
do
-- Draco (codecs/model/Draco): the Stanford bunny (35k points, 69k faces, Edgebreaker valence, normals) and a UV
-- sphere with seams; MB/s of decoded output (u32 indices + f32 attributes per point), plus triangles per second.
local Draco = require("@formats/codecs/model/Draco")
local DC = require("@tests/gen/draco_cases")
for _, c in DC do
if c.name == "enc/bunny_norm.obj.cl7" or c.name == "enc/uvsphere.obj.cl10" or c.name == "enc/uvsphere.obj.cl0" then
local data = buffer.fromstring(c.data)
local g = assert(Draco.decode(data))
local n = g.numFaces * 12
for _, a in g.attributes do
n += buffer.len(a.data)
end
local dt = bench("draco " .. string.sub(c.name, 5), 3, n, function()
Draco.decode(data)
end)
print(string.format("%-8s %-30s %8.0f triangles/s", runtime, " (" .. g.numFaces .. " faces)", g.numFaces / dt))
end
end
end
+17
View File
@@ -0,0 +1,17 @@
# Docs inputs for the Draco section of docs/guide/scene.md (tools/fixtures.py, tools/docs_check.py): the Khronos Box
# sample (tests/fixtures/gltf) compressed with KHR_draco_mesh_compression by draco_transcoder 1.5.7 (nix).
# tests/gen/docs_draco.luau { files = { [name] = bytes }, vars = { dracoGlbBytes = "Box_draco.glb" } }
import importlib.util, os, subprocess, tempfile
INPUTS = ["tools/docs_check.py", "tests/fixtures/gltf/Box"]
def generate(ctx):
spec = importlib.util.spec_from_file_location("docs_check", os.path.join(ctx.root, "tools", "docs_check.py"))
dc = importlib.util.module_from_spec(spec)
spec.loader.exec_module(dc)
draco = subprocess.run(["nix", "build", "nixpkgs#draco", "--no-link", "--print-out-paths"], capture_output=True, check=True).stdout.decode().strip().split("\n")[-1]
out = os.path.join(tempfile.mkdtemp(prefix="formats-docs-draco-"), "Box_draco.glb")
subprocess.run([os.path.join(draco, "bin", "draco_transcoder"), "-i", os.path.join(ctx.root, "tests", "fixtures", "gltf", "Box", "glTF-Binary", "Box.glb"), "-o", out],
capture_output=True, check=True)
dc.emit_inputs(ctx, {"Box_draco.glb": open(out, "rb").read()}, {"dracoGlbBytes": "Box_draco.glb"})
+132
View File
@@ -0,0 +1,132 @@
# glTF + Draco fixtures (tools/fixtures.py): KHR_draco_mesh_compression files. The Khronos samples of
# tests/fixtures/gltf compressed by draco_transcoder 1.5.7 (nix) at its default and at a finer quantization, Draco's
# own glTF test files (Box_Draco.glb, BoxMetaDraco) and assimp's 2CylinderEngine (robot.glb: 12 MB, left out), read from the
# nixpkgs sources and never committed. Reference values: every Draco primitive's buffer view decoded by libdraco
# (tools/fixtures/_draco_dump.cc, compiled against nixpkgs#draco): points, faces, the index and per-attribute CRCs.
# tests/gen/gltf_draco.luau { { name, data, files = { uri -> bytes }, original? = { data, files } (the uncompressed
# source), prims = { { mesh, prim, points, faces, indices, attrs = { [name] = { uniqueId,
# dataType, crc } } } } } }
import json, os, struct, subprocess, tempfile, zlib
INPUTS = ["tests/fixtures/gltf", "tools/fixtures/_draco_dump.cc"]
def store_path(attr):
out = subprocess.run(["nix", "build", "nixpkgs#" + attr, "--no-link", "--print-out-paths"], capture_output=True, check=True)
return out.stdout.decode().strip().split("\n")[-1]
def load(path):
# -> (doc, bin, files): the JSON, the GLB binary chunk, the sibling files a .gltf refers to
raw = open(path, "rb").read()
files, binchunk = {}, None
if raw[:4] == b"glTF":
off = 12
doc = None
while off + 8 <= len(raw):
n, kind = struct.unpack_from("<II", raw, off)
chunk = raw[off + 8:off + 8 + n]
if kind == 0x4E4F534A:
doc = json.loads(chunk)
elif kind == 0x004E4942:
binchunk = chunk
off += 8 + n
else:
doc = json.loads(raw)
d = os.path.dirname(path)
for b in doc.get("buffers", []) + doc.get("images", []):
uri = b.get("uri")
if uri and not uri.startswith("data:") and os.path.exists(os.path.join(d, uri)):
files[uri] = open(os.path.join(d, uri), "rb").read()
return doc, binchunk, files
def buffer_bytes(doc, binchunk, files, i):
b = doc["buffers"][i]
uri = b.get("uri")
if uri is None:
return binchunk
if uri.startswith("data:"):
import base64
return base64.b64decode(uri.split(",", 1)[1])
return files[uri]
def references(doc, binchunk, files, dump, tmp):
prims = []
for mi, m in enumerate(doc.get("meshes", [])):
for pi, p in enumerate(m.get("primitives", [])):
ext = p.get("extensions", {}).get("KHR_draco_mesh_compression")
if not ext:
continue
v = doc["bufferViews"][ext["bufferView"]]
data = buffer_bytes(doc, binchunk, files, v["buffer"])
off = v.get("byteOffset", 0)
drc = data[off:off + v["byteLength"]]
path = os.path.join(tmp, "p.drc")
open(path, "wb").write(drc)
lines = subprocess.run([dump, path], capture_output=True).stdout.decode().split("\n")
entry = {"mesh": mi + 1, "prim": pi + 1, "attrs": {}}
by_id = {}
for line in lines:
parts = line.split(" ")
if parts[0] == "POINTS":
entry["points"] = int(parts[1])
elif parts[0] == "FACES":
entry["faces"] = int(parts[1])
entry["indices"] = zlib.crc32(bytes.fromhex(parts[2] if len(parts) > 2 else ""))
elif parts[0] == "ATTR":
by_id[int(parts[5])] = {"dataType": int(parts[2]), "crc": zlib.crc32(bytes.fromhex(parts[6] if len(parts) > 6 else ""))}
for name, uid in ext.get("attributes", {}).items():
if uid in by_id:
a = dict(by_id[uid])
a["uniqueId"] = uid
entry["attrs"][name] = a
prims.append(entry)
return prims
def generate(ctx):
draco = store_path("draco")
dsrc = store_path("draco.src")
asrc = store_path("assimp.src")
tmp = tempfile.mkdtemp(prefix="formats-gltfdraco-")
dump = os.path.join(tmp, "dump")
ctx.nix("gcc", ["g++", "-O1", "-std=c++17", "-I" + os.path.join(draco, "include"), os.path.join(ctx.root, "tools", "fixtures", "_draco_dump.cc"),
"-L" + os.path.join(draco, "lib"), "-l:libdraco.a", "-o", dump])
transcoder = os.path.join(draco, "bin", "draco_transcoder")
sources = [] # (name, path, original path?)
gl = os.path.join(ctx.root, "tests", "fixtures", "gltf")
for model in sorted(os.listdir(gl)):
d0 = os.path.join(gl, model)
for variant in sorted(os.listdir(d0)):
d = os.path.join(d0, variant)
if not os.path.isdir(d) or "Quantized" in variant:
continue
mains = [f for f in sorted(os.listdir(d)) if f.endswith(".gltf") or f.endswith(".glb")]
if not mains:
continue
src = os.path.join(d, mains[0])
for q, args in (("default", []), ("fine", ["-qp", "16", "-qt", "14", "-qn", "12", "-qc", "10", "-qw", "12", "-qtg", "10"])):
out = os.path.join(tmp, "%s_%s.glb" % (model, q))
r = subprocess.run([transcoder, "-i", src, "-o", out] + args, capture_output=True)
if r.returncode == 0 and os.path.exists(out):
sources.append(("transcoded/%s/%s" % (model, q), out, src))
break
for name, rel in (("draco/Box_Draco.glb", os.path.join(dsrc, "testdata", "Box", "glTF_Binary", "Box_Draco.glb")),
("draco/BoxMetaDraco.gltf", os.path.join(dsrc, "testdata", "BoxMetaDraco", "glTF", "BoxMetaDraco.gltf")),
("assimp/2CylinderEngine.gltf", os.path.join(asrc, "test", "models", "glTF2", "draco", "2CylinderEngine.gltf"))):
if os.path.exists(rel):
sources.append((name, rel, None))
cases = []
for name, path, orig in sources:
doc, binchunk, files = load(path)
prims = references(doc, binchunk, files, dump, tmp)
if not prims:
continue
case = {"name": name, "data": open(path, "rb").read(), "files": files, "prims": prims}
if orig:
_, _, ofiles = load(orig)
case["original"] = {"data": open(orig, "rb").read(), "files": ofiles}
cases.append(case)
ctx.emit("gltf_draco", cases)