Files
rosetta/src/Formats/model/dae/init.luau
T
4DBugandClaude Opus 5.5 434a304315 ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4
C2, the hierarchy (tools/move.py, every reference rewritten mechanically):
- codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder;
  codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample
  VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url;
  codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err
  Crc32 Adler32 Base64 Md5 Input Sniff.
- LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md).
- Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes.

C3, generic code out of format folders:
- containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first,
  trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64
  through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it.
- codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position,
  priming and end trimming) that aac, caf and m4a each carried (~70 lines each).
- codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of
  its own (the AND mask / alpha rule stay ICO's).
- codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model),
  Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is
  Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the
  fixtures' bind shapes).
- README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes:
  FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the
  shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks
  decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type
  baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-31 12:25:03 -05:00

207 lines
8.3 KiB
Luau

--!strict
-- model/dae: COLLADA 1.4.1 / 1.5.0 (Khronos COLLADA specifications; .dae XML, and .zae: a zip holding the .dae, its
-- manifest.xml and the images). New code.
-- Reads: geometry (<mesh> triangles / polylist / polygons / lines / linestrips / tristrips / trifans with shared input
-- offsets, de-indexed per index tuple; n-gons fan-triangulated unless opts.triangulate = false keeps "polygons"),
-- common-profile materials (phong / blinn / lambert / constant -> PBR baseColor / emissive / roughness from shininess /
-- alpha from transparent + transparency; every Phong term kept in material.extras.phong; FCOLLADA / MAX3D bump ->
-- normalTexture, double_sided), images through newparam sampler2D -> surface -> image (1.4) or instance_image (1.5),
-- kept encoded (opts.resolve / opts.files, embedded hex <data>, data: URIs), the instanced visual scene (matrix /
-- translate / rotate / scale / lookat / skew; instance_geometry / controller / camera / light / node; extra instances
-- of a node become child nodes), skin controllers (bind_shape_matrix applied to the mesh, joints by sid under
-- <skeleton> or by id / name, INV_BIND_MATRIX, JOINTS_0 / WEIGHTS_0 from the 4 strongest weights, normalized), morph
-- controllers (targets as POSITION / NORMAL deltas, weights), cameras (perspective: yfov from xfov / aspect;
-- orthographic), lights (directional / point / spot; attenuation in light.extras.dae; ambient lights as
-- node.extras.dae.ambientLight), animations (channels on node transform elements: whole elements, .X / .ANGLE
-- members, matrix (i)(j) elements; resampled at the union of their key times, rotations over 90 degrees subdivided,
-- into glTF TRS channels; one animation per animation_clip, else one for the file). meta.up = the up_axis ("y" / "z"
-- / "x"), meta.unit = unit meter; the data is never rotated or scaled. TEXCOORD_n V is flipped to glTF's top-left
-- origin (opts.flipV = false keeps Collada's).
-- Writes: Collada 1.4.1 (see model/dae/Write: meshes, materials, images, nodes, cameras, lights), or a .zae.
-- Not supported: <spline> / <brep> geometry, polygon holes (<ph>: the outer loop only), Bezier / Hermite curves
-- (sampled linearly at their keys), animations of non-transform targets, physics / kinematics / FX profiles other than
-- COMMON (counted in meta.source.skipped). Writing skins, morphs and animations.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Xml = require("@formats/codecs/text/Xml")
local Zip = require("@formats/containers/Zip")
local Read = require("@formats/model/dae/Read")
local Write = require("@formats/model/dae/Write")
-- ------------------------------------------------------------------------------------------------ contract
local Dae = {
name = "dae",
category = "model",
extensions = { "dae", "zae" },
mime = { "model/vnd.collada+xml", "model/vnd.collada+zip" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/text/Xml", "core/Base64", "containers/Zip", "codecs/model/Mat4" },
caps = { decode = true, encode = true, materials = true, polygons = true, skins = true, morphTargets = true, animation = true, cameras = true, lights = true, zae = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
resolve: ((uri: string) -> any)?, -- image files (buffer or string); the api sets it for paths
files: { [string]: any }?, -- or: the files by uri / base name
triangulate: boolean?, -- fan-triangulate n-gons (default true); false keeps "polygons" primitives
flipV: boolean?, -- TEXCOORD_n v = 1 - v (default true: glTF's convention)
maxVertices: number?, -- refuse more output vertices / array values (default 2^25)
}
export type EncodeOptions = {
files: { [string]: any }?, -- receives the texture images (else they are written as data: URIs or their uri)
name: string?, -- the destination's file name (names the image files)
flipV: boolean?, -- default true (the inverse of decode)
format: string?, -- "zae" writes a zip (manifest.xml + model.dae + images); the api passes the extension
}
-- ------------------------------------------------------------------------------------------------ sniff
function Dae.sniff(r: Bytes.Reader): number
local head = r:peek(2048)
if string.sub(head, 1, 4) == "PK\3\4" then
local nlen = string.byte(head, 27) or 0
local name = string.lower(string.sub(head, 31, 30 + nlen))
if string.find(name, "%.dae$") or name == "manifest.xml" then
return 0.95
end
return 0
end
-- UTF-16 files: drop the zero bytes
if string.find(string.sub(head, 1, 4), "\0", 1, true) then
head = string.gsub(head, "%z", "")
end
if string.find(head, "<COLLADA", 1, true) then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function fetcher(opts: DecodeOptions?, zip: any): Read.Fetch
return function(uri: string): buffer?
local v: any = nil
if zip then
local d = zip:read(uri)
if d then
return d
end
end
if not opts then
return nil
end
if type(opts.files) == "table" then
v = opts.files[uri]
if v == nil then
v = opts.files[string.match(uri, "([^/\\]+)$") or uri]
end
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 main .dae of a .zae: manifest.xml's <dae_root>, else the first .dae entry
local function zae(r: Bytes.Reader): (any, string?, Err.Err?)
local zip, err = Zip.open(r)
if not zip then
return nil, nil, err
end
local main: string? = nil
local manifest = zip:readString("manifest.xml")
if manifest then
local d = Xml.decode(manifest)
local rootEl = d and d.root and Xml.child(d.root :: Xml.Node, "dae_root")
if rootEl then
main = string.match(Xml.text(rootEl), "^%s*(.-)%s*$")
main = main and string.gsub(main, "^%./", "")
end
end
if not main or not zip:find(main) then
main = nil
for _, e in zip:list() do
if string.find(string.lower(e.name), "%.dae$") then
main = e.name
break
end
end
end
if not main then
return nil, nil, Err.new(Err.CORRUPT, "zae without a .dae")
end
local text, rerr = zip:readString(main)
if not text then
return nil, nil, rerr
end
return zip, text, nil
end
function Dae.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local text: string
local zip: any = nil
if r:peek(4) == "PK\3\4" then
local z, t, err = zae(r)
if not z then
return nil, err
end
zip, text = z, t :: string
else
text = buffer.readstring(r.buf, r.base, r.limit - r.base)
end
local doc, xerr = Xml.decode(text)
if not doc then
return nil, xerr
end
local scene, err = Read.scene(doc, fetcher(opts, zip), opts)
if not scene then
return nil, err
end
if zip and scene.meta.source then
scene.meta.source.zae = true
end
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Dae.encode(scene: Types.Scene, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(scene) ~= "table" or scene.kind ~= "scene" or type(scene.meshes) ~= "table" or type(scene.nodes) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Scene")
end
if opts and opts.format == "zae" then
-- a zip: manifest.xml, the .dae and its images
local files = {}
local o = table.clone(opts)
o.files = files
o.name = "model.dae"
local text = Write.build(scene, o)
if not text then
return nil, Err.new(Err.ARG, "the scene could not be written")
end
local w = Zip.writer()
w:add("manifest.xml", '<?xml version="1.0" encoding="utf-8"?>\n<dae_root>./model.dae</dae_root>\n')
w:add("model.dae", text)
local names = {}
for name in files do
table.insert(names, name)
end
table.sort(names)
for _, name in names do
w:add(name, files[name], { method = "store" })
end
return w:finish()
end
local text = Write.build(scene, opts)
if not text then
return nil, Err.new(Err.ARG, "the scene could not be written")
end
return buffer.fromstring(text), nil
end
return Dae