merge ws/3d2

This commit is contained in:
4DBug committed 2026-10-31 09:55:41 -05:00
commit 17c00a15df
45 files changed
+16368 -2

No files matched your search

+60
View File
@@ -278,6 +278,42 @@ local list: { Entry } = {
return require("@formats/audio/wav")
end,
},
{
name = "3mf",
category = "model",
path = "model/3mf",
extensions = { "3mf" },
mime = { "model/3mf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "containers/Zip" },
caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true },
load = function()
return require("@formats/model/3mf")
end,
},
{
name = "dae",
category = "model",
path = "model/dae",
extensions = { "dae", "zae" },
mime = { "model/vnd.collada+xml", "model/vnd.collada+zip" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "codecs/Base64", "containers/Zip" },
caps = { decode = true, encode = true, materials = true, polygons = true, skins = true, morphTargets = true, animation = true, cameras = true, lights = true, zae = true },
load = function()
return require("@formats/model/dae")
end,
},
{
name = "fbx",
category = "model",
path = "model/fbx",
extensions = { "fbx" },
mime = { "application/vnd.autodesk.fbx", "model/fbx" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "core/Base64" },
caps = { decode = true, encode = true, binary = true, ascii = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true },
load = function()
return require("@formats/model/fbx")
end,
},
{
name = "gltf",
category = "model",
@@ -338,6 +374,18 @@ local list: { Entry } = {
return require("@formats/model/stl")
end,
},
{
name = "usda",
category = "model",
path = "model/usda",
extensions = { "usda", "usd", "usdz" },
mime = { "model/vnd.usda", "model/vnd.usdz+zip" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" },
caps = { decode = true, encode = true, materials = true, animation = true, cameras = true, lights = true, polygons = true, vertexColors = true, usdz = "read", usdc = false },
load = function()
return require("@formats/model/usda")
end,
},
{
name = "vox",
category = "model",
@@ -350,6 +398,18 @@ local list: { Entry } = {
return require("@formats/model/vox")
end,
},
{
name = "step",
category = "cad",
path = "cad/step",
extensions = { "step", "stp", "p21" },
mime = { "model/step", "application/step", "application/p21" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" },
load = function()
return require("@formats/cad/step")
end,
},
{
name = "bmfont",
category = "font",
+3 -1
View File
@@ -562,7 +562,9 @@ end
-- ------------------------------------------------------------------------------------------------ Cad
-- the STEP entity graph; B-rep bodies and tessellation come from the injected brep plug-in (Formats.plugins.brep)
export type StepEntity = { id: number, type: string, args: { any } }
-- complex (external mapping) instances: type = "COMPLEX", args = {}, parts = { { type, args } } in file order;
-- section = the DATA section index when a file has more than one (edition 3)
export type StepEntity = { id: number, type: string, args: { any }, parts: { { type: string, args: { any } } }?, section: number? }
export type Cad = {
kind: "cad",
schema: string, -- "AP203", "AP214", "AP242", ...
+248
View File
@@ -0,0 +1,248 @@
--!strict
-- cad/step/Brep: the injected B-rep plug-in (Formats.plugins.brep; formats-luau never requires a kernel). Normalises
-- the plug-in table, calls it under pcall (kernels throw on bad geometry) and turns its tessellated meshes into a
-- Scene. Interpreted on purpose: the plug-in's errors unwind through here.
--
-- The interface (every function may throw; results are checked):
-- read(text: string, opts) -> { bodies = { Body }, stats = { ... }? } STEP text -> B-rep bodies (body.name?,
-- body.color? = Color3 | { r, g, b } | { 1, 2, 3 })
-- write(bodies: { Body }, opts) -> string bodies -> STEP text
-- tessellate(body: Body, opts) -> { positions = { vector | {x, y, z} }, normals = { ... }?, indices = { 1-based
-- triples }, faceOf = { [triangle] = Face (face.color?) }? }
-- or brep-luau's modules as they are: { Step = , StepBrep = , StepWrite = , Tess = } (adapted here: read =
-- StepBrep.read(Step.parse(text)), write = StepWrite.write with options.colors from body.color, tessellate = Tess.body).
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Brep = {}
export type Plugin = {
read: (text: string, opts: any) -> any,
write: ((bodies: { any }, opts: any) -> string)?,
tessellate: ((body: any, opts: any) -> any)?,
}
local function rgbOf(c: any): (number?, number?, number?)
if c == nil then
return nil, nil, nil
end
local ok, r, g, b = pcall(function(): (any, any, any)
if type(c) == "table" then
return c.r or c.R or c[1], c.g or c.G or c[2], c.b or c.B or c[3]
end
return (c :: any).R, (c :: any).G, (c :: any).B -- Color3
end)
if ok and type(r) == "number" and type(g) == "number" and type(b) == "number" then
return r, g, b
end
return nil, nil, nil
end
-- plugin(p) -> the normalised interface, or nil + the reason
function Brep.plugin(p: any): (Plugin?, string?)
if type(p) ~= "table" then
return nil, "needs the B-rep plug-in (Formats.plugins.brep = { read, write, tessellate }, e.g. brep-luau's { Step, StepBrep, StepWrite, Tess })"
end
if type(p.read) == "function" then
return {
read = p.read,
write = if type(p.write) == "function" then p.write else nil,
tessellate = if type(p.tessellate) == "function" then p.tessellate else nil,
}, nil
end
local S, SB, SW, Tess = p.Step, p.StepBrep, p.StepWrite, p.Tess
if type(S) == "table" and type(SB) == "table" and type(S.parse) == "function" and type(SB.read) == "function" then
return {
read = function(text: string, opts: any): any
return SB.read(S.parse(text), opts)
end,
write = if type(SW) == "table" and type(SW.write) == "function"
then function(bodies: { any }, opts: any): string
local o = if type(opts) == "table" then table.clone(opts) else {}
if o.colors == nil then
local colors = {}
for i, b in bodies do
local r, g, bl = rgbOf(type(b) == "table" and b.color or nil)
if r then
colors[i] = { r, g, bl }
end
end
o.colors = colors
end
return SW.write(bodies, o)
end
else nil,
tessellate = if type(Tess) == "table" and type(Tess.body) == "function"
then function(body: any, opts: any): any
return Tess.body(body, opts)
end
else nil,
}, nil
end
return nil, "the B-rep plug-in has neither read() nor brep-luau's Step + StepBrep modules"
end
-- find(opts) -> the plug-in from opts.brep or opts.plugins.brep
function Brep.find(opts: any): (Plugin?, Err.Err?)
local p = nil
if type(opts) == "table" then
p = opts.brep
if p == nil and type(opts.plugins) == "table" then
p = opts.plugins.brep
end
end
local plug, why = Brep.plugin(p)
if not plug then
return nil, Err.new(Err.UNSUPPORTED, why :: string)
end
return plug, nil
end
-- read(plug, text, opts) -> bodies, result | nil, Err
function Brep.read(plug: Plugin, text: string, opts: any): (({ any })?, any, Err.Err?)
local ok, res = pcall(plug.read, text, opts)
if not ok then
return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to read: " .. tostring(res))
end
if type(res) ~= "table" or type(res.bodies) ~= "table" then
return nil, nil, Err.new(Err.CORRUPT, "the B-rep plug-in's read returned no bodies")
end
return res.bodies, res, nil
end
-- write(plug, bodies, opts) -> text | nil, Err
function Brep.write(plug: Plugin, bodies: { any }, opts: any): (string?, Err.Err?)
local w = plug.write
if not w then
return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no write()")
end
local ok, res = pcall(w, bodies, opts)
if not ok then
return nil, Err.new(Err.ARG, "the B-rep plug-in failed to write: " .. tostring(res))
end
if type(res) ~= "string" then
return nil, Err.new(Err.ARG, "the B-rep plug-in's write returned no text")
end
return res, nil
end
local function xyz(p: any): (number, number, number)
if type(p) == "table" then
return tonumber(p.x or p.X or p[1]) or 0, tonumber(p.y or p.Y or p[2]) or 0, tonumber(p.z or p.Z or p[3]) or 0
end
return (p :: any).X, (p :: any).Y, (p :: any).Z -- vector / Vector3
end
local function linear(c: number): number
c = math.clamp(c, 0, 1)
return if c <= 0.04045 then c / 12.92 else ((c + 0.055) / 1.055) ^ 2.4
end
-- scene(plug, bodies, opts) -> Scene: one node + mesh per body, one primitive per face colour (materials shared by
-- colour; baseColor = the STEP colour converted from sRGB to linear, extras.color = the colour as written)
function Brep.scene(plug: Plugin, bodies: { any }, opts: any): (Types.Scene?, Err.Err?)
local tess = plug.tessellate
if not tess then
return nil, Err.new(Err.UNSUPPORTED, "the B-rep plug-in has no tessellate()")
end
local scene = Types.Scene.new()
scene.meta.up = "z"
scene.meta.unit = 0.001
local tessOpts = if type(opts) == "table" and type(opts.tess) == "table"
then opts.tess
else { chord = if type(opts) == "table" and type(opts.chord) == "number" then opts.chord else 0.05 }
local matByKey: { [string]: number } = {}
local function material(r: number?, g: number?, b: number?): number
local key = if r then string.format("%.6f,%.6f,%.6f", r, g :: number, b :: number) else "default"
local m = matByKey[key]
if m then
return m
end
local mat = Types.Scene.material(if r then "step_" .. #scene.materials + 1 else "default")
if r then
mat.baseColor = { linear(r), linear(g :: number), linear(b :: number), 1 }
mat.extras = { color = { r, g, b } }
else
mat.baseColor = { 0.6, 0.6, 0.6, 1 }
end
mat.metallic, mat.roughness = 0, 0.5
table.insert(scene.materials, mat)
matByKey[key] = #scene.materials
return #scene.materials
end
for bi, body in bodies do
local ok, mesh = pcall(tess, body, tessOpts)
if not ok then
return nil, Err.new(Err.CORRUPT, "the B-rep plug-in failed to tessellate body " .. bi .. ": " .. tostring(mesh))
end
if type(mesh) ~= "table" or type(mesh.positions) ~= "table" or type(mesh.indices) ~= "table" then
return nil, Err.new(Err.CORRUPT, "the B-rep plug-in's tessellate returned no mesh")
end
local cok, prims = pcall(function(): { Types.Primitive }
local P, N, I = mesh.positions, mesh.normals, mesh.indices
local nv = #P
local pos = Types.Scene.accessor(nil, "f32", 3, nv)
local nrm = if type(N) == "table" and #N == nv then Types.Scene.accessor(nil, "f32", 3, nv) else nil
for i = 1, nv do
local x, y, z = xyz(P[i])
buffer.writef32(pos.data, (i - 1) * 12, x)
buffer.writef32(pos.data, (i - 1) * 12 + 4, y)
buffer.writef32(pos.data, (i - 1) * 12 + 8, z)
if nrm then
local a, b, c = xyz(N[i])
buffer.writef32(nrm.data, (i - 1) * 12, a)
buffer.writef32(nrm.data, (i - 1) * 12 + 4, b)
buffer.writef32(nrm.data, (i - 1) * 12 + 8, c)
end
end
local br, bg, bb = rgbOf(type(body) == "table" and body.color or nil)
-- triangles grouped by colour, in first-seen order
local groups: { { mat: number, tris: { number } } } = {}
local byMat: { [number]: { mat: number, tris: { number } } } = {}
local faceOf = if type(mesh.faceOf) == "table" then mesh.faceOf else {}
local nt = #I // 3
for t = 1, nt do
local f = faceOf[t]
local r, g, b = rgbOf(type(f) == "table" and f.color or nil)
if not r then
r, g, b = br, bg, bb
end
local m = material(r, g, b)
local grp = byMat[m]
if not grp then
grp = { mat = m, tris = {} }
byMat[m] = grp
table.insert(groups, grp)
end
table.insert(grp.tris, t)
end
local out: { Types.Primitive } = {}
for _, grp in groups do
local idx = Types.Scene.accessor(nil, "u32", 1, #grp.tris * 3)
for k, t in grp.tris do
for c = 0, 2 do
local v = (tonumber(I[(t - 1) * 3 + c + 1]) or 1) - 1
buffer.writeu32(idx.data, ((k - 1) * 3 + c) * 4, math.clamp(v, 0, math.max(nv - 1, 0)))
end
end
local attrs: { [string]: Types.Accessor } = { POSITION = pos }
if nrm then
attrs.NORMAL = nrm
end
table.insert(out, { attributes = attrs, indices = idx, mode = "triangles" :: any, material = grp.mat })
end
return out
end)
if not cok then
return nil, Err.new(Err.CORRUPT, "bad tessellation of body " .. bi .. ": " .. tostring(prims))
end
local name = if type(body) == "table" and type(body.name) == "string" then body.name else "body_" .. bi
table.insert(scene.meshes, { name = name, primitives = prims })
table.insert(scene.nodes, { name = name, children = {}, mesh = #scene.meshes })
table.insert(scene.roots, #scene.nodes)
end
scene.meta.source = { format = "step", tessellated = true, bodies = #bodies }
return scene, nil
end
return Brep
+573
View File
@@ -0,0 +1,573 @@
--!strict
--!native
-- cad/step/Parse: ISO 10303-21 (STEP physical file, editions 1-3) text -> header + entity instances. A single pass
-- over the text: comments, the HEADER section, any number of DATA sections (edition 3 `DATA('name', ('schema'));`),
-- ANCHOR / REFERENCE / SIGNATURE sections kept as raw text, simple and complex (external mapping) instances, every
-- parameter kind (integer, real, string with its \S\ \X\ \X2\ \X4\ escapes decoded to UTF-8, enumeration, binary,
-- entity reference, $, *, list, typed parameter). Never throws: failures return nil, message, offset.
--
-- Values: numbers; strings; { enum = "T" }; { ref = 12 }; { binary = "0FF" }; { typed = "LENGTH_MEASURE", value = v };
-- lists as arrays; NULL / DERIVED sentinels (from the caller). A real literal with an integral value (`0.`, `1.E2`)
-- is recorded in the metatable of the list (or typed table) holding it (`__reals = { [index | "value"] = true }`), so
-- the writer prints it back as a real; integral numbers without that mark are written as integers.
local Parse = {}
local sbyte, ssub, sfind, schar, floor = string.byte, string.sub, string.find, string.char, math.floor
local MAX_DEPTH = 100
export type Ctx = {
s: string,
n: number,
err: string?,
errAt: number?,
null: any,
derived: any,
}
local function fail(ctx: Ctx, msg: string, at: number): nil
if not ctx.err then
ctx.err, ctx.errAt = msg, at
end
return nil
end
-- the next position that is not white space or inside a /* comment */ (n + 1 at the end; an open comment -> error)
local function skip(ctx: Ctx, i: number): number
local s, n = ctx.s, ctx.n
while i <= n do
local c = sbyte(s, i)
if c == 32 or c == 10 or c == 13 or c == 9 or c == 12 then
i += 1
elseif c == 47 and sbyte(s, i + 1) == 42 then
local _, e = sfind(s, "*/", i + 2, true)
if not e then
fail(ctx, "unterminated comment", i)
return n + 1
end
i = e + 1
else
return i
end
end
return i
end
local function isAlpha(c: number): boolean
return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95
end
local function isWord(c: number): boolean
return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95 or (c >= 48 and c <= 57)
end
-- keyword at i ([!]A-Z_ A-Z0-9_*) -> word, next; nil when there is none
local function keyword(ctx: Ctx, i: number): (string?, number)
local s, n = ctx.s, ctx.n
local j = i
if j <= n and sbyte(s, j) == 33 then -- '!' user-defined
j += 1
end
if j > n or not isAlpha(sbyte(s, j) :: number) then
return nil, i
end
j += 1
while j <= n and isWord(sbyte(s, j) :: number) do
j += 1
end
return string.upper(ssub(s, i, j - 1)), j
end
-- UTF-8 of a code point
local function utf8char(cp: number): string
if cp < 0x80 then
return schar(cp)
elseif cp < 0x800 then
return schar(0xC0 + floor(cp / 64), 0x80 + cp % 64)
elseif cp < 0x10000 then
return schar(0xE0 + floor(cp / 4096), 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64)
elseif cp < 0x110000 then
return schar(0xF0 + floor(cp / 262144), 0x80 + floor(cp / 4096) % 64, 0x80 + floor(cp / 64) % 64, 0x80 + cp % 64)
end
return "\239\191\189"
end
Parse.utf8char = utf8char
local function hexAt(s: string, i: number, k: number): number?
local h = ssub(s, i, i + k - 1)
if #h ~= k or sfind(h, "[^%x]") then
return nil
end
return tonumber(h, 16)
end
-- the text between the quotes of a string literal -> its value ('' -> ', \\ -> \, \S\c, \X\hh, \X2\..\X0\, \X4\..\X0\,
-- \P?\ page switches ignored: every page reads as ISO 8859-1). Bytes >= 0x80 written raw (common, though not allowed)
-- pass through.
function Parse.unescape(raw: string): string
if not sfind(raw, "[\\']") then
return raw
end
local out = {}
local i, n = 1, #raw
local plain = 1
while i <= n do
local c = sbyte(raw, i)
if c == 39 then -- '' -> '
table.insert(out, ssub(raw, plain, i))
i += 2
plain = i
elseif c == 92 then
table.insert(out, ssub(raw, plain, i - 1))
local d = sbyte(raw, i + 1)
if d == 92 then
table.insert(out, "\\")
i += 2
elseif d == 83 and sbyte(raw, i + 2) == 92 and i + 3 <= n then -- \S\c
table.insert(out, utf8char(((sbyte(raw, i + 3) :: number) + 128) % 256))
i += 4
elseif d == 80 and sbyte(raw, i + 3) == 92 then -- \P?\ code page
i += 4
elseif d == 88 and sbyte(raw, i + 2) == 92 then -- \X\hh
local h = hexAt(raw, i + 3, 2)
if h then
table.insert(out, utf8char(h))
i += 5
else
table.insert(out, "\\")
i += 1
end
elseif d == 88 and (sbyte(raw, i + 2) == 50 or sbyte(raw, i + 2) == 52) and sbyte(raw, i + 3) == 92 then
local k = if sbyte(raw, i + 2) == 50 then 4 else 8
local j = i + 4
local hi: number? = nil
while j <= n do
if sbyte(raw, j) == 92 then
break
end
local cp = hexAt(raw, j, k)
if not cp then
break
end
if k == 4 and cp >= 0xD800 and cp < 0xDC00 then
hi = cp
elseif k == 4 and hi and cp >= 0xDC00 and cp < 0xE000 then
table.insert(out, utf8char(0x10000 + (hi - 0xD800) * 1024 + (cp - 0xDC00)))
hi = nil
else
table.insert(out, utf8char(cp))
hi = nil
end
j += k
end
if ssub(raw, j, j + 3) == "\\X0\\" then
j += 4
end
i = j
else
table.insert(out, "\\")
i += 1
end
plain = i
else
i += 1
end
end
table.insert(out, ssub(raw, plain, n))
return table.concat(out)
end
local function markReal(t: { [any]: any }, key: any)
local mt: any = getmetatable(t)
if not mt then
mt = { __reals = {} }
setmetatable(t, mt)
end
mt.__reals[key] = true
end
-- one parameter at i -> value, next, integralReal (nil value + ctx.err on failure)
local value: (ctx: Ctx, i: number, depth: number) -> (any, number, boolean)
local function list(ctx: Ctx, i: number, depth: number): ({ any }?, number)
-- i is just past "("
local s = ctx.s
local out = {}
i = skip(ctx, i)
if sbyte(s, i) == 41 then
return out, i + 1
end
local k = 0
while true do
local v, j, intReal = value(ctx, i, depth + 1)
if v == nil then
return nil, j
end
k += 1
out[k] = v
if intReal then
markReal(out, k)
end
j = skip(ctx, j)
local c = sbyte(s, j)
if c == 44 then
i = skip(ctx, j + 1)
elseif c == 41 then
return out, j + 1
elseif c == nil then
return fail(ctx, "truncated list", j), j
else
return fail(ctx, "expected , or ) in a list", j), j
end
end
end
Parse.list = list
value = function(ctx: Ctx, i: number, depth: number): (any, number, boolean)
if depth > MAX_DEPTH then
return fail(ctx, "lists nested too deeply", i), i, false
end
local s = ctx.s
i = skip(ctx, i)
local c = sbyte(s, i)
if c == nil then
return fail(ctx, "truncated parameter", i), i, false
elseif c == 35 then -- #ref
local _, e = sfind(s, "^%d+", i + 1)
if not e then
return fail(ctx, "bad entity reference", i), i, false
end
return { ref = tonumber(ssub(s, i + 1, e)) }, e + 1, false
elseif c == 39 then -- 'string'
local j = i + 1
while true do
local q = sfind(s, "'", j, true)
if not q then
return fail(ctx, "unterminated string", i), i, false
end
if sbyte(s, q + 1) == 39 then
j = q + 2
else
return Parse.unescape(ssub(s, i + 1, q - 1)), q + 1, false
end
end
elseif c == 36 then
return ctx.null, i + 1, false
elseif c == 42 then
return ctx.derived, i + 1, false
elseif c == 40 then
local l, j = list(ctx, i + 1, depth)
return l, j, false
elseif c == 46 then -- .ENUM.
local _, e = sfind(s, "^[%a_][%w_]*%.", i + 1)
if not e then
return fail(ctx, "bad enumeration", i), i, false
end
return { enum = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false
elseif c == 34 then -- "binary"
local _, e = sfind(s, "^[0-3]%x*\"", i + 1)
if not e then
return fail(ctx, "bad binary literal", i), i, false
end
return { binary = string.upper(ssub(s, i + 1, e - 1)) }, e + 1, false
elseif (c >= 48 and c <= 57) or c == 45 or c == 43 then
local _, e = sfind(s, "^[+-]?%d*%.?%d*[eE]?[+-]?%d*", i)
local tok = ssub(s, i, e :: number)
local num = tonumber(if c == 43 then ssub(tok, 2) else tok)
if num == nil then
-- "1.E" without digits and the like
local core = string.match(tok, "^[+-]?%d*%.?%d*")
num = core and tonumber(if c == 43 then ssub(core, 2) else core)
if num == nil then
return fail(ctx, "bad number", i), i, false
end
e = i + #(core :: string) - 1
end
local real = sfind(tok, "[.eE]") ~= nil
local nv = num :: number
return nv, (e :: number) + 1, real and nv == floor(nv) and nv == nv
elseif isAlpha(c) or c == 33 then -- typed parameter NAME(value)
local word, j = keyword(ctx, i)
j = skip(ctx, j)
if word == nil or sbyte(s, j) ~= 40 then
return fail(ctx, "expected a parameter", i), i, false
end
local v, k, intReal = value(ctx, j + 1, depth + 1)
if v == nil then
return nil, k, false
end
k = skip(ctx, k)
if sbyte(s, k) ~= 41 then
return fail(ctx, "expected ) after a typed parameter", k), k, false
end
local t = { typed = word, value = v }
if intReal then
markReal(t, "value")
end
return t, k + 1, false
end
return fail(ctx, "unexpected character " .. string.format("%q", schar(c)), i), i, false
end
Parse.value = value
-- the simple record at i: NAME(params) -> type, args, next
local function record(ctx: Ctx, i: number): (string?, { any }?, number)
local word, j = keyword(ctx, i)
if not word then
return fail(ctx, "expected an entity name", i), nil, i
end
j = skip(ctx, j)
if sbyte(ctx.s, j) ~= 40 then
return fail(ctx, "expected ( after " .. word, j), nil, j
end
local args, k = list(ctx, j + 1, 0)
if not args then
return nil, nil, k
end
return word, args, k
end
-- expect(ctx, i, ch) -> next position after ch (skipping blanks), or nil
local function expect(ctx: Ctx, i: number, ch: number, what: string): number?
i = skip(ctx, i)
if sbyte(ctx.s, i) ~= ch then
if i > ctx.n then
return fail(ctx, "truncated: expected " .. what, i)
end
return fail(ctx, "expected " .. what, i)
end
return i + 1
end
local function at(s: string, i: number, word: string): boolean
return ssub(s, i, i + #word - 1) == word
end
export type Result = {
header: { [string]: { any } },
headerOrder: { string },
entities: { [number]: any },
count: number,
sections: { { name: any?, schema: any? } },
extra: { { name: string, text: string } },
duplicates: number,
terminated: boolean,
}
-- parse(s, opts) -> Result | nil, message, offset (1-based position in s)
function Parse.parse(s: string, null: any, derived: any, maxEntities: number): (Result?, string?, number?)
local ctx: Ctx = { s = s, n = #s, err = nil, errAt = nil, null = null, derived = derived }
local res: Result = {
header = {},
headerOrder = {},
entities = {},
count = 0,
sections = {},
extra = {},
duplicates = 0,
terminated = false,
}
local i = skip(ctx, 1)
if not at(s, i, "ISO-10303-21") then
return nil, "no ISO-10303-21 magic", i
end
local ni = expect(ctx, i + 12, 59, ";")
if not ni then
return nil, ctx.err, ctx.errAt
end
i = ni
local sawData = false
while true do
i = skip(ctx, i)
if ctx.err then
return nil, ctx.err, ctx.errAt
end
if i > ctx.n then
if not sawData then
return nil, "truncated: no DATA section", i
end
break
end
if at(s, i, "END-ISO-10303-21") then
res.terminated = true
local e = expect(ctx, i + 16, 59, ";")
if not e then
return nil, ctx.err, ctx.errAt
end
break
end
local word, j = keyword(ctx, i)
if word == "HEADER" then
local e = expect(ctx, j, 59, ";")
if not e then
return nil, ctx.err, ctx.errAt
end
i = e
while true do
i = skip(ctx, i)
if at(s, i, "ENDSEC") then
local e2 = expect(ctx, i + 6, 59, ";")
if not e2 then
return nil, ctx.err, ctx.errAt
end
i = e2
break
end
if i > ctx.n then
return nil, "truncated header", i
end
local t, args, k = record(ctx, i)
if not t then
return nil, ctx.err, ctx.errAt
end
local e2 = expect(ctx, k, 59, ";")
if not e2 then
return nil, ctx.err, ctx.errAt
end
if res.header[t] == nil then
table.insert(res.headerOrder, t)
end
res.header[t] = args :: { any }
i = e2
end
elseif word == "DATA" then
sawData = true
local sec: { name: any?, schema: any? } = {}
j = skip(ctx, j)
if sbyte(s, j) == 40 then
local params, k = list(ctx, j + 1, 0)
if not params then
return nil, ctx.err, ctx.errAt
end
sec.name, sec.schema = params[1], params[2]
j = k
end
table.insert(res.sections, sec)
local secIndex = #res.sections
local e = expect(ctx, j, 59, ";")
if not e then
return nil, ctx.err, ctx.errAt
end
i = e
while true do
i = skip(ctx, i)
if ctx.err then
return nil, ctx.err, ctx.errAt
end
local c = sbyte(s, i)
if c == nil then
return nil, "truncated: the DATA section has no ENDSEC", i
end
if c ~= 35 then
if at(s, i, "ENDSEC") then
local e2 = expect(ctx, i + 6, 59, ";")
if not e2 then
return nil, ctx.err, ctx.errAt
end
i = e2
break
end
return nil, "expected an entity instance (#id = ...)", i
end
local _, idEnd = sfind(s, "^%d+", i + 1)
if not idEnd then
return nil, "bad entity instance name", i
end
local id = tonumber(ssub(s, i + 1, idEnd)) :: number
local k = expect(ctx, idEnd + 1, 61, "=")
if not k then
return nil, ctx.err, ctx.errAt
end
k = skip(ctx, k)
local ent: any
if sbyte(s, k) == 40 then -- complex instance (A(..) B(..))
local parts = {}
k = skip(ctx, k + 1)
while sbyte(s, k) ~= 41 do
if k > ctx.n then
return nil, "truncated complex instance", k
end
local t, args, k2 = record(ctx, k)
if not t then
return nil, ctx.err, ctx.errAt
end
table.insert(parts, { type = t, args = args })
k = skip(ctx, k2)
end
if #parts == 0 then
return nil, "empty complex instance", k
end
ent = { id = id, type = "COMPLEX", args = {}, parts = parts }
k += 1
else
local t, args, k2 = record(ctx, k)
if not t then
return nil, ctx.err, ctx.errAt
end
ent = { id = id, type = t, args = args }
k = k2
end
local e2 = expect(ctx, k, 59, ";")
if not e2 then
return nil, ctx.err, ctx.errAt
end
if secIndex > 1 then
ent.section = secIndex
end
if res.entities[id] then
res.duplicates += 1
else
res.count += 1
if res.count > maxEntities then
return nil, "LIMIT", i
end
end
res.entities[id] = ent
i = e2
end
elseif word == "ANCHOR" or word == "REFERENCE" or word == "SIGNATURE" then
-- kept as raw text (to the ENDSEC outside strings)
local k = j
local stop: number? = nil
while k <= ctx.n do
local c = sbyte(s, k)
if c == 39 then
local q = k + 1
while true do
local p = sfind(s, "'", q, true)
if not p then
return nil, "unterminated string", k
end
if sbyte(s, p + 1) == 39 then
q = p + 2
else
k = p + 1
break
end
end
elseif c == 69 and at(s, k, "ENDSEC") then
stop = k
break
else
k += 1
end
end
if not stop then
return nil, "truncated " .. word .. " section", i
end
table.insert(res.extra, { name = word, text = ssub(s, j, stop - 1) })
local e2 = expect(ctx, stop + 6, 59, ";")
if not e2 then
return nil, ctx.err, ctx.errAt
end
i = e2
else
return nil, "unknown section " .. tostring(word), i
end
end
if not sawData then
return nil, "no DATA section", i
end
return res, nil, nil
end
return Parse
+252
View File
@@ -0,0 +1,252 @@
--!strict
--!native
-- cad/step/Write: header + entity instances -> ISO 10303-21 text. Values as cad/step/Parse produces them; strings
-- re-escaped (' -> '', \ -> \\, UTF-8 outside printable ASCII -> \X2\..\X0\ / \X4\..\X0\, control bytes and invalid
-- UTF-8 -> \X\hh), reals printed with the fewest digits (15..17) that read back to the same double. Never throws:
-- failures return nil, message.
local Write = {}
local sformat, sbyte, ssub, sfind, floor, huge = string.format, string.byte, string.sub, string.find, math.floor, math.huge
local MAX_DEPTH = 100
-- the shortest %g form that reads back exactly, in Part 21 syntax (a '.' always, upper-case E)
function Write.real(v: number): string?
if v ~= v or v == huge or v == -huge then
return nil
end
local s = sformat("%.15g", v)
if tonumber(s) ~= v then
s = sformat("%.16g", v)
if tonumber(s) ~= v then
s = sformat("%.17g", v)
end
end
s = string.upper(s)
local e = sfind(s, "E", 1, true)
if not sfind(s, ".", 1, true) then
if e then
s = ssub(s, 1, e - 1) .. "." .. ssub(s, e)
else
s ..= "."
end
end
return s
end
local HEX = "0123456789ABCDEF"
local function hex(v: number, k: number): string
local out = table.create(k)
for i = k, 1, -1 do
local d = v % 16
out[i] = ssub(HEX, d + 1, d + 1)
v = floor(v / 16)
end
return table.concat(out)
end
-- a string's Part 21 literal (with the quotes)
function Write.str(s: string): string
if not sfind(s, "[^ -&(-[%]^-~]") then -- printable ASCII without ' and \
return "'" .. s .. "'"
end
local out = { "'" }
local i, n = 1, #s
local wide: number? = nil -- 4 (\X2\) or 8 (\X4\) while in an extended run
local function close()
if wide then
table.insert(out, "\\X0\\")
wide = nil
end
end
while i <= n do
local c = sbyte(s, i) :: number
if c >= 32 and c < 127 then
close()
if c == 39 then
table.insert(out, "''")
elseif c == 92 then
table.insert(out, "\\\\")
else
table.insert(out, string.char(c))
end
i += 1
else
-- a UTF-8 sequence -> code point
local cp: number? = nil
local len = 1
if c >= 0xC2 and c < 0xE0 then
local c2 = sbyte(s, i + 1)
if c2 and c2 >= 0x80 and c2 < 0xC0 then
cp, len = (c - 0xC0) * 64 + (c2 - 0x80), 2
end
elseif c >= 0xE0 and c < 0xF0 then
local c2, c3 = sbyte(s, i + 1, i + 2)
if c2 and c3 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 then
local v = (c - 0xE0) * 4096 + (c2 - 0x80) * 64 + (c3 - 0x80)
if v >= 0x800 and (v < 0xD800 or v >= 0xE000) then
cp, len = v, 3
end
end
elseif c >= 0xF0 and c < 0xF5 then
local c2, c3, c4 = sbyte(s, i + 1, i + 3)
if c2 and c3 and c4 and c2 >= 0x80 and c2 < 0xC0 and c3 >= 0x80 and c3 < 0xC0 and c4 >= 0x80 and c4 < 0xC0 then
local v = (c - 0xF0) * 262144 + (c2 - 0x80) * 4096 + (c3 - 0x80) * 64 + (c4 - 0x80)
if v >= 0x10000 and v < 0x110000 then
cp, len = v, 4
end
end
end
if cp == nil then
close()
table.insert(out, "\\X\\" .. hex(c, 2))
i += 1
else
local k = if cp >= 0x10000 then 8 else 4
if wide ~= k then
close()
table.insert(out, if k == 4 then "\\X2\\" else "\\X4\\")
wide = k
end
table.insert(out, hex(cp, k))
i += len
end
end
end
close()
table.insert(out, "'")
return table.concat(out)
end
local function isName(s: any): boolean
return type(s) == "string" and sfind(s, "^!?[%a_][%w_]*$") ~= nil
end
Write.isName = isName
export type Ctx = { out: { string }, null: any, derived: any, err: string? }
local value: (ctx: Ctx, v: any, real: boolean, depth: number) -> boolean
local function reals(t: any): { [any]: boolean }?
local mt = getmetatable(t)
return if type(mt) == "table" and type(mt.__reals) == "table" then mt.__reals else nil
end
local function list(ctx: Ctx, t: { any }, depth: number): boolean
local out = ctx.out
table.insert(out, "(")
local marks = reals(t)
local n = #t
for i = 1, n do
if i > 1 then
table.insert(out, ",")
end
if not value(ctx, t[i], marks ~= nil and marks[i] == true, depth + 1) then
return false
end
end
table.insert(out, ")")
return true
end
Write.list = list
value = function(ctx: Ctx, v: any, real: boolean, depth: number): boolean
local out = ctx.out
if depth > MAX_DEPTH then
ctx.err = "values nested too deeply (or a cycle)"
return false
end
local tv = type(v)
if tv == "number" then
if not real and v == floor(v) and v > -2 ^ 53 and v < 2 ^ 53 then
table.insert(out, sformat("%.0f", v))
return true
end
local r = Write.real(v)
if not r then
ctx.err = "a number that STEP cannot hold (nan / inf)"
return false
end
table.insert(out, r)
return true
elseif tv == "string" then
table.insert(out, Write.str(v))
return true
elseif tv == "boolean" then
table.insert(out, if v then ".T." else ".F.")
return true
elseif tv == "table" then
if v == ctx.null then
table.insert(out, "$")
return true
elseif v == ctx.derived then
table.insert(out, "*")
return true
end
local ref = v.ref
if ref ~= nil then
if type(ref) ~= "number" or ref ~= floor(ref) or ref < 0 then
ctx.err = "bad entity reference " .. tostring(ref)
return false
end
table.insert(out, sformat("#%.0f", ref))
return true
end
local enum = v.enum
if enum ~= nil then
if type(enum) ~= "string" or not sfind(enum, "^[%a_][%w_]*$") then
ctx.err = "bad enumeration " .. tostring(enum)
return false
end
table.insert(out, "." .. string.upper(enum) .. ".")
return true
end
local bin = v.binary
if bin ~= nil then
if type(bin) ~= "string" or not sfind(bin, "^[0-3]%x*$") then
ctx.err = "bad binary literal"
return false
end
table.insert(out, "\"" .. string.upper(bin) .. "\"")
return true
end
local typed = v.typed
if typed ~= nil then
if not isName(typed) then
ctx.err = "bad typed parameter name " .. tostring(typed)
return false
end
if v.value == nil then
ctx.err = "typed parameter " .. typed .. " without a value"
return false
end
local marks = reals(v)
table.insert(out, string.upper(typed) .. "(")
if not value(ctx, v.value, marks ~= nil and marks.value == true, depth + 1) then
return false
end
table.insert(out, ")")
return true
end
return list(ctx, v, depth)
end
ctx.err = "cannot write a " .. tv .. " value"
return false
end
Write.value = value
-- record(ctx, type, args) -> appends TYPE(args)
function Write.record(ctx: Ctx, t: any, args: any): boolean
if not isName(t) then
ctx.err = "bad entity type " .. tostring(t)
return false
end
if type(args) ~= "table" then
ctx.err = "entity " .. t .. " without an args list"
return false
end
table.insert(ctx.out, string.upper(t))
return list(ctx, args, 0)
end
return Write
+412
View File
@@ -0,0 +1,412 @@
--!strict
-- cad/step: STEP physical files (ISO 10303-21 editions 1-3, "Part 21": AP203 / AP214 / AP242 and any other schema).
-- New code. Reads and writes the entity graph (Types.Cad) fully in-library: the header (FILE_DESCRIPTION / FILE_NAME /
-- FILE_SCHEMA + any other header entity), every DATA section (edition 3 named sections: entity.section), simple and
-- complex instances (type "COMPLEX", parts = { { type, args } }), every parameter kind: integers and reals (numbers;
-- integral reals such as `0.` keep their real-ness through a metatable mark, see Parse), strings (escapes decoded to
-- UTF-8: \S\ \X\ \X2\ \X4\, '' and \\), { enum = "T" } (.T. / .F. booleans too), { ref = id }, { binary = "0FF" },
-- { typed = "LENGTH_MEASURE", value = v }, lists, Step.NULL ($) and Step.DERIVED (*), comments; ANCHOR / REFERENCE /
-- SIGNATURE sections kept as raw text (meta.source.extra) and written back. parse -> write -> parse gives the same
-- entities. Writes one instance per line in id order, strings escaped as Part 21 requires (\X2\ for non-ASCII).
--
-- B-rep bodies and tessellation come from an injected kernel, never required by formats-luau:
-- F.plugins.brep = { read = fn(text, opts) -> { bodies, stats? }, write = fn(bodies, opts) -> text,
-- tessellate = fn(body, opts) -> { positions, normals?, indices (1-based), faceOf? } }
-- or brep-luau's modules as they are: F.plugins.brep = { Step = , StepBrep = , StepWrite = , Tess = }
-- (the full contract is in cad/step/Brep). Step.toBodies(cad, opts) / Step.fromBodies(bodies, opts) /
-- Step.tessellate(cad | bodies, opts) take it from opts.brep or opts.plugins.brep; F.cad.toBodies / fromBodies /
-- tessellate pass F.plugins. Tessellated scenes: one node + mesh per body, one primitive per face colour, z up,
-- millimetres (meta.unit = 0.001).
-- Not supported: STEP-XML (ISO 10303-28), compressed .stpZ, edition 3 value instances (#NAME, @constants: CORRUPT),
-- code pages other than ISO 8859-1 in \S\ escapes (\P?\ is ignored).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Parse = require("@formats/cad/step/Parse")
local Write = require("@formats/cad/step/Write")
local Brep = require("@formats/cad/step/Brep")
-- ------------------------------------------------------------------------------------------------ contract
local Step = {
name = "step",
category = "cad",
extensions = { "step", "stp", "p21" },
mime = { "model/step", "application/step", "application/p21" },
deps = { "core/Err", "core/Bytes", "Types" },
caps = { decode = true, encode = true, complexEntities = true, sections = true, brep = "plugin", tessellate = "plugin" },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxBytes: number?, -- refuse larger files (default 2^30)
maxEntities: number?, -- refuse more instances (default 2^24)
}
export type EncodeOptions = {
schema: string?, -- "AP203" | "AP214" | "AP242" | a schema name: overrides the header's FILE_SCHEMA
name: string?, -- FILE_NAME name (default: the header's, else "model")
timestamp: string?, -- FILE_NAME time_stamp when the header has none (default "1970-01-01T00:00:00")
crlf: boolean?, -- CRLF line ends (default LF)
}
export type BrepOptions = {
brep: any?, -- the plug-in (else opts.plugins.brep)
plugins: { [string]: any }?,
chord: number?, -- tessellation sag in millimetres (default 0.05); opts.tess = the kernel's own options instead
tess: { [string]: any }?,
}
-- ------------------------------------------------------------------------------------------------ constants
Step.NULL = table.freeze({ null = true }) -- $
Step.DERIVED = table.freeze({ derived = true }) -- *
local SCHEMAS = {
AP203 = "CONFIG_CONTROL_DESIGN",
AP214 = "AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }",
AP242 = "AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }",
}
Step.SCHEMAS = SCHEMAS
-- a FILE_SCHEMA name -> "AP203" | "AP214" | "AP242" | the name itself
local function schemaOf(name: string): string
local n = string.upper(string.match(name, "^%s*([^%s{]+)") or name)
if n == "CONFIG_CONTROL_DESIGN" or string.find(n, "^AP203") then
return "AP203"
elseif n == "AUTOMOTIVE_DESIGN" or n == "AUTOMOTIVE_DESIGN_CC2" or string.find(n, "^AP214") then
return "AP214"
elseif string.find(n, "^AP242") then
return "AP242"
end
return n
end
Step.schemaOf = schemaOf
-- ------------------------------------------------------------------------------------------------ sniff
function Step.sniff(r: Bytes.Reader): number
local head = r:peek(256)
if string.sub(head, 1, 3) == "\239\187\191" then
head = string.sub(head, 4)
end
head = string.gsub(head, "^%s*/%*.-%*/", "")
if string.find(head, "^%s*ISO%-10303%-21%s*;") then
return 1
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Step.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Cad?, Err.Err?)
local size = r.limit - r.base
if size > (opts and opts.maxBytes or 2 ^ 30) then
return nil, Err.new(Err.LIMIT, "file over maxBytes")
end
local s = buffer.readstring(r.buf, r.base, size)
local bom = 0
if string.sub(s, 1, 3) == "\239\187\191" then
s = string.sub(s, 4)
bom = 3
end
local res, msg, at = Parse.parse(s, Step.NULL, Step.DERIVED, opts and opts.maxEntities or 2 ^ 24)
if not res then
local off = if at then r.base + bom + at - 1 else nil
if msg == "LIMIT" then
return nil, Err.new(Err.LIMIT, "more entity instances than maxEntities", off)
end
local m = msg or "parse error"
if string.find(m, "^truncated") or string.find(m, "^unterminated") or (at and at > #s) then
return nil, Err.new(Err.TRUNCATED, m, off)
end
return nil, Err.new(Err.CORRUPT, m, off)
end
local fs = res.header.FILE_SCHEMA
local schemaName = if fs and type(fs[1]) == "table" and type(fs[1][1]) == "string" then fs[1][1] else ""
local cad: Types.Cad = {
kind = "cad",
schema = if schemaName ~= "" then schemaOf(schemaName) else "unknown",
header = res.header,
entities = res.entities,
meta = {
count = res.count,
headerOrder = res.headerOrder,
source = {
format = "step",
schemaName = schemaName,
sections = res.sections,
extra = if #res.extra > 0 then res.extra else nil,
duplicates = if res.duplicates > 0 then res.duplicates else nil,
terminated = res.terminated,
},
},
}
return cad, nil
end
-- ------------------------------------------------------------------------------------------------ encode
local function headerArgs(cad: Types.Cad, o: EncodeOptions): { [string]: { any } }
local h = if type(cad.header) == "table" then cad.header else {}
local out: { [string]: { any } } = {}
for k, v in h do
out[k] = v
end
if type(out.FILE_DESCRIPTION) ~= "table" then
out.FILE_DESCRIPTION = { { "formats-luau" }, "2;1" }
end
if type(out.FILE_NAME) ~= "table" then
out.FILE_NAME = { o.name or "model", o.timestamp or "1970-01-01T00:00:00", { "" }, { "" }, "formats-luau", "formats-luau", "" }
end
local schema = o.schema or (if type(out.FILE_SCHEMA) ~= "table" then cad.schema else nil)
if schema then
out.FILE_SCHEMA = { { SCHEMAS[schema] or schema } }
end
return out
end
function Step.encode(cad: Types.Cad, opts: EncodeOptions?): (buffer?, Err.Err?)
if type(cad) ~= "table" or cad.kind ~= "cad" or type(cad.entities) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Cad (kind = \"cad\", entities)")
end
local o: EncodeOptions = opts or {}
local nl = if o.crlf then "\r\n" else "\n"
local ctx: Write.Ctx = { out = {}, null = Step.NULL, derived = Step.DERIVED, err = nil }
local out = ctx.out
table.insert(out, "ISO-10303-21;" .. nl .. "HEADER;" .. nl)
local header = headerArgs(cad, o)
local order = { "FILE_DESCRIPTION", "FILE_NAME", "FILE_SCHEMA" }
local seen = { FILE_DESCRIPTION = true, FILE_NAME = true, FILE_SCHEMA = true }
local meta: any = if type(cad.meta) == "table" then cad.meta else {}
local rest = {}
for _, k in (if type(meta.headerOrder) == "table" then meta.headerOrder else {}) do
if type(k) == "string" and header[k] and not seen[k] then
seen[k] = true
table.insert(order, k)
end
end
for k in header do
if type(k) == "string" and not seen[k] then
table.insert(rest, k)
end
end
table.sort(rest)
for _, k in rest do
table.insert(order, k)
end
for _, k in order do
if not Write.record(ctx, k, header[k]) then
return nil, Err.new(Err.ARG, "header " .. tostring(k) .. ": " .. tostring(ctx.err))
end
table.insert(out, ";" .. nl)
end
table.insert(out, "ENDSEC;" .. nl)
local source = if type(meta.source) == "table" then meta.source else {}
if type(source.extra) == "table" then
for _, x in source.extra do
if type(x) == "table" and type(x.name) == "string" and type(x.text) == "string" then
table.insert(out, x.name .. x.text .. "ENDSEC;" .. nl)
end
end
end
-- entities by section, in id order
local ids = {}
for id, e in cad.entities do
if type(id) ~= "number" or id ~= math.floor(id) or id < 0 or type(e) ~= "table" then
return nil, Err.new(Err.ARG, "entity ids must be non-negative integers (" .. tostring(id) .. ")")
end
table.insert(ids, id)
end
table.sort(ids)
local sections = if type(source.sections) == "table" and #source.sections > 1 then source.sections else { {} }
for si, sec in sections do
if #sections > 1 then
table.insert(out, "DATA")
local params = {}
if sec.name ~= nil then
params[1] = sec.name
params[2] = if sec.schema ~= nil then sec.schema else {}
if not Write.list(ctx, params, 0) then
return nil, Err.new(Err.ARG, "section " .. si .. ": " .. tostring(ctx.err))
end
end
table.insert(out, ";" .. nl)
else
table.insert(out, "DATA;" .. nl)
end
for _, id in ids do
local e: any = cad.entities[id]
local esec = if type(e.section) == "number" then e.section else 1
if #sections == 1 or esec == si or (si == 1 and (esec < 1 or esec > #sections)) then
table.insert(out, string.format("#%.0f=", id))
if e.type == "COMPLEX" or type(e.parts) == "table" then
if type(e.parts) ~= "table" or #e.parts == 0 then
return nil, Err.new(Err.ARG, "#" .. id .. ": a complex instance without parts")
end
table.insert(out, "(")
for _, p in e.parts do
if type(p) ~= "table" or not Write.record(ctx, p.type, p.args) then
return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err or "bad part"))
end
end
table.insert(out, ")")
elseif not Write.record(ctx, e.type, e.args) then
return nil, Err.new(Err.ARG, "#" .. id .. ": " .. tostring(ctx.err))
end
table.insert(out, ";" .. nl)
end
end
table.insert(out, "ENDSEC;" .. nl)
end
table.insert(out, "END-ISO-10303-21;" .. nl)
return buffer.fromstring(table.concat(out)), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- get(cad, id | { ref = id }) -> the entity
function Step.get(cad: Types.Cad, id: any): Types.StepEntity?
if type(id) == "table" then
id = id.ref
end
return cad.entities[id]
end
-- ids(cad) -> the instance ids in ascending order
function Step.ids(cad: Types.Cad): { number }
local out = {}
for id in cad.entities do
table.insert(out, id)
end
table.sort(out)
return out
end
-- byType(cad, "ADVANCED_FACE") -> the ids of the instances of that type (complex ones with such a part too), ascending
function Step.byType(cad: Types.Cad, name: string): { number }
local n = string.upper(name)
local out = {}
for id, e in cad.entities do
if e.type == n then
table.insert(out, id)
elseif e.parts then
for _, p in e.parts do
if p.type == n then
table.insert(out, id)
break
end
end
end
end
table.sort(out)
return out
end
-- part(entity, "TYPE") -> the args of that type (the entity's own, or one part of a complex instance)
function Step.part(e: Types.StepEntity?, name: string): { any }?
if not e then
return nil
end
if e.type == name then
return e.args
end
if e.parts then
for _, p in e.parts do
if p.type == name then
return p.args
end
end
end
return nil
end
-- add(cad, type, args) -> id: a new instance after the highest id
function Step.add(cad: Types.Cad, type: string, args: { any }): number
local top = 0
for id in cad.entities do
if id > top then
top = id
end
end
local id = top + 1
cad.entities[id] = { id = id, type = string.upper(type), args = args }
cad.meta.count = (cad.meta.count or 0) + 1
return id
end
-- real(list, index) -> list: marks list[index] as a real (an integral value is then written `3.`, not `3`)
function Step.real(t: { [any]: any }, key: any): { [any]: any }
local mt: any = getmetatable(t)
if not mt then
mt = { __reals = {} }
setmetatable(t, mt)
end
mt.__reals[key] = true
return t
end
-- new(schema?) -> an empty Cad ("AP214" by default)
function Step.new(schema: string?): Types.Cad
return { kind = "cad", schema = schema or "AP214", header = {}, entities = {}, meta = { count = 0 } }
end
-- plugin(p) -> the normalised B-rep plug-in interface (see cad/step/Brep) | nil, reason
Step.plugin = Brep.plugin
local function textOf(cad: Types.Cad): (string?, Err.Err?)
local buf, err = Step.encode(cad)
if not buf then
return nil, err
end
return buffer.tostring(buf), nil
end
-- toBodies(cad, opts) -> bodies, result (the plug-in's read result: stats, warnings, ...) | nil, Err
function Step.toBodies(cad: Types.Cad, opts: BrepOptions?): (({ any })?, any)
local plug, perr = Brep.find(opts)
if not plug then
return nil, perr
end
local text, err = textOf(cad)
if not text then
return nil, err
end
local bodies, res, rerr = Brep.read(plug, text, opts)
if not bodies then
return nil, rerr
end
return bodies, res
end
-- fromBodies(bodies, opts) -> Cad (the plug-in writes STEP text, parsed here) | nil, Err
function Step.fromBodies(bodies: { any }, opts: BrepOptions?): (Types.Cad?, Err.Err?)
if type(bodies) ~= "table" then
return nil, Err.new(Err.ARG, "needs a list of bodies")
end
local plug, perr = Brep.find(opts)
if not plug then
return nil, perr
end
local text, err = Brep.write(plug, bodies, opts)
if not text then
return nil, err
end
return Step.decode(Bytes.reader(buffer.fromstring(text)))
end
-- tessellate(cad | bodies, opts) -> Scene (one node + mesh per body, z up, millimetres) | nil, Err
function Step.tessellate(value: any, opts: BrepOptions?): (Types.Scene?, Err.Err?)
local plug, perr = Brep.find(opts)
if not plug then
return nil, perr
end
local bodies = value
if type(value) == "table" and value.kind == "cad" then
local b, err = Step.toBodies(value, opts)
if not b then
return nil, err
end
bodies = b
end
if type(bodies) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Cad or a list of bodies")
end
return Brep.scene(plug, bodies, opts)
end
return Step
+30 -1
View File
@@ -255,11 +255,15 @@ end
-- so the api hands decoders opts.decodeImage(buf) -> Image | nil, Err and encoders opts.encodeImage(img, format) ->
-- buffer | nil, Err (unless the caller passed its own). Formats work without them (returning Err.UNSUPPORTED for
-- the embedded parts) when called directly.
-- They also see the injected plug-ins as opts.plugins (F.plugins: the B-rep kernel for cad/step) unless given their own.
local function withHooks(o: Options): Options
if o.decodeImage ~= nil and o.encodeImage ~= nil then
if o.decodeImage ~= nil and o.encodeImage ~= nil and o.plugins ~= nil then
return o
end
local c = table.clone(o)
if c.plugins == nil then
c.plugins = F.plugins
end
if c.decodeImage == nil then
c.decodeImage = function(b: buffer): (any, Err.Err?)
return F.load(b, { category = "image" })
@@ -539,6 +543,31 @@ for category in Types.CATEGORIES do
end
F.data.null = Types.null
-- F.cad.toBodies(cad, opts?) -> bodies, result | nil, Err; F.cad.fromBodies(bodies, opts?) -> Cad | nil, Err;
-- F.cad.tessellate(cad | bodies, opts?) -> Scene | nil, Err: cad/step's B-rep calls with the injected kernel
-- (F.plugins.brep, unless opts.brep / opts.plugins is given). Without a plug-in they return Err.UNSUPPORTED.
for _, fn in { "toBodies", "fromBodies", "tessellate" } do
local name: string = fn
F.cad[name] = function(value: any, opts: Options?): (any, any)
local o = if opts then table.clone(opts) else {}
if o.plugins == nil then
o.plugins = F.plugins
end
local m, err = F.format("step")
if not m then
return nil, err
end
local ok, a, b = pcall(m[name], value, o)
if not ok then
return nil, Err.wrap(Err.new(Err.CORRUPT, name .. " threw: " .. tostring(a)), "step")
end
if a == nil and type(b) == "table" and b.code then
return nil, Err.wrap(b, "step")
end
return a, b
end
end
-- F.model.loadTextures(scene, opts?) -> scene, { [index]: Err }: decodes each texture's encoded bytes (texture.data, or
-- texture.uri through opts.resolve) into texture.image with F.image.load. Model formats never decode images
-- themselves (a format does not require another format); this is the lazy step at the api layer. Textures whose
+598
View File
@@ -0,0 +1,598 @@
--!strict
-- model/3mf/Read: a 3MF package (an OPC zip) -> Scene. The root model part from _rels/.rels (fallback: the first
-- *.model under 3D/), other model parts referenced by the production extension's p:path (components and build items),
-- core resources (objects with mesh vertices / triangles, components with transforms), the materials extension
-- (basematerials, colorgroup, texture2d + texture2dgroup, compositematerials blended into one colour per entry,
-- multiproperties resolved through their first layer), build items with transforms -> root nodes, metadata, the unit.
-- Triangles are grouped into one primitive per property (a base material, a colour group, a texture group); colour and
-- texture groups give per-corner COLOR_0 / TEXCOORD_0, so vertices are split where corners of one vertex differ.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Xml = require("@formats/codecs/Xml")
local Zip = require("@formats/containers/Zip")
local Read = {}
local REL_MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"
local UNITS = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 }
Read.UNITS = UNITS
local WRAP = { wrap = "repeat", mirror = "mirror", clamp = "clamp", none = "clamp" }
local MAX_DEPTH = 64
local localName = Xml.localName
-- an attribute by local name (namespaced attributes such as p:path)
local function attr(node: any, name: string): string?
local a = node.attrs
local v = a[name]
if v ~= nil then
return v
end
for k, x in next, a do
if type(k) == "string" and localName(k) == name then
return x
end
end
return nil
end
local function int(s: string?): number?
local n = if s then tonumber(s) else nil
if n and n == math.floor(n) and n >= 0 then
return n
end
return nil
end
-- "#RRGGBB" / "#RRGGBBAA" -> { r, g, b, a } sRGB 0..1
local function hexColor(s: string?): { number }?
if type(s) ~= "string" then
return nil
end
local h = string.match(s, "^%s*#(%x+)%s*$")
if not h or (#h ~= 6 and #h ~= 8) then
return nil
end
local function c(i: number): number
return (tonumber(string.sub(h :: string, i, i + 1), 16) :: number) / 255
end
return { c(1), c(3), c(5), if #h == 8 then c(7) else 1 }
end
Read.hexColor = hexColor
function Read.toLinear(c: number): number
if c <= 0.04045 then
return c / 12.92
end
return ((c + 0.055) / 1.055) ^ 2.4
end
local toLinear = Read.toLinear
-- "m00 m01 m02 m10 ... m32" (3MF row-vector convention) -> a column-major glTF matrix, nil for identity / invalid
local function transform(s: string?): ({ number }?, boolean)
if not s then
return nil, true
end
local v = {}
for w in string.gmatch(s, "%S+") do
local n = tonumber(w)
if not n or n ~= n or n == math.huge or n == -math.huge then
return nil, false
end
table.insert(v, n)
end
if #v ~= 12 then
return nil, false
end
local m = { v[1], v[2], v[3], 0, v[4], v[5], v[6], 0, v[7], v[8], v[9], 0, v[10], v[11], v[12], 1 }
for i = 1, 16 do
if m[i] ~= Types.Scene.IDENTITY[i] then
return m, true
end
end
return nil, true
end
local function normPath(p: string): string
p = string.gsub(p, "\\", "/")
p = string.gsub(p, "^/+", "")
return p
end
-- one model part parsed into its resources and build
type Model = { path: string, unit: string?, metadata: { [string]: string }, res: { [number]: any }, items: { any }, required: string? }
local function parseModel(text: string, path: string, opts: any): (Model?, Err.Err?)
local doc, err = Xml.decode(text, { parents = false })
if not doc then
return nil, err
end
local root = (doc :: any).root
if not root or localName(root.name) ~= "model" then
return nil, Err.new(Err.CORRUPT, path .. ": the root element is not <model>")
end
local maxV = opts.maxVertices or 2 ^ 25
local model: Model = { path = path, unit = attr(root, "unit"), metadata = {}, res = {}, items = {}, required = attr(root, "requiredextensions") }
local resources: any = nil
local build: any = nil
for _, ch in Xml.children(root) do
local ln = localName(ch.name)
if ln == "metadata" then
local n = attr(ch, "name")
if n then
model.metadata[n] = Xml.text(ch)
end
elseif ln == "resources" then
resources = ch
elseif ln == "build" then
build = ch
end
end
local total = 0
if resources then
for _, r in Xml.children(resources) do
local ln = localName(r.name)
local id = int(attr(r, "id"))
if id == nil then
continue
end
if ln == "object" then
local o: any = { kind = "object", id = id, name = attr(r, "name"), type = attr(r, "type") or "model", pid = int(attr(r, "pid")), pindex = int(attr(r, "pindex")), partnumber = attr(r, "partnumber") }
local mesh = Xml.child(r, "mesh")
local comps = Xml.child(r, "components")
if mesh then
local verts = Xml.child(mesh, "vertices")
local tris = Xml.child(mesh, "triangles")
local vl = if verts then Xml.children(verts, "vertex") else {}
local tl = if tris then Xml.children(tris, "triangle") else {}
total += #vl + #tl * 3
if total > maxV then
return nil, Err.new(Err.LIMIT, "more than " .. maxV .. " vertices / corners")
end
local nv = #vl
local pos = table.create(nv * 3, 0)
for i, v in vl do
local a = v.attrs
local x, y, z = tonumber(a.x), tonumber(a.y), tonumber(a.z)
if not x or not y or not z then
return nil, Err.new(Err.CORRUPT, "object " .. id .. ": bad vertex " .. i)
end
pos[i * 3 - 2], pos[i * 3 - 1], pos[i * 3] = x, y, z
end
local nt = #tl
local tv = table.create(nt * 3, 0)
local tp = table.create(nt * 4, -1) -- pid, p1, p2, p3 (-1 = none)
for i, tri in tl do
local a = tri.attrs
local v1, v2, v3 = int(a.v1), int(a.v2), int(a.v3)
if not v1 or not v2 or not v3 or v1 >= nv or v2 >= nv or v3 >= nv then
return nil, Err.new(Err.CORRUPT, "object " .. id .. ": triangle " .. i .. " has a bad vertex index")
end
tv[i * 3 - 2], tv[i * 3 - 1], tv[i * 3] = v1, v2, v3
local b = i * 4 - 4
local pid, p1, p2, p3 = int(a.pid), int(a.p1), int(a.p2), int(a.p3)
tp[b + 1] = pid or -1
tp[b + 2] = p1 or -1
tp[b + 3] = p2 or p1 or -1
tp[b + 4] = p3 or p1 or -1
end
o.positions, o.tv, o.tp, o.nt = pos, tv, tp, nt
end
if comps then
o.components = {}
for _, c in Xml.children(comps, "component") do
local oid = int(attr(c, "objectid"))
local m, ok = transform(attr(c, "transform"))
if oid and ok then
table.insert(o.components, { objectid = oid, matrix = m, path = attr(c, "path") })
end
end
end
model.res[id] = o
elseif ln == "basematerials" then
local items = {}
for _, b in Xml.children(r, "base") do
table.insert(items, { name = attr(b, "name"), color = hexColor(attr(b, "displaycolor")) or { 1, 1, 1, 1 }, hex = attr(b, "displaycolor") })
end
model.res[id] = { kind = "base", id = id, items = items }
elseif ln == "colorgroup" then
local items = {}
for _, c in Xml.children(r, "color") do
table.insert(items, hexColor(attr(c, "color")) or { 1, 1, 1, 1 })
end
model.res[id] = { kind = "color", id = id, items = items }
elseif ln == "texture2d" then
model.res[id] = { kind = "texture", id = id, path = attr(r, "path"), contenttype = attr(r, "contenttype"), tileu = attr(r, "tilestyleu"), tilev = attr(r, "tilestylev"), filter = attr(r, "filter") }
elseif ln == "texture2dgroup" then
local uvs = {}
for _, c in Xml.children(r, "tex2coord") do
table.insert(uvs, tonumber(attr(c, "u")) or 0)
table.insert(uvs, tonumber(attr(c, "v")) or 0)
end
model.res[id] = { kind = "texgroup", id = id, texid = int(attr(r, "texid")), uvs = uvs, count = #uvs // 2 }
elseif ln == "compositematerials" then
local mats = {}
for w in string.gmatch(attr(r, "matindices") or "", "%S+") do
table.insert(mats, tonumber(w) or 0)
end
local items = {}
for _, c in Xml.children(r, "composite") do
local vals = {}
for w in string.gmatch(attr(c, "values") or "", "%S+") do
table.insert(vals, tonumber(w) or 0)
end
table.insert(items, vals)
end
model.res[id] = { kind = "composite", id = id, matid = int(attr(r, "matid")), matindices = mats, items = items }
elseif ln == "multiproperties" then
local pids = {}
for w in string.gmatch(attr(r, "pids") or "", "%S+") do
table.insert(pids, tonumber(w) or -1)
end
local items = {}
for _, c in Xml.children(r, "multi") do
local ix = {}
for w in string.gmatch(attr(c, "pindices") or "", "%S+") do
table.insert(ix, tonumber(w) or 0)
end
table.insert(items, ix)
end
model.res[id] = { kind = "multi", id = id, pids = pids, items = items }
end
end
end
if build then
for _, it in Xml.children(build, "item") do
local oid = int(attr(it, "objectid"))
local m, ok = transform(attr(it, "transform"))
if oid and ok then
table.insert(model.items, { objectid = oid, matrix = m, path = attr(it, "path"), partnumber = attr(it, "partnumber") })
end
end
end
return model, nil
end
-- the root model part's path
local function rootPath(zip: any): string?
local rels = zip:readString("_rels/.rels")
if rels then
local doc = Xml.decode(rels, { parents = false })
if doc then
for _, rel in Xml.descendants((doc :: any).root or doc, "Relationship") do
local t, target = attr(rel, "Type"), attr(rel, "Target")
if t and target and (t == REL_MODEL or string.find(t, "/3dmodel$")) then
return normPath(target)
end
end
end
end
for _, e in zip:list() do
if not e.isDir and string.find(string.lower(e.name), "%.model$") then
return e.name
end
end
return nil
end
function Read.scene(zip: any, opts: any): (Types.Scene?, Err.Err?)
local rootP = rootPath(zip)
if not rootP then
return nil, Err.new(Err.CORRUPT, "no 3D model part in the package")
end
local models: { [string]: Model } = {}
local function getModel(path: string): (Model?, Err.Err?)
local p = normPath(path)
local m = models[p]
if m then
return m, nil
end
local text, err = zip:readString(p)
if not text then
return nil, err or Err.new(Err.CORRUPT, "missing model part " .. p)
end
if string.sub(text, 1, 5) == "%3McF" then
return nil, Err.new(Err.UNSUPPORTED, "secure content extension: " .. p .. " is encrypted / wrapped")
end
local mm, perr = parseModel(text, p, opts)
if not mm then
return nil, perr
end
models[p] = mm
return mm, nil
end
local root, rerr = getModel(rootP)
if not root then
return nil, rerr
end
local scene = Types.Scene.new()
local unitName = root.unit or "millimeter"
scene.meta.up = "z"
scene.meta.unit = UNITS[unitName] or 1e-3
scene.meta.metadata = root.metadata
scene.meta.source = { format = "3mf", unit = unitName, part = rootP, requiredExtensions = root.required }
-- textures and materials (shared across model parts by part path + resource id)
local texCache: { [string]: number } = {}
local function texture(model: Model, id: number): number?
local key = model.path .. "#" .. id
if texCache[key] then
return texCache[key]
end
local r = model.res[id]
if not r or r.kind ~= "texture" or type(r.path) ~= "string" then
return nil
end
local data = zip:read(normPath(r.path))
local tex: Types.Texture = {
name = r.path,
data = data,
mime = r.contenttype,
uri = r.path,
sampler = { wrapS = WRAP[r.tileu or "wrap"] or "repeat", wrapT = WRAP[r.tilev or "wrap"] or "repeat", filter = if r.filter == "nearest" or r.filter == "linear" then r.filter else nil },
extras = { ["3mf"] = { id = id, tilestyleu = r.tileu, tilestylev = r.tilev, filter = r.filter } },
}
table.insert(scene.textures, tex)
texCache[key] = #scene.textures
return #scene.textures
end
local matCache: { [string]: number } = {}
local function addMaterial(key: string, make: () -> Types.Material): number
local i = matCache[key]
if i then
return i
end
table.insert(scene.materials, make())
matCache[key] = #scene.materials
return #scene.materials
end
local function colorMaterial(name: string?, c: { number }, extras: any): Types.Material
local m = Types.Scene.material(name)
m.baseColor = { toLinear(c[1]), toLinear(c[2]), toLinear(c[3]), c[4] }
m.metallic = 0
m.roughness = 1
if c[4] < 1 then
m.alphaMode = "blend"
end
m.extras = { ["3mf"] = extras }
return m
end
-- property of one corner -> (group key, material index?, kind, resource, index)
local function resolve(model: Model, pid: number, p: number, depth: number?): (string, number?, string, any, number)
local r = model.res[pid]
if not r or p < 0 then
return "none", nil, "none", nil, 0
end
local k = r.kind
if k == "base" then
local item = r.items[p + 1]
if not item then
return "none", nil, "none", nil, 0
end
local key = "b" .. model.path .. "#" .. pid .. ":" .. p
return key, addMaterial(key, function()
return colorMaterial(item.name, item.color, { group = pid, index = p, displaycolor = item.hex })
end), "base", r, p
elseif k == "color" then
return "c" .. model.path .. "#" .. pid, nil, "color", r, p
elseif k == "texgroup" then
local ti = r.texid and texture(model, r.texid)
local mat: number? = nil
if ti then
local mk = "t" .. model.path .. "#" .. (r.texid :: number)
mat = addMaterial(mk, function()
local m = Types.Scene.material("texture " .. tostring(r.texid))
m.metallic = 0
m.roughness = 1
m.baseColorTexture = { texture = ti :: number }
m.extras = { ["3mf"] = { texture = r.texid } }
return m
end)
end
return "t" .. model.path .. "#" .. pid, mat, "tex", r, p
elseif k == "composite" then
local item = r.items[p + 1]
local base = r.matid and model.res[r.matid]
if not item or not base or base.kind ~= "base" then
return "none", nil, "none", nil, 0
end
local key = "x" .. model.path .. "#" .. pid .. ":" .. p
return key, addMaterial(key, function()
local c, sum = { 0, 0, 0, 0 }, 0
for j, w in item do
local b = base.items[(r.matindices[j] or 0) + 1]
if b then
for q = 1, 4 do
c[q] += b.color[q] * w
end
sum += w
end
end
if sum > 0 then
for q = 1, 4 do
c[q] /= sum
end
else
c = { 1, 1, 1, 1 }
end
return colorMaterial("composite " .. pid .. ":" .. p, c, { composite = pid, index = p })
end), "base", r, p
elseif k == "multi" and (depth or 0) < 1 then
local item = r.items[p + 1]
local first = r.pids[1]
if item and first then
return resolve(model, first, item[1] or 0, 1)
end
end
return "none", nil, "none", nil, 0
end
-- one Scene mesh per (part, object) with a mesh
local meshCache: { [string]: number } = {}
local function buildMesh(model: Model, o: any): number?
local key = model.path .. "#" .. o.id
local cached = meshCache[key]
if cached ~= nil then
return if cached > 0 then cached else nil
end
local groups: { [string]: any } = {}
local order: { any } = {}
local pos, tv, tp = o.positions, o.tv, o.tp
for t = 0, o.nt - 1 do
local pid = tp[t * 4 + 1]
local ps = { tp[t * 4 + 2], tp[t * 4 + 3], tp[t * 4 + 4] }
if pid < 0 then
pid = o.pid or -1
if ps[1] < 0 then
local d = o.pindex or (if pid >= 0 then 0 else -1)
ps = { d, d, d }
end
end
local gkey, mat, kind, res, _ = resolve(model, pid, ps[1])
local g = groups[gkey]
if not g then
g = { kind = kind, res = res, material = mat, vmap = {}, pos = {}, attr = {}, idx = {}, n = 0 }
groups[gkey] = g
table.insert(order, g)
end
for c = 1, 3 do
local v = tv[t * 3 + c]
local vk = v
local pc = 0
if kind == "color" or kind == "tex" then
pc = ps[c]
local cnt = if kind == "color" then #res.items else res.count
if pc < 0 or pc >= cnt then
pc = ps[1]
end
if pc < 0 or pc >= cnt then
pc = 0
end
vk = v * (cnt + 1) + pc
end
local ni = g.vmap[vk]
if not ni then
ni = g.n
g.n += 1
g.vmap[vk] = ni
table.insert(g.pos, pos[v * 3 + 1])
table.insert(g.pos, pos[v * 3 + 2])
table.insert(g.pos, pos[v * 3 + 3])
if kind == "color" then
local col = res.items[pc + 1] or { 1, 1, 1, 1 }
table.insert(g.attr, toLinear(col[1]))
table.insert(g.attr, toLinear(col[2]))
table.insert(g.attr, toLinear(col[3]))
table.insert(g.attr, col[4])
elseif kind == "tex" then
table.insert(g.attr, res.uvs[pc * 2 + 1] or 0)
table.insert(g.attr, 1 - (res.uvs[pc * 2 + 2] or 0))
end
end
table.insert(g.idx, ni)
end
end
local mesh: Types.Mesh = { name = o.name, primitives = {}, extras = { ["3mf"] = { id = o.id, part = model.path, type = o.type, partnumber = o.partnumber } } }
for _, g in order do
local n = g.n
local pa = Types.Scene.accessor(nil, "f32", 3, n)
for i, x in g.pos do
buffer.writef32(pa.data, (i - 1) * 4, x)
end
local ia = Types.Scene.accessor(nil, "u32", 1, #g.idx)
for i, x in g.idx do
buffer.writeu32(ia.data, (i - 1) * 4, x)
end
local prim: Types.Primitive = { attributes = { POSITION = pa }, indices = ia, mode = "triangles", material = g.material }
if g.kind == "color" then
local ca = Types.Scene.accessor(nil, "f32", 4, n)
for i, x in g.attr do
buffer.writef32(ca.data, (i - 1) * 4, x)
end
prim.attributes.COLOR_0 = ca
prim.extras = { ["3mf"] = { colorgroup = g.res.id } }
elseif g.kind == "tex" then
local ua = Types.Scene.accessor(nil, "f32", 2, n)
for i, x in g.attr do
buffer.writef32(ua.data, (i - 1) * 4, x)
end
prim.attributes.TEXCOORD_0 = ua
prim.extras = { ["3mf"] = { texture2dgroup = g.res.id } }
end
table.insert(mesh.primitives, prim)
end
if #mesh.primitives == 0 then
meshCache[key] = 0
return nil
end
table.insert(scene.meshes, mesh)
meshCache[key] = #scene.meshes
return #scene.meshes
end
-- nodes: one per object instance (build items and components)
local nodeCount = 0
local maxNodes = opts.maxNodes or 2 ^ 20
local instantiate: (model: Model, oid: number, matrix: { number }?, depth: number, extra: any) -> (number?, Err.Err?)
function instantiate(model: Model, oid: number, matrix: { number }?, depth: number, extra: any): (number?, Err.Err?)
if depth > MAX_DEPTH then
return nil, Err.new(Err.CORRUPT, "components nested deeper than " .. MAX_DEPTH .. " (a cycle?)")
end
nodeCount += 1
if nodeCount > maxNodes then
return nil, Err.new(Err.LIMIT, "more than " .. maxNodes .. " object instances")
end
local o = model.res[oid]
if not o or o.kind ~= "object" then
return nil, Err.new(Err.CORRUPT, "no object " .. oid .. " in " .. model.path)
end
local node: Types.Node = { name = o.name, children = {}, matrix = matrix, extras = { ["3mf"] = extra or { objectid = oid } } }
table.insert(scene.nodes, node)
local index = #scene.nodes
if o.positions then
node.mesh = buildMesh(model, o)
end
if o.components then
for _, c in o.components do
local m: Model? = model
if c.path then
local mm, err = getModel(c.path)
if not mm then
return nil, err
end
m = mm
end
local child, err = instantiate(m :: Model, c.objectid, c.matrix, depth + 1, { objectid = c.objectid, path = c.path })
if not child then
return nil, err
end
table.insert(node.children, child)
end
end
return index, nil
end
for _, it in root.items do
local m: Model? = root
if it.path then
local mm, err = getModel(it.path)
if not mm then
return nil, err
end
m = mm
end
local idx, err = instantiate(m :: Model, it.objectid, it.matrix, 0, { objectid = it.objectid, path = it.path, partnumber = it.partnumber, item = true })
if not idx then
return nil, err
end
table.insert(scene.roots, idx)
end
return scene, nil
end
function Read.open(r: any): (any, Err.Err?)
return Zip.open(r)
end
return Read
+417
View File
@@ -0,0 +1,417 @@
--!strict
-- model/3mf/Write: Scene -> a 3MF package. One mesh object per Scene mesh (every triangle primitive: triangles,
-- strips, fans, polygons fan-split; points and lines are skipped), one build item per node with a mesh, carrying the
-- node's world matrix (the hierarchy is flattened). Materials go into one basematerials group (sRGB display colours),
-- primitives with COLOR_0 into a colorgroup, primitives with TEXCOORD_0 and a material whose baseColorTexture has
-- PNG / JPEG bytes into a texture2d + texture2dgroup (the image stored in the package under 3D/Textures/).
-- Units: meta.unit picks the 3MF unit when it is one of them; otherwise millimetres and the build transforms scale.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Xml = require("@formats/codecs/Xml")
local Zip = require("@formats/containers/Zip")
local Write = {}
local NS_CORE = "http://schemas.microsoft.com/3dmanufacturing/core/2015/02"
local NS_MAT = "http://schemas.microsoft.com/3dmanufacturing/material/2015/02"
local REL_MODEL = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"
local REL_TEXTURE = "http://schemas.microsoft.com/3dmanufacturing/2013/01/3dtexture"
local UNIT_ORDER = { "micron", "millimeter", "centimeter", "inch", "foot", "meter" }
local UNITS = { micron = 1e-6, millimeter = 1e-3, centimeter = 1e-2, inch = 0.0254, foot = 0.3048, meter = 1 }
local TEX_EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg" }
local fmt = string.format
local esc = Xml.escapeAttr
local function num(x: number): string
if x ~= x or x == math.huge or x == -math.huge then
return "0"
end
if x == math.floor(x) and math.abs(x) < 1e15 then
return fmt("%d", x)
end
return fmt("%.9g", x)
end
local function toSrgb(c: number): number
c = math.clamp(c, 0, 1)
if c <= 0.0031308 then
return c * 12.92
end
return 1.055 * c ^ (1 / 2.4) - 0.055
end
local function hex(r: number, g: number, b: number, a: number): string
local function q(x: number): number
return math.clamp(math.floor(x * 255 + 0.5), 0, 255)
end
return fmt("#%02X%02X%02X%02X", q(toSrgb(r)), q(toSrgb(g)), q(toSrgb(b)), q(math.clamp(a, 0, 1)))
end
-- the triangle corner list of a primitive (0-based vertex indices) or nil
local function triangles(prim: any): { number }?
local pos = prim.attributes and prim.attributes.POSITION
if type(pos) ~= "table" then
return nil
end
local n = pos.count
local ix: { number } = {}
if prim.indices then
local get = Types.Scene.reader(prim.indices)
if not get then
return nil
end
for i = 0, prim.indices.count - 1 do
ix[i + 1] = get(i, 0)
end
else
for i = 1, n do
ix[i] = i - 1
end
end
for _, v in ix do
if v ~= v or v < 0 or v >= n then
return nil
end
end
local mode = prim.mode or "triangles"
local out: { number } = {}
local function tri(a: number, b: number, c: number)
if a ~= b and b ~= c and a ~= c then
table.insert(out, a)
table.insert(out, b)
table.insert(out, c)
end
end
if mode == "triangles" then
for i = 1, #ix - 2, 3 do
tri(ix[i], ix[i + 1], ix[i + 2])
end
elseif mode == "triangle_strip" then
for i = 1, #ix - 2 do
if i % 2 == 1 then
tri(ix[i], ix[i + 1], ix[i + 2])
else
tri(ix[i + 1], ix[i], ix[i + 2])
end
end
elseif mode == "triangle_fan" then
for i = 2, #ix - 1 do
tri(ix[1], ix[i], ix[i + 1])
end
elseif mode == "polygons" and prim.faces then
local get = Types.Scene.reader(prim.faces)
if not get then
return nil
end
local at = 1
for f = 0, prim.faces.count - 1 do
local k = get(f, 0)
if at + k - 1 > #ix then
break
end
for j = 1, k - 2 do
tri(ix[at], ix[at + j], ix[at + j + 1])
end
at += k
end
else
return nil
end
return out
end
function Write.build(scene: Types.Scene, opts: any): (buffer?, Err.Err?)
local o = opts or {}
local nextId = 0
local function id(): number
nextId += 1
return nextId
end
local res: { string } = {} -- resource XML chunks, in definition order
local files: { { name: string, data: buffer, mime: string } } = {}
-- unit
local unitName: string, scale: number = "millimeter", 1
local mu: any = scene.meta and scene.meta.unit
if type(o.unit) == "string" and UNITS[o.unit] then
unitName = o.unit
if type(mu) == "number" and mu > 0 then
scale = mu / UNITS[o.unit]
end
elseif type(mu) == "number" and mu > 0 then
local found = false
for _, u in UNIT_ORDER do
if math.abs(UNITS[u] - mu) <= 1e-9 * mu then
unitName, found = u, true
break
end
end
if not found then
scale = mu / 1e-3
end
end
-- base materials: one group with every Scene material
local baseId: number? = nil
local nmat = #scene.materials
local defaultBase = nmat -- 0-based index of an extra white "default" base, added when needed
local needDefault = false
if nmat > 0 then
baseId = id()
end
-- textures used as base colour textures
local texRes: { [number]: number } = {}
local function textureId(ti: number): number?
if texRes[ti] ~= nil then
return if texRes[ti] > 0 then texRes[ti] else nil
end
local tex = scene.textures[ti]
local ext = tex and TEX_EXT[tex.mime or ""]
if not tex or type(tex.data) ~= "buffer" or not ext then
texRes[ti] = 0
return nil
end
local rid = id()
local name = fmt("3D/Textures/texture_%d.%s", ti, ext :: string)
table.insert(files, { name = name, data = tex.data :: buffer, mime = tex.mime :: string })
local s = tex.sampler
local function tile(w: string?): string
return if w == "clamp" then "clamp" elseif w == "mirror" then "mirror" else "wrap"
end
local filter = if s and (s.filter == "nearest" or s.filter == "linear") then s.filter else "auto"
table.insert(res, fmt('\t\t<m:texture2d id="%d" path="/%s" contenttype="%s" tilestyleu="%s" tilestylev="%s" filter="%s" />\n', rid, esc(name), tex.mime :: string, tile(s and s.wrapS), tile(s and s.wrapT), filter))
texRes[ti] = rid
return rid
end
-- objects
local objectOf: { [number]: number } = {}
local objChunks: { string } = {}
for mi, mesh in scene.meshes do
local verts: { string } = {}
local tris: { string } = {}
local base = 0
local objPid: number?, objP: number? = nil, nil
local anyNone = false
local triList: { { number } } = {} -- { v1, v2, v3, pid | -1, p1, p2, p3 }
for _, prim in mesh.primitives do
local corners = triangles(prim)
if not corners or #corners == 0 then
continue
end
local pos = prim.attributes.POSITION
local getP = Types.Scene.reader(pos)
if not getP then
continue
end
local n = pos.count
for v = 0, n - 1 do
table.insert(verts, fmt('\t\t\t\t\t<vertex x="%s" y="%s" z="%s" />\n', num(getP(v, 0)), num(if pos.components >= 2 then getP(v, 1) else 0), num(if pos.components >= 3 then getP(v, 2) else 0)))
end
-- properties: texture group, colour group, base material, none
local pid, kind = -1, "none"
local mat = prim.material and scene.materials[prim.material]
local uv = prim.attributes.TEXCOORD_0
local col = prim.attributes.COLOR_0
local tref = mat and mat.baseColorTexture
local tid = if tref and uv and (tref.texCoord or 0) == 0 then textureId(tref.texture) else nil
if tid and uv then
local get = Types.Scene.reader(uv)
if get then
pid, kind = id(), "tex"
local parts = { fmt('\t\t<m:texture2dgroup id="%d" texid="%d">\n', pid, tid) }
for v = 0, n - 1 do
table.insert(parts, fmt('\t\t\t<m:tex2coord u="%s" v="%s" />\n', num(get(v, 0)), num(1 - get(v, 1))))
end
table.insert(parts, "\t\t</m:texture2dgroup>\n")
table.insert(res, table.concat(parts))
end
end
if kind == "none" and col then
local get = Types.Scene.reader(col)
if get then
pid, kind = id(), "color"
local parts = { fmt('\t\t<m:colorgroup id="%d">\n', pid) }
local four = col.components >= 4
for v = 0, n - 1 do
table.insert(parts, fmt('\t\t\t<m:color color="%s" />\n', hex(get(v, 0), get(v, 1), get(v, 2), if four then get(v, 3) else 1)))
end
table.insert(parts, "\t\t</m:colorgroup>\n")
table.insert(res, table.concat(parts))
end
end
local pindex = -1
if kind == "none" and baseId and prim.material and scene.materials[prim.material] then
pid, kind, pindex = baseId :: number, "base", prim.material - 1
end
for i = 1, #corners, 3 do
local a, b, c = corners[i] + base, corners[i + 1] + base, corners[i + 2] + base
if kind == "tex" or kind == "color" then
table.insert(triList, { a, b, c, pid, corners[i], corners[i + 1], corners[i + 2] })
elseif kind == "base" then
table.insert(triList, { a, b, c, pid, pindex, pindex, pindex })
else
table.insert(triList, { a, b, c, -1, -1, -1, -1 })
anyNone = true
end
if objPid == nil and kind ~= "none" then
objPid, objP = pid, if kind == "base" then pindex else corners[i]
end
end
base += n
end
if #triList == 0 then
continue
end
if objPid and anyNone then
needDefault = true
if not baseId then
baseId = id()
end
end
for _, t in triList do
if t[4] < 0 and objPid then
t[4], t[5], t[6], t[7] = baseId :: number, defaultBase, defaultBase, defaultBase
end
if t[4] < 0 then
table.insert(tris, fmt('\t\t\t\t\t<triangle v1="%d" v2="%d" v3="%d" />\n', t[1], t[2], t[3]))
elseif t[5] == t[6] and t[6] == t[7] then
table.insert(tris, fmt('\t\t\t\t\t<triangle v1="%d" v2="%d" v3="%d" pid="%d" p1="%d" />\n', t[1], t[2], t[3], t[4], t[5]))
else
table.insert(tris, fmt('\t\t\t\t\t<triangle v1="%d" v2="%d" v3="%d" pid="%d" p1="%d" p2="%d" p3="%d" />\n', t[1], t[2], t[3], t[4], t[5], t[6], t[7]))
end
end
local oid = id()
objectOf[mi] = oid
local head = fmt('\t\t<object id="%d" type="model"', oid)
if mesh.name then
head ..= fmt(' name="%s"', esc(mesh.name))
end
if objPid then
head ..= fmt(' pid="%d" pindex="%d"', objPid, objP :: number)
end
table.insert(objChunks, table.concat({ head, ">\n\t\t\t<mesh>\n\t\t\t\t<vertices>\n", table.concat(verts), "\t\t\t\t</vertices>\n\t\t\t\t<triangles>\n", table.concat(tris), "\t\t\t\t</triangles>\n\t\t\t</mesh>\n\t\t</object>\n" }))
table.insert(res, objChunks[#objChunks])
end
-- the base material group goes first (its id was taken first)
if baseId then
local parts = { fmt('\t\t<basematerials id="%d">\n', baseId) }
for _, m in scene.materials do
local c = m.baseColor or { 1, 1, 1, 1 }
table.insert(parts, fmt('\t\t\t<base name="%s" displaycolor="%s" />\n', esc(m.name or "material"), hex(c[1] or 1, c[2] or 1, c[3] or 1, c[4] or 1)))
end
if needDefault then
table.insert(parts, '\t\t\t<base name="default" displaycolor="#FFFFFFFF" />\n')
end
table.insert(parts, "\t\t</basematerials>\n")
table.insert(res, 1, table.concat(parts))
end
-- build items: every node with a mesh, at its world matrix
local items: { string } = {}
local seen: { [number]: boolean } = {}
for _, pl in Types.Scene.flatten(scene) do
if seen[pl.node] then
continue
end
seen[pl.node] = true
local oid = objectOf[pl.mesh]
if not oid then
continue
end
local m = pl.matrix
local s = scale
local tr = { m[1] * s, m[2] * s, m[3] * s, m[5] * s, m[6] * s, m[7] * s, m[9] * s, m[10] * s, m[11] * s, m[13] * s, m[14] * s, m[15] * s }
local ident = s == 1
for i, v in { 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 } do
if tr[i] ~= v then
ident = false
end
end
if ident then
table.insert(items, fmt('\t\t<item objectid="%d" />\n', oid))
else
local ns = table.create(12, "")
for i = 1, 12 do
ns[i] = num(tr[i])
end
table.insert(items, fmt('\t\t<item objectid="%d" transform="%s" />\n', oid, table.concat(ns, " ")))
end
end
-- metadata
local meta: { string } = {}
local md = scene.meta and scene.meta.metadata
if type(md) == "table" then
local keys: { string } = {}
for k: any, v: any in md do
if type(k) == "string" and (type(v) == "string" or type(v) == "number") then
table.insert(keys, k)
end
end
table.sort(keys)
for _, k in keys do
table.insert(meta, fmt('\t<metadata name="%s">%s</metadata>\n', esc(k), Xml.escape(tostring(md[k]))))
end
end
local model = table.concat({
'<?xml version="1.0" encoding="UTF-8"?>\n',
'<model unit="' .. unitName .. '" xml:lang="en-US" xmlns="' .. NS_CORE .. '" xmlns:m="' .. NS_MAT .. '">\n',
table.concat(meta),
"\t<resources>\n",
table.concat(res),
"\t</resources>\n\t<build>\n",
table.concat(items),
"\t</build>\n</model>\n",
})
local types = { '<?xml version="1.0" encoding="UTF-8"?>\n<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\n',
'\t<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />\n',
'\t<Default Extension="model" ContentType="application/vnd.ms-package.3dmanufacturing-3dmodel+xml" />\n' }
local exts: { [string]: boolean } = {}
for _, f in files do
local e = string.match(f.name, "%.(%w+)$") :: string
if not exts[e] then
exts[e] = true
table.insert(types, fmt('\t<Default Extension="%s" ContentType="%s" />\n', e, f.mime))
end
end
table.insert(types, "</Types>\n")
local rels = '<?xml version="1.0" encoding="UTF-8"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n'
.. fmt('\t<Relationship Target="/3D/3dmodel.model" Id="rel0" Type="%s" />\n', REL_MODEL)
.. "</Relationships>\n"
local w = Zip.writer()
local level = o.level or 6
local method = if level == 0 then "store" else "deflate"
local ok, err = w:add("[Content_Types].xml", table.concat(types), { level = level, method = method })
if ok then
ok, err = w:add("_rels/.rels", rels, { level = level, method = method })
end
if ok then
ok, err = w:add("3D/3dmodel.model", model, { level = level, method = method })
end
if ok and #files > 0 then
local mr = { '<?xml version="1.0" encoding="UTF-8"?>\n<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\n' }
for i, f in files do
table.insert(mr, fmt('\t<Relationship Target="/%s" Id="rel%d" Type="%s" />\n', esc(f.name), i, REL_TEXTURE))
end
table.insert(mr, "</Relationships>\n")
ok, err = w:add("3D/_rels/3dmodel.model.rels", table.concat(mr), { level = level, method = method })
for _, f in files do
if ok then
ok, err = w:add(f.name, f.data, { method = "store" })
end
end
end
if not ok then
return nil, err or Err.new(Err.ARG, "zip writer failed")
end
return w:finish()
end
return Write
+95
View File
@@ -0,0 +1,95 @@
--!strict
-- model/3mf: 3D Manufacturing Format (3MF Consortium core specification 1.3, materials and properties extension 1.2,
-- production extension 1.1 part references). New code. An OPC package (containers/Zip) holding XML model parts
-- (codecs/Xml).
-- Reads: the root model part (_rels/.rels), objects (mesh vertices / triangles; components with transforms, also from
-- other model parts through p:path), build items -> root nodes with their transforms (3MF's row-vector 4x3 matrices
-- become column-major node.matrix), object names / types / part numbers (node / mesh extras["3mf"]), metadata
-- (meta.metadata), the unit (meta.unit in metres; meta.up = "z"), basematerials (-> materials, sRGB display colours
-- made linear), colorgroup (-> COLOR_0, linear RGBA), texture2d + texture2dgroup (-> TEXCOORD_0 with v flipped to
-- glTF's top-left origin, a material with baseColorTexture, the texture kept encoded from its package part: decode it
-- with F.model.loadTextures), compositematerials (one blended colour per composite), multiproperties (their first
-- layer), per-triangle pid / p1 / p2 / p3 and per-object pid / pindex defaults. One primitive per property; vertices
-- are split where a vertex's corners carry different colours / texture coordinates.
-- Writes: one object per mesh (all triangle-like primitives; points / lines skipped), one build item per node with a
-- mesh at its world matrix (the hierarchy is flattened), materials as basematerials, COLOR_0 as colour groups,
-- PNG / JPEG base colour textures as texture2d + texture2dgroup, metadata, the unit (opts.unit or from meta.unit).
-- Not supported: beam lattice, slices, displacement, volumetric and secure content extensions (their elements are
-- ignored; meta.source.requiredExtensions lists what the file declared), thumbnails, normals (3MF has none).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Zip = require("@formats/containers/Zip")
local Read = require("@formats/model/3mf/Read")
local Write = require("@formats/model/3mf/Write")
-- ------------------------------------------------------------------------------------------------ contract
local ThreeMf = {
name = "3mf",
category = "model",
extensions = { "3mf" },
mime = { "model/3mf" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Xml", "containers/Zip" },
caps = { decode = true, encode = true, materials = true, vertexColors = true, textures = true, units = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
maxVertices: number?, -- refuse more vertices + triangle corners in total (default 2^25)
maxNodes: number?, -- refuse more object instances (default 2^20)
}
export type EncodeOptions = {
unit: string?, -- "micron" | "millimeter" | "centimeter" | "inch" | "foot" | "meter" (default: from meta.unit, else
-- millimeter); positions are scaled through the build transforms when meta.unit differs
level: number?, -- deflate level for the XML parts (default 6; 0 stores them)
}
-- ------------------------------------------------------------------------------------------------ sniff
function ThreeMf.sniff(r: Bytes.Reader): number
if r:peek(4) ~= "PK\3\4" then
return 0
end
-- the central directory sits at the end: look for the model part's name there, then at the start
local n = r:size()
local tail = buffer.readstring(r.buf, r.base + math.max(0, n - 65536), math.min(n, 65536))
if string.find(tail, "3D/[^/]*%.model") or string.find(tail, "3dmodel.model", 1, true) then
return 0.95
end
local head = r:peek(256)
if string.find(head, "3D/", 1, true) then
return 0.7
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
function ThreeMf.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local zip, zerr = Zip.open(r)
if not zip then
return nil, zerr
end
local ok, scene, err = pcall(Read.scene, zip, opts or {})
if not ok then
return nil, Err.new(Err.CORRUPT, "bad package (" .. tostring(scene) .. ")")
end
return scene, err
end
-- ------------------------------------------------------------------------------------------------ encode
function ThreeMf.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.materials) ~= "table" or type(scene.textures) ~= "table" then
return nil, Err.new(Err.ARG, "needs a Scene")
end
if opts and opts.unit ~= nil and not Read.UNITS[opts.unit] then
return nil, Err.new(Err.ARG, "unknown unit " .. tostring(opts.unit))
end
local ok, out, err = pcall(Write.build, scene, opts)
if not ok then
return nil, Err.new(Err.ARG, "bad scene (" .. tostring(out) .. ")")
end
return out, err
end
return ThreeMf
+188
View File
@@ -0,0 +1,188 @@
--!strict
-- model/dae/Math: the matrix helpers the Collada reader and writer share. Matrices are flat arrays of 16 in glTF's
-- column-major order (Collada writes row-major: fromRows / toRows convert). Quaternions are { x, y, z, w }.
local DaeMath = {}
local sqrt, abs, rad, sin, cos = math.sqrt, math.abs, math.rad, math.sin, math.cos
function DaeMath.identity(): { number }
return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
end
-- fromRows(v, at?) -> column-major from 16 row-major values starting at v[at] (default 1)
function DaeMath.fromRows(v: { number }, at: number?): { number }
local o = (at or 1) - 1
local m = table.create(16, 0)
for r = 0, 3 do
for c = 0, 3 do
m[c * 4 + r + 1] = v[o + r * 4 + c + 1] or (if r == c then 1 else 0)
end
end
return m
end
function DaeMath.toRows(m: { number }): { number }
local v = table.create(16, 0)
for r = 0, 3 do
for c = 0, 3 do
v[r * 4 + c + 1] = m[c * 4 + r + 1]
end
end
return v
end
function DaeMath.mul(a: { number }, b: { number }): { number }
local m = table.create(16, 0)
for col = 0, 3 do
for row = 0, 3 do
local s = 0
for k = 0, 3 do
s += a[k * 4 + row + 1] * b[col * 4 + k + 1]
end
m[col * 4 + row + 1] = s
end
end
return m
end
function DaeMath.translation(x: number, y: number, z: number): { number }
return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 }
end
function DaeMath.scaling(x: number, y: number, z: number): { number }
return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 }
end
-- axisAngle(x, y, z, degrees) -> quaternion
function DaeMath.axisAngle(x: number, y: number, z: number, degrees: number): { number }
local l = sqrt(x * x + y * y + z * z)
if l < 1e-12 then
return { 0, 0, 0, 1 }
end
local h = rad(degrees) / 2
local s = sin(h) / l
return { x * s, y * s, z * s, cos(h) }
end
function DaeMath.quatMatrix(q: { number }): { number }
local x, y, z, w = q[1], q[2], q[3], q[4]
local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z
return {
1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0,
2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0,
2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0,
0, 0, 0, 1,
}
end
local function cross(a: { number }, b: { number }): { number }
return { a[2] * b[3] - a[3] * b[2], a[3] * b[1] - a[1] * b[3], a[1] * b[2] - a[2] * b[1] }
end
local function norm(a: { number }): { number }
local l = sqrt(a[1] * a[1] + a[2] * a[2] + a[3] * a[3])
if l < 1e-20 then
return { 0, 0, 0 }
end
return { a[1] / l, a[2] / l, a[3] / l }
end
-- lookat(eye, interest, up) -> the placement of an object at eye whose -Z looks at interest
function DaeMath.lookat(v: { number }): { number }
local ex, ey, ez = v[1] or 0, v[2] or 0, v[3] or 0
local z = norm({ ex - (v[4] or 0), ey - (v[5] or 0), ez - (v[6] or 0) })
local x = norm(cross({ v[7] or 0, v[8] or 1, v[9] or 0 }, z))
local y = cross(z, x)
return { x[1], x[2], x[3], 0, y[1], y[2], y[3], 0, z[1], z[2], z[3], 0, ex, ey, ez, 1 }
end
-- skew(angle, rotation axis, translation axis) (RenderMan's skew)
function DaeMath.skew(v: { number }): { number }
local a = rad(v[1] or 0)
local r = norm({ v[2] or 0, v[3] or 0, v[4] or 0 })
local t = norm({ v[5] or 0, v[6] or 0, v[7] or 0 })
local s = math.tan(a)
local m = DaeMath.identity()
-- M = I + s * t * r^T (column-major: m[col*4 + row])
for row = 0, 2 do
for col = 0, 2 do
m[col * 4 + row + 1] += s * t[row + 1] * r[col + 1]
end
end
return m
end
-- decompose(m) -> translation, rotation, scale | nil (shear, a projective row, or a singular matrix)
function DaeMath.decompose(m: { number }): ({ number }?, { number }?, { number }?)
if abs(m[4]) > 1e-6 or abs(m[8]) > 1e-6 or abs(m[12]) > 1e-6 or abs(m[16] - 1) > 1e-6 then
return nil, nil, nil
end
local c1 = { m[1], m[2], m[3] }
local c2 = { m[5], m[6], m[7] }
local c3 = { m[9], m[10], m[11] }
local sx = sqrt(c1[1] * c1[1] + c1[2] * c1[2] + c1[3] * c1[3])
local sy = sqrt(c2[1] * c2[1] + c2[2] * c2[2] + c2[3] * c2[3])
local sz = sqrt(c3[1] * c3[1] + c3[2] * c3[2] + c3[3] * c3[3])
if sx < 1e-12 or sy < 1e-12 or sz < 1e-12 then
return nil, nil, nil
end
local x, y, z = { c1[1] / sx, c1[2] / sx, c1[3] / sx }, { c2[1] / sy, c2[2] / sy, c2[3] / sy }, { c3[1] / sz, c3[2] / sz, c3[3] / sz }
local dxy = x[1] * y[1] + x[2] * y[2] + x[3] * y[3]
local dxz = x[1] * z[1] + x[2] * z[2] + x[3] * z[3]
local dyz = y[1] * z[1] + y[2] * z[2] + y[3] * z[3]
if abs(dxy) > 1e-4 or abs(dxz) > 1e-4 or abs(dyz) > 1e-4 then
return nil, nil, nil
end
local cr = cross(x, y)
if cr[1] * z[1] + cr[2] * z[2] + cr[3] * z[3] < 0 then
sx = -sx
x = { -x[1], -x[2], -x[3] }
end
-- rotation matrix (columns x, y, z) -> quaternion
local m00, m01, m02 = x[1], y[1], z[1]
local m10, m11, m12 = x[2], y[2], z[2]
local m20, m21, m22 = x[3], y[3], z[3]
local tr = m00 + m11 + m22
local qx, qy, qz, qw
if tr > 0 then
local s = sqrt(tr + 1) * 2
qw, qx, qy, qz = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s
elseif m00 > m11 and m00 > m22 then
local s = sqrt(1 + m00 - m11 - m22) * 2
qw, qx, qy, qz = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s
elseif m11 > m22 then
local s = sqrt(1 + m11 - m00 - m22) * 2
qw, qx, qy, qz = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s
else
local s = sqrt(1 + m22 - m00 - m11) * 2
qw, qx, qy, qz = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4
end
local l = sqrt(qx * qx + qy * qy + qz * qz + qw * qw)
return { m[13], m[14], m[15] }, { qx / l, qy / l, qz / l, qw / l }, { sx, sy, sz }
end
-- transformPoint / transformDir (column-major m)
function DaeMath.point(m: { number }, x: number, y: number, z: number): (number, number, number)
return m[1] * x + m[5] * y + m[9] * z + m[13], m[2] * x + m[6] * y + m[10] * z + m[14], m[3] * x + m[7] * y + m[11] * z + m[15]
end
-- the inverse transpose of the upper 3x3 (for normals), as a column-major 4x4
function DaeMath.normalMatrix(m: { number }): { number }
local a, b, c = m[1], m[5], m[9]
local d, e, f = m[2], m[6], m[10]
local g, h, i = m[3], m[7], m[11]
local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g
local det = a * A + b * B + c * C
if abs(det) < 1e-30 then
return DaeMath.identity()
end
local k = 1 / det
-- inverse = adj / det; its transpose has rows = cofactors
return {
A * k, B * k, C * k, 0,
-(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0,
(b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0,
0, 0, 0, 1,
}
end
return DaeMath
File diff suppressed because it is too large. Load diff
+376
View File
@@ -0,0 +1,376 @@
--!strict
-- model/dae/Write: Scene -> Collada 1.4.1 text. One <geometry> per mesh primitive (triangles, lines or polylist; strips
-- and fans unrolled into triangles, points skipped) with POSITION / NORMAL / TEXCOORD_n (V flipped back) / COLOR_n
-- sources sharing one index; common-profile phong (or lambert / constant) effects from the PBR material and its
-- extras.phong; images as files (opts.files), their uri, or data: URIs; the node tree as row-major <matrix>; cameras;
-- lights. Not written: skins, morph targets, animations.
local Types = require("@formats/Types")
local Xml = require("@formats/codecs/Xml")
local Base64 = require("@formats/codecs/Base64")
local M = require("@formats/model/dae/Math")
local Write = {}
local Scene = Types.Scene
local format, concat = string.format, table.concat
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/tga"] = "tga", ["image/bmp"] = "bmp", ["image/gif"] = "gif" }
local function f(v: number): string
if v ~= v or v == math.huge or v == -math.huge then
return "0"
end
if v == math.floor(v) and math.abs(v) < 1e15 then
return format("%d", v)
end
return format("%.9g", v)
end
local function list(v: { number }): string
local out = table.create(#v)
for i, x in v do
out[i] = f(x)
end
return concat(out, " ")
end
local function esc(s: string): string
return Xml.escapeAttr(s)
end
local function nameAttr(s: string?): string
return if s then ' name="' .. esc(s) .. '"' else ""
end
-- triangle / line corner lists of a primitive (0-based vertex indices) and the element kind
local function corners(prim: Types.Primitive): ({ number }?, string?, { number }?)
local n = prim.attributes.POSITION.count
local idx: { number } = {}
if prim.indices then
local get = Scene.reader(prim.indices)
if not get then
return nil, nil, nil
end
for i = 0, prim.indices.count - 1 do
idx[i + 1] = get(i, 0)
end
else
for i = 0, n - 1 do
idx[i + 1] = i
end
end
for _, i in idx do
if i < 0 or i >= n then
return nil, nil, nil
end
end
local mode = prim.mode or "triangles"
if mode == "triangles" then
local m = #idx - #idx % 3
return table.move(idx, 1, m, 1, {}), "triangles", nil
elseif mode == "triangle_strip" or mode == "triangle_fan" then
local out = {}
for k = 1, #idx - 2 do
if mode == "triangle_fan" then
table.insert(out, idx[1])
table.insert(out, idx[k + 1])
table.insert(out, idx[k + 2])
elseif k % 2 == 1 then
table.insert(out, idx[k])
table.insert(out, idx[k + 1])
table.insert(out, idx[k + 2])
else
table.insert(out, idx[k + 1])
table.insert(out, idx[k])
table.insert(out, idx[k + 2])
end
end
return out, "triangles", nil
elseif mode == "lines" then
local m = #idx - #idx % 2
return table.move(idx, 1, m, 1, {}), "lines", nil
elseif mode == "line_strip" or mode == "line_loop" then
local out = {}
for k = 1, #idx - 1 do
table.insert(out, idx[k])
table.insert(out, idx[k + 1])
end
if mode == "line_loop" and #idx > 2 then
table.insert(out, idx[#idx])
table.insert(out, idx[1])
end
return out, "lines", nil
elseif mode == "polygons" and prim.faces then
local get = Scene.reader(prim.faces)
if not get then
return nil, nil, nil
end
local sizes = {}
local total = 0
for i = 0, prim.faces.count - 1 do
sizes[i + 1] = get(i, 0)
total += sizes[i + 1]
end
if total ~= #idx then
return nil, nil, nil
end
return idx, "polylist", sizes
end
return nil, nil, nil
end
local function source(out: { string }, id: string, acc: Types.Accessor, comps: number, params: { string }, flipV: boolean)
local get = Scene.reader(acc)
if not get then
return
end
local vals = table.create(acc.count * comps)
local n = 0
for i = 0, acc.count - 1 do
for c = 0, comps - 1 do
n += 1
local v = if c < acc.components then get(i, c) else (if c == 3 then 1 else 0)
if flipV and c == 1 then
v = 1 - v
end
vals[n] = f(v)
end
end
table.insert(out, format('<source id="%s"><float_array id="%s-array" count="%d">%s</float_array>', id, id, n, concat(vals, " ")))
local ps = {}
for c = 1, comps do
ps[c] = format('<param name="%s" type="float"/>', params[c] or "V")
end
table.insert(out, format('<technique_common><accessor source="#%s-array" count="%d" stride="%d">%s</accessor></technique_common></source>\n', id, acc.count, comps, concat(ps)))
end
local function colorEl(tag: string, c: { number }?, tex: string?, uv: number?): string
if tex then
return format('<%s><texture texture="%s" texcoord="UVSET%d"/></%s>', tag, tex, uv or 0, tag)
end
local v = c or { 0, 0, 0, 1 }
return format("<%s><color>%s %s %s %s</color></%s>", tag, f(v[1] or 0), f(v[2] or 0), f(v[3] or 0), f(v[4] or 1), tag)
end
function Write.build(scene: Types.Scene, opts: any?): string?
local files = opts and type(opts.files) == "table" and opts.files or nil
local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model"
local flipV = not (opts and opts.flipV == false)
local out: { string } = {}
local function w(s: string)
table.insert(out, s)
end
w('<?xml version="1.0" encoding="utf-8"?>\n<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">\n')
local meta = scene.meta or {}
local up = if meta.up == "z" then "Z_UP" elseif meta.up == "x" then "X_UP" else "Y_UP"
w(format('<asset><contributor><authoring_tool>formats-luau</authoring_tool></contributor><created>1970-01-01T00:00:00Z</created><modified>1970-01-01T00:00:00Z</modified><unit meter="%s" name="unit"/><up_axis>%s</up_axis></asset>\n', f(meta.unit or 1), up))
-- images
local imageId: { [number]: string } = {}
if #scene.textures > 0 then
w("<library_images>\n")
for i, tex in scene.textures do
local uri: string? = nil
if tex.data then
if files then
uri = format("%s_%d.%s", base, i, EXT[tex.mime or ""] or "png")
files[uri :: string] = tex.data
else
uri = Base64.dataUri(tex.data, tex.mime or "image/png")
end
elseif tex.uri then
uri = tex.uri
end
if uri then
local id = "image" .. i
imageId[i] = id
w(format('<image id="%s"%s><init_from>%s</init_from></image>\n', id, nameAttr(tex.name), Xml.escape(uri :: string)))
end
end
w("</library_images>\n")
end
-- effects + materials
if #scene.materials > 0 then
w("<library_effects>\n")
for i, mat in scene.materials do
local ph: any = mat.extras and mat.extras.phong or {}
local params = {}
local function texParam(ref: Types.TextureRef?): (string?, number?)
if not ref or not imageId[ref.texture] then
return nil, nil
end
local sid = "tex" .. ref.texture
if not params[sid] then
params[sid] = true
table.insert(params, format('<newparam sid="%s-surface"><surface type="2D"><init_from>%s</init_from></surface></newparam><newparam sid="%s"><sampler2D><source>%s-surface</source></sampler2D></newparam>', sid, imageId[ref.texture], sid, sid))
end
return sid, ref.texCoord
end
local dtex, duv = texParam(mat.baseColorTexture)
local etex, euv = texParam(mat.emissiveTexture)
local ntex, nuv = texParam(mat.normalTexture)
local unlit = mat.extensions and mat.extensions.KHR_materials_unlit ~= nil
local model = if unlit then "constant" elseif ph.model == "lambert" then "lambert" else "phong"
local body = {}
local bc = mat.baseColor
if unlit then
table.insert(body, colorEl("emission", { bc[1], bc[2], bc[3], 1 }, nil, nil))
else
table.insert(body, colorEl("emission", if type(ph.emission) == "table" then ph.emission else { mat.emissive[1], mat.emissive[2], mat.emissive[3], 1 }, etex, euv))
table.insert(body, colorEl("ambient", if type(ph.ambient) == "table" then ph.ambient else { 0, 0, 0, 1 }, nil, nil))
table.insert(body, colorEl("diffuse", { bc[1], bc[2], bc[3], 1 }, dtex, duv))
if model == "phong" then
table.insert(body, colorEl("specular", if type(ph.specular) == "table" then ph.specular else { 0, 0, 0, 1 }, nil, nil))
local sh = if type(ph.shininess) == "number" then ph.shininess else math.max(2 / math.max((mat.roughness or 1) ^ 2, 1e-4) - 2, 0)
table.insert(body, format("<shininess><float>%s</float></shininess>", f(sh)))
end
end
if (bc[4] or 1) < 1 then
table.insert(body, '<transparent opaque="A_ONE"><color>1 1 1 1</color></transparent>')
table.insert(body, format("<transparency><float>%s</float></transparency>", f(bc[4])))
end
local extra = ""
if ntex or mat.doubleSided then
extra = "<extra><technique profile=\"FCOLLADA\">" .. (if ntex then format('<bump><texture texture="%s" texcoord="UVSET%d"/></bump>', ntex, nuv or 0) else "") .. (if mat.doubleSided then "<double_sided>1</double_sided>" else "") .. "</technique></extra>"
end
w(format('<effect id="effect%d"><profile_COMMON>%s<technique sid="common"><%s>%s</%s>%s</technique></profile_COMMON></effect>\n', i, concat(params), model, concat(body), model, extra))
end
w("</library_effects>\n<library_materials>\n")
for i, mat in scene.materials do
w(format('<material id="material%d"%s><instance_effect url="#effect%d"/></material>\n', i, nameAttr(mat.name), i))
end
w("</library_materials>\n")
end
-- geometries: one per primitive
local geoms: { [number]: { { id: string, material: number?, sets: number } } } = {}
w("<library_geometries>\n")
for mi, mesh in scene.meshes do
geoms[mi] = {}
for pi, prim in mesh.primitives do
local pos = prim.attributes and prim.attributes.POSITION
if not pos then
continue
end
local idx, kind, sizes = corners(prim)
if not idx or not kind or #idx == 0 then
continue
end
local id = format("mesh%d-%d", mi, pi)
w(format('<geometry id="%s"%s><mesh>\n', id, nameAttr(mesh.name)))
source(out, id .. "-positions", pos, 3, { "X", "Y", "Z" }, false)
local ins = { format('<input semantic="VERTEX" source="#%s-vertices" offset="0"/>', id) }
if prim.attributes.NORMAL then
source(out, id .. "-normals", prim.attributes.NORMAL, 3, { "X", "Y", "Z" }, false)
table.insert(ins, format('<input semantic="NORMAL" source="#%s-normals" offset="0"/>', id))
end
local sets = 0
for k = 0, 7 do
local a = prim.attributes["TEXCOORD_" .. k]
if not a then
break
end
source(out, format("%s-uv%d", id, k), a, 2, { "S", "T" }, flipV)
table.insert(ins, format('<input semantic="TEXCOORD" source="#%s-uv%d" offset="0" set="%d"/>', id, k, k))
sets += 1
end
for k = 0, 7 do
local a = prim.attributes["COLOR_" .. k]
if not a then
break
end
local c = if a.components >= 4 then 4 else 3
source(out, format("%s-color%d", id, k), a, c, { "R", "G", "B", "A" }, false)
table.insert(ins, format('<input semantic="COLOR" source="#%s-color%d" offset="0" set="%d"/>', id, k, k))
end
w(format('<vertices id="%s-vertices"><input semantic="POSITION" source="#%s-positions"/></vertices>\n', id, id))
local matAttr = if prim.material and scene.materials[prim.material] then format(' material="m%d"', prim.material) else ""
local count = if kind == "triangles" then #idx // 3 elseif kind == "lines" then #idx // 2 else #(sizes :: { number })
w(format('<%s count="%d"%s>%s', kind, count, matAttr, concat(ins)))
if sizes then
w("<vcount>" .. list(sizes) .. "</vcount>")
end
w("<p>" .. list(idx) .. "</p></" .. kind .. ">\n</mesh></geometry>\n")
table.insert(geoms[mi], { id = id, material = if matAttr ~= "" then prim.material else nil, sets = sets })
end
end
w("</library_geometries>\n")
-- cameras / lights
if #scene.cameras > 0 then
w("<library_cameras>\n")
for i, cam in scene.cameras do
local body: string
if cam.type == "orthographic" then
body = format("<orthographic><xmag>%s</xmag><ymag>%s</ymag><znear>%s</znear><zfar>%s</zfar></orthographic>", f(cam.xmag or 1), f(cam.ymag or 1), f(cam.znear or 0.1), f(cam.zfar or 1000))
else
body = format("<perspective><yfov>%s</yfov>%s<znear>%s</znear><zfar>%s</zfar></perspective>", f(math.deg(cam.yfov or 0.8)), if cam.aspect then format("<aspect_ratio>%s</aspect_ratio>", f(cam.aspect)) else "", f(cam.znear or 0.1), f(cam.zfar or 1000))
end
w(format('<camera id="camera%d"%s><optics><technique_common>%s</technique_common></optics></camera>\n', i, nameAttr(cam.name), body))
end
w("</library_cameras>\n")
end
if #scene.lights > 0 then
w("<library_lights>\n")
for i, l in scene.lights do
local c = l.color or { 1, 1, 1 }
local k = l.intensity or 1
local col = format("<color>%s %s %s</color>", f(c[1] * k), f(c[2] * k), f(c[3] * k))
local body = if l.type == "spot" then format("<spot>%s<constant_attenuation>1</constant_attenuation><linear_attenuation>0</linear_attenuation><quadratic_attenuation>0</quadratic_attenuation><falloff_angle>%s</falloff_angle><falloff_exponent>0</falloff_exponent></spot>", col, f(math.deg(l.outerCone or math.pi / 4) * 2))
elseif l.type == "point" then format("<point>%s<constant_attenuation>1</constant_attenuation><linear_attenuation>0</linear_attenuation><quadratic_attenuation>0</quadratic_attenuation></point>", col)
else format("<directional>%s</directional>", col)
w(format('<light id="light%d"%s><technique_common>%s</technique_common></light>\n', i, nameAttr(l.name), body))
end
w("</library_lights>\n")
end
-- the node tree
w('<library_visual_scenes><visual_scene id="scene" name="scene">\n')
local seen: { [number]: boolean } = {}
local function node(i: number, depth: number)
local n = scene.nodes[i]
if not n or seen[i] or depth > 512 then
return
end
seen[i] = true
w(format('<node id="node%d"%s type="NODE"><matrix sid="transform">%s</matrix>', i, nameAttr(n.name), list(M.toRows(Scene.nodeMatrix(n)))))
if n.mesh and geoms[n.mesh] then
for _, g in geoms[n.mesh] do
if g.material then
local binds = {}
for k = 0, g.sets - 1 do
table.insert(binds, format('<bind_vertex_input semantic="UVSET%d" input_semantic="TEXCOORD" input_set="%d"/>', k, k))
end
w(format('<instance_geometry url="#%s"><bind_material><technique_common><instance_material symbol="m%d" target="#material%d">%s</instance_material></technique_common></bind_material></instance_geometry>', g.id, g.material, g.material, concat(binds)))
else
w(format('<instance_geometry url="#%s"/>', g.id))
end
end
end
if n.camera and scene.cameras[n.camera] then
w(format('<instance_camera url="#camera%d"/>', n.camera))
end
if n.light and scene.lights[n.light] then
w(format('<instance_light url="#light%d"/>', n.light))
end
w("\n")
for _, c in n.children or {} do
node(c, depth + 1)
end
w("</node>\n")
end
local roots = scene.roots
if not roots or #roots == 0 then
local isChild = {}
for _, n in scene.nodes do
for _, c in n.children or {} do
isChild[c] = true
end
end
roots = {}
for i in scene.nodes do
if not isChild[i] then
table.insert(roots, i)
end
end
end
for _, r in roots do
node(r, 0)
end
w('</visual_scene></library_visual_scenes>\n<scene><instance_visual_scene url="#scene"/></scene>\n</COLLADA>\n')
return concat(out)
end
return Write
+206
View File
@@ -0,0 +1,206 @@
--!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/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/Xml", "codecs/Base64", "containers/Zip" },
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, "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
+274
View File
@@ -0,0 +1,274 @@
--!strict
-- model/fbx/Ascii: the ASCII FBX node tree reader and writer (7.x: "Name: value, value, ... { children }", ';'
-- comments, "*N { a: ... }" arrays, &quot; in strings). Produces the same Node / Array values as model/fbx/Binary
-- (arrays as f64 buffers; integers longer than 15 digits stay strings so ids are exact). Never throws.
local Base64 = require("@formats/core/Base64")
local Ascii = {}
type Node = { name: string, props: { any }, children: { Node } }
local sbyte, sfind, ssub = string.byte, string.find, string.sub
local MAX_DEPTH = 128
local function isNameStart(c: number): boolean
return (c >= 65 and c <= 90) or (c >= 97 and c <= 122) or c == 95
end
-- parse(text) -> root node (children = the top-level nodes), version | nil, message, offset
function Ascii.parse(text: string, opts: { maxBytes: number? }?): (Node?, any, number?)
local maxBytes = opts and opts.maxBytes or 2 ^ 30
local n = #text
local i = 1
local total = 0
local function skip()
while i <= n do
local c = sbyte(text, i)
if c == 59 then -- ; comment
local e = sfind(text, "\n", i, true)
i = if e then e + 1 else n + 1
elseif c == 32 or c == 9 or c == 10 or c == 13 then
i += 1
else
return
end
end
end
-- at i: a name followed by ':'? -> name, the index after ':'
local function nameAt(): (string?, number)
local c = sbyte(text, i)
if not c or not isNameStart(c) then
return nil, i
end
local s, e = sfind(text, "^[%w_|%-]+", i)
if not s then
return nil, i
end
local j = (e :: number) + 1
while j <= n do
local d = sbyte(text, j)
if d == 32 or d == 9 then
j += 1
else
break
end
end
if sbyte(text, j) == 58 then
return ssub(text, i, e :: number), j + 1
end
return nil, i
end
-- the values of one node (after the ':'), up to a new name, '{' or '}'
local function values(): ({ any }?, string?)
local props = {}
while true do
skip()
if i > n then
return props
end
local c = sbyte(text, i)
if c == 44 then -- ,
i += 1
elseif c == 123 or c == 125 then
return props
elseif c == 34 then -- "
local e = sfind(text, "\"", i + 1, true)
if not e then
return nil, "unterminated string"
end
local s = ssub(text, i + 1, e - 1)
if sfind(s, "&", 1, true) then
s = string.gsub(s, "&quot;", "\"")
end
table.insert(props, s)
i = e + 1
elseif c == 42 then -- *N
local s, e = sfind(text, "^%*%d+", i)
if not s then
return nil, "bad array length"
end
table.insert(props, { star = tonumber(ssub(text, i + 1, e :: number)) })
i = (e :: number) + 1
elseif (c >= 48 and c <= 57) or c == 45 or c == 43 or c == 46 then
local s, e = sfind(text, "^[-+%deE.]+", i)
local tok = ssub(text, i, e :: number)
local v = tonumber(tok)
if v == nil then
-- "1.#INF", "-1.#IND", "nan": special floats
local s2, e2 = sfind(text, "^[-+%w.#]+", i)
tok = ssub(text, i, e2 :: number)
local low = string.lower(tok)
if sfind(low, "inf", 1, true) then
v = if sbyte(tok, 1) == 45 then -math.huge else math.huge
else
v = 0 / 0
end
e = e2
local _ = s2
elseif #tok > 15 and not sfind(tok, "[.eE]") then
v = (if sbyte(tok, 1) == 45 then "L-" else "L") .. string.gsub(tok, "^[-+]", "") :: any
end
local _ = s
table.insert(props, v)
i = (e :: number) + 1
else
local nm = nameAt()
if nm then
return props
end
local s, e = sfind(text, "^[%w_]+", i)
if not s then
return nil, string.format("unexpected character %q", ssub(text, i, i))
end
table.insert(props, ssub(text, i, e :: number))
i = (e :: number) + 1
end
end
end
local function nodes(depth: number, into: { Node }): string?
while true do
skip()
if i > n then
return if depth > 0 then "unterminated {" else nil
end
if sbyte(text, i) == 125 then
if depth == 0 then
return "unbalanced }"
end
i += 1
return nil
end
local name, j = nameAt()
if not name then
return string.format("expected a node name at %q", ssub(text, i, i + 10))
end
i = j
local props, err = values()
if not props then
return err
end
local node: Node = { name = name, props = props, children = {} }
skip()
if sbyte(text, i) == 123 then
if depth >= MAX_DEPTH then
return "nodes nested too deep"
end
i += 1
local e = nodes(depth + 1, node.children)
if e then
return e
end
end
-- "*N { a: v, v, ... }" -> an Array
local p1 = props[1]
if #props == 1 and type(p1) == "table" and p1.star then
local a = node.children[1]
local count = if a and a.name == "a" then #a.props else 0
total += count * 8
if total > maxBytes then
return "limit:arrays over " .. maxBytes .. " bytes"
end
local data = buffer.create(count * 8)
for k = 1, count do
local v = (a :: Node).props[k]
buffer.writef64(data, (k - 1) * 8, if type(v) == "number" then v else (tonumber(v) or 0))
end
node.props = { { array = true, type = "d", count = count, data = data } }
node.children = {}
end
table.insert(into, node)
end
end
local root: Node = { name = "", props = {}, children = {} }
local err = nodes(0, root.children)
if err then
return nil, err, i - 1
end
local version = nil
for _, c in root.children do
if c.name == "FBXHeaderExtension" then
for _, d in c.children do
if d.name == "FBXVersion" then
version = d.props[1]
end
end
end
end
return root, version, nil
end
-- ------------------------------------------------------------------------------------------------ writer
local function fmt(v: number): string
if v == math.floor(v) and math.abs(v) < 1e15 then
return string.format("%d", v)
end
if v ~= v then
return "0"
end
return string.format("%.17g", v)
end
-- write(root) -> string: the ASCII form of a tree (the same node shapes Binary.write takes)
function Ascii.write(root: any, version: number?): string
local out = { string.format("; FBX %d.%d.0 project file\n; Created by formats-luau\n\n", (version or 7400) // 1000, (version or 7400) % 1000 // 100) }
local function node(nd: any, indent: string)
local parts = {}
local arr = nil
for _, v in nd.props do
local tv = type(v)
if tv == "number" then
table.insert(parts, fmt(v))
elseif tv == "boolean" then
table.insert(parts, if v then "T" else "F")
elseif tv == "string" then
if string.sub(v, 1, 1) == "L" and string.find(v, "^L%-?%d+$") then
table.insert(parts, string.sub(v, 2))
else
local nm, cls = string.match(v, "^(.-)%z\1(.*)$")
local sv = if nm then cls .. "::" .. nm else v
table.insert(parts, "\"" .. string.gsub(sv, "\"", "&quot;") .. "\"")
end
elseif tv == "table" and v.array then
arr = v
elseif tv == "buffer" then
-- raw bytes (Video Content): base64, split into lines as the FBX SDK writes them
local b64 = Base64.encode(v)
local chunks = {}
for k = 1, #b64, 2048 do
table.insert(chunks, "\"" .. string.sub(b64, k, k + 2047) .. "\"")
end
table.insert(parts, if #chunks > 0 then table.concat(chunks, ",\n") else "\"\"")
end
end
if arr then
local vals = table.create(arr.count)
for k = 0, arr.count - 1 do
vals[k + 1] = fmt(buffer.readf64(arr.data, k * 8))
end
table.insert(out, string.format("%s%s: *%d {\n%s\ta: %s\n%s}\n", indent, nd.name, arr.count, indent, table.concat(vals, ","), indent))
return
end
table.insert(out, indent .. nd.name .. ": " .. table.concat(parts, ", "))
local ch = nd.children
if ch and #ch > 0 then
table.insert(out, " {\n")
for _, c in ch do
node(c, indent .. "\t")
end
table.insert(out, indent .. "}\n")
else
table.insert(out, "\n")
end
end
for _, c in root.children do
node(c, "")
end
return table.concat(out)
end
return Ascii
+461
View File
@@ -0,0 +1,461 @@
--!strict
--!native
-- model/fbx/Binary: the binary FBX node tree reader and writer (versions 7.x: 32-bit node records before 7500, 64-bit
-- from 7500). From the format as documented by Blender's io_scene_fbx (encode_bin.py / parse_fbx.py) and assimp's
-- FBXBinaryTokenizer. Arrays (f, d, l, i, b) are inflated with codecs/Deflate when compressed and kept as Tree.Array
-- values (every element as an f64; 64-bit integers past 2^53 lose precision there); scalar L values past 2^53 become
-- the string "L<hex>" so ids stay exact. Never throws: errors are returned (nil, message, offset).
local Deflate = require("@formats/codecs/Deflate")
local Binary = {}
export type Node = { name: string, props: { any }, children: { Node } }
export type Array = { array: true, type: string, count: number, data: buffer }
local MAGIC = "Kaydara FBX Binary \0"
Binary.MAGIC = MAGIC
local FOOT_ID = "\250\188\171\9\208\200\212\102\177\118\251\131\28\247\38\126"
local FOOT_MAGIC = "\248\90\140\106\222\245\217\126\236\233\12\227\117\143\41\11"
local MAX_DEPTH = 128
local readu8, readu32, readi32, readf32, readf64, readi16 = buffer.readu8, buffer.readu32, buffer.readi32, buffer.readf32, buffer.readf64, buffer.readi16
local writef64 = buffer.writef64
-- a signed 64-bit integer at p: a number when exact (|v| < 2^53), else "L<16 hex digits>"
local function i64(b: buffer, p: number, asString: boolean): any
local lo, hi = readu32(b, p), readu32(b, p + 4)
if hi >= 0x80000000 then
local v = (hi - 4294967296) * 4294967296 + lo
if v >= -9007199254740991 or not asString then
return v
end
else
if hi < 0x200000 or not asString then
return hi * 4294967296 + lo
end
end
return string.format("L%08x%08x", hi, lo)
end
Binary.i64 = i64
local ELEM = { f = 4, d = 8, l = 8, i = 4, b = 1, c = 1 }
-- the elements of a raw array (n elements of type t at p) as f64s
local function toF64(t: string, src: buffer, p: number, n: number): buffer
local out = buffer.create(n * 8)
if t == "d" then
buffer.copy(out, 0, src, p, n * 8)
elseif t == "f" then
for k = 0, n - 1 do
writef64(out, k * 8, readf32(src, p + k * 4))
end
elseif t == "i" then
for k = 0, n - 1 do
writef64(out, k * 8, readi32(src, p + k * 4))
end
elseif t == "l" then
for k = 0, n - 1 do
local lo, hi = readu32(src, p + k * 8), readu32(src, p + k * 8 + 4)
writef64(out, k * 8, if hi >= 0x80000000 then (hi - 4294967296) * 4294967296 + lo else hi * 4294967296 + lo)
end
else
for k = 0, n - 1 do
writef64(out, k * 8, readu8(src, p + k))
end
end
return out
end
-- parse(buf, base, limit, opts?) -> root node (name "", children = the top-level nodes), version | nil, message, offset
function Binary.parse(b: buffer, base: number, limit: number, opts: { maxBytes: number? }?): (Node?, any, number?)
local maxBytes = opts and opts.maxBytes or 2 ^ 30
if limit - base < 27 or buffer.readstring(b, base, 21) ~= MAGIC then
return nil, "not a binary FBX", base
end
local version = readu32(b, base + 23)
if version < 7000 or version >= 10000 then
return nil, "unsupported:FBX version " .. version, base + 23
end
local wide = version >= 7500
local head = if wide then 25 else 13
local total = 0
local function props(p: number, n: number, stop: number): ({ any }?, any)
local out = table.create(math.min(n, 64))
for k = 1, n do
if p >= stop then
return nil, "property list runs past its record"
end
local c = readu8(b, p)
p += 1
local v: any
if c == 89 then -- Y
if p + 2 > stop then return nil, "truncated property" end
v = readi16(b, p)
p += 2
elseif c == 67 then -- C
if p + 1 > stop then return nil, "truncated property" end
v = readu8(b, p) ~= 0
p += 1
elseif c == 73 then -- I
if p + 4 > stop then return nil, "truncated property" end
v = readi32(b, p)
p += 4
elseif c == 70 then -- F
if p + 4 > stop then return nil, "truncated property" end
v = readf32(b, p)
p += 4
elseif c == 68 then -- D
if p + 8 > stop then return nil, "truncated property" end
v = readf64(b, p)
p += 8
elseif c == 76 then -- L
if p + 8 > stop then return nil, "truncated property" end
v = i64(b, p, true)
p += 8
elseif c == 83 or c == 82 then -- S, R
if p + 4 > stop then return nil, "truncated property" end
local len = readu32(b, p)
p += 4
if len > stop - p then return nil, "string runs past its record" end
if c == 83 then
v = buffer.readstring(b, p, len)
else
local raw = buffer.create(len)
buffer.copy(raw, 0, b, p, len)
v = raw
end
p += len
elseif c == 102 or c == 100 or c == 108 or c == 105 or c == 98 or c == 99 then -- f d l i b c
if p + 12 > stop then return nil, "truncated array header" end
local count, enc, clen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8)
p += 12
local t = string.char(c)
local es = ELEM[t]
if clen > stop - p then return nil, "array runs past its record" end
total += count * 8
if total > maxBytes then return nil, "limit:arrays over " .. maxBytes .. " bytes" end
local data: buffer
if enc == 0 then
if clen < count * es then return nil, "raw array shorter than its count" end
data = toF64(t, b, p, count)
elseif enc == 1 then
local raw, err = Deflate.zlib(b, p, clen, count * es)
if not raw then
return nil, "array: " .. tostring(if type(err) == "table" then err.message else err)
end
data = toF64(t, raw, 0, count)
else
return nil, "unknown array encoding " .. enc
end
p += clen
v = { array = true, type = t, count = count, data = data }
else
return nil, string.format("unknown property type 0x%02x", c)
end
out[k] = v
end
return out, p
end
-- one node record at p: node | false (the null record), next offset | nil, message, offset
local function node(p: number, stop: number, depth: number): (any, any, number?)
if p + head > stop then
return nil, "truncated node record", p
end
local endOff, nprops, plen, nlen
if wide then
endOff = readu32(b, p) + readu32(b, p + 4) * 4294967296
nprops = readu32(b, p + 8) + readu32(b, p + 12) * 4294967296
plen = readu32(b, p + 16) + readu32(b, p + 20) * 4294967296
nlen = readu8(b, p + 24)
else
endOff, nprops, plen, nlen = readu32(b, p), readu32(b, p + 4), readu32(b, p + 8), readu8(b, p + 12)
end
if endOff == 0 then
return false, p + head
end
local e = base + endOff
if e > stop or e < p + head + nlen + plen then
return nil, "node end offset out of range", p
end
if nprops > plen then
return nil, "more properties than bytes", p
end
local q = p + head
local name = buffer.readstring(b, q, nlen)
q += nlen
local pl, nq = props(q, nprops, q + plen)
if not pl then
return nil, nq, q
end
q += plen
local children: { Node } = {}
if q < e then
if depth >= MAX_DEPTH then
return nil, "nodes nested too deep", p
end
while q < e do
local child, nx, off = node(q, e, depth + 1)
if child == nil then
return nil, nx, off
end
q = nx
if child == false then
break
end
table.insert(children, child)
end
end
return { name = name, props = pl, children = children }, e
end
local root: Node = { name = "", props = {}, children = {} }
local p = base + 27
while p < limit do
local n, nx, off = node(p, limit, 0)
if n == nil then
if #root.children > 0 and p + head > limit then
break -- a file cut right after its last node: keep what was read
end
return nil, nx, off
end
if n == false then
break
end
table.insert(root.children, n)
p = nx
end
return root, version, nil
end
-- ------------------------------------------------------------------------------------------------ writer
-- write(root, version?) -> buffer: the children of root as a binary FBX file (default version 7400, the 32-bit
-- record layout; 7500+ writes 64-bit records). Values: numbers are written as D unless the node gives a type hint
-- (node.types = "ILDS..." one character per property), booleans as C, strings as S, buffers as R, Arrays by their
-- type (compressed with zlib when longer than 32 elements, unless compress = false).
export type WNode = { name: string, props: { any }, children: { WNode }?, types: string? }
local function sizeHint(n: WNode): number
local s = 32 + #n.name
for _, v in n.props do
if type(v) == "string" then
s += 5 + #v
elseif type(v) == "buffer" then
s += 5 + buffer.len(v)
elseif type(v) == "table" then
s += 13 + (v.count or 0) * 8
else
s += 9
end
end
for _, c in n.children or {} do
s += sizeHint(c)
end
return s
end
function Binary.write(root: WNode, version: number?, compress: boolean?): buffer
local zip = compress ~= false
local ver = version or 7400
local wide = ver >= 7500
local head = if wide then 25 else 13
local cap = sizeHint(root) + 256
local out = buffer.create(cap)
local pos = 0
local function ensure(n: number)
if pos + n > cap then
while pos + n > cap do
cap *= 2
end
local nb = buffer.create(cap)
buffer.copy(nb, 0, out, 0, pos)
out = nb
end
end
local function u8(v: number)
ensure(1)
buffer.writeu8(out, pos, v)
pos += 1
end
local function u32(v: number)
ensure(4)
buffer.writeu32(out, pos, v)
pos += 4
end
local function i64w(v: number)
ensure(8)
local hi = math.floor(v / 4294967296)
local lo = v - hi * 4294967296
buffer.writeu32(out, pos, lo)
buffer.writeu32(out, pos + 4, hi % 4294967296)
pos += 8
end
local function str(s: string)
ensure(#s)
buffer.writestring(out, pos, s)
pos += #s
end
local function bytes(src: buffer)
local n = buffer.len(src)
ensure(n)
buffer.copy(out, pos, src, 0, n)
pos += n
end
local function array(a: any)
local t, n, d = a.type, a.count, a.data
local es = ELEM[t] or 8
local raw = buffer.create(n * es)
if a.raw then
buffer.copy(raw, 0, a.raw, 0, math.min(buffer.len(a.raw), n * es))
else
for k = 0, n - 1 do
local v = readf64(d, k * 8)
if t == "d" then
writef64(raw, k * 8, v)
elseif t == "f" then
buffer.writef32(raw, k * 4, v)
elseif t == "i" then
buffer.writei32(raw, k * 4, v)
elseif t == "b" then
buffer.writeu8(raw, k, if v ~= 0 then 1 else 0)
else
local hi = math.floor(v / 4294967296)
buffer.writeu32(raw, k * 8, v - hi * 4294967296)
buffer.writeu32(raw, k * 8 + 4, hi % 4294967296)
end
end
end
u8(string.byte(t))
u32(n)
if zip and n > 32 then
local z = Deflate.zlibCompress(raw, { level = 6 })
if z then
u32(1)
u32(buffer.len(z))
bytes(z)
return
end
end
u32(0)
u32(n * es)
bytes(raw)
end
local function setOff(at: number, v: number)
if wide then
buffer.writeu32(out, at, v % 4294967296)
buffer.writeu32(out, at + 4, math.floor(v / 4294967296))
else
buffer.writeu32(out, at, v)
end
end
local function nullRecord()
ensure(head)
buffer.fill(out, pos, 0, head)
pos += head
end
local function node(n: WNode)
local start = pos
ensure(head)
buffer.fill(out, pos, 0, head)
pos += head
buffer.writeu8(out, start + head - 1, #n.name)
str(n.name)
local pstart = pos
local hints = n.types or ""
for k, v in n.props do
local h = string.sub(hints, k, k)
local tv = type(v)
if tv == "number" then
if h == "I" then
u8(73)
ensure(4)
buffer.writei32(out, pos, v)
pos += 4
elseif h == "L" then
u8(76)
i64w(v)
elseif h == "F" then
u8(70)
ensure(4)
buffer.writef32(out, pos, v)
pos += 4
elseif h == "Y" then
u8(89)
ensure(2)
buffer.writei16(out, pos, v)
pos += 2
else
u8(68)
ensure(8)
writef64(out, pos, v)
pos += 8
end
elseif tv == "boolean" then
u8(67)
u8(if v then 1 else 0)
elseif tv == "string" then
if string.sub(v, 1, 1) == "L" and h == "L" and #v == 17 then
u8(76)
local hi, lo = tonumber(string.sub(v, 2, 9), 16) or 0, tonumber(string.sub(v, 10, 17), 16) or 0
u32(lo)
u32(hi)
else
u8(83)
u32(#v)
str(v)
end
elseif tv == "buffer" then
u8(82)
u32(buffer.len(v))
bytes(v)
elseif tv == "table" and v.array then
array(v)
else
u8(83)
u32(0)
end
end
local plen = pos - pstart
local children = n.children
if children and #children > 0 then
for _, c in children do
node(c)
end
nullRecord()
elseif #n.props == 0 then
nullRecord()
end
setOff(start, pos)
if wide then
setOff(start + 8, #n.props)
setOff(start + 16, plen)
else
buffer.writeu32(out, start + 4, #n.props)
buffer.writeu32(out, start + 8, plen)
end
end
str(MAGIC)
u8(0x1A)
u8(0)
u32(ver)
for _, c in root.children or {} do
node(c)
end
nullRecord()
str(FOOT_ID)
str("\0\0\0\0")
local pad = ((pos + 15) // 16) * 16 - pos
if pad == 0 then
pad = 16
end
str(string.rep("\0", pad))
u32(ver)
str(string.rep("\0", 120))
str(FOOT_MAGIC)
local res = buffer.create(pos)
buffer.copy(res, 0, out, 0, pos)
return res
end
return Binary
File diff suppressed because it is too large. Load diff
+996
View File
@@ -0,0 +1,996 @@
--!strict
-- model/fbx/Write: Scene -> an FBX 7.4 node tree (model/fbx/Binary.write / Ascii.write serialize it). Property types
-- follow what Blender's and the FBX SDK's readers check (ids L, ints I, doubles D, KTime L, arrays d / i / l / f).
-- Nodes -> Model (Mesh / Null / LimbNode / Camera / Light) with Lcl T / R (Euler XYZ degrees) / S; meshes -> one
-- Geometry (primitives merged; triangles, polygons, strips and fans; control points = the Scene vertices; normals
-- ByVertice, uvs and colours ByPolygonVertex IndexToDirect, materials ByPolygon); materials -> Phong Material;
-- textures -> Texture + Video (Content embedded); skins -> Skin + Cluster deformers + BindPose; morph targets ->
-- BlendShape / BlendShapeChannel / Shape; animations -> AnimationStack / Layer / CurveNode / Curve.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Xform = require("@formats/model/fbx/Xform")
local Write = {}
type WNode = { name: string, props: { any }, children: { WNode }?, types: string? }
local TICKS = 46186158000
local ORIENT_INV = { camera = { 0, 90, 0 }, light = { 90, 0, 0 } }
local function N(name: string, types: string, props: { any }, children: { WNode }?): WNode
return { name = name, types = types, props = props, children = children }
end
local function arr(t: string, list: { number }): any
local n = #list
local d = buffer.create(n * 8)
for k = 1, n do
buffer.writef64(d, (k - 1) * 8, list[k])
end
return { array = true, type = t, count = n, data = d }
end
-- P: name, type, label, flags, values (vt: one type character per value)
local function P(name: string, ptype: string, label: string, flags: string, vt: string, ...: any): WNode
return { name = "P", types = "SSSS" .. vt, props = { name, ptype, label, flags, ... } }
end
local function Pvec(name: string, ptype: string, label: string, v: { number }): WNode
return P(name, ptype, label, "A", "DDD", v[1], v[2], v[3])
end
local function Pcolor(name: string, v: { number }): WNode
return P(name, "Color", "", "A", "DDD", v[1] or 0, v[2] or 0, v[3] or 0)
end
local function Pnum(name: string, v: number): WNode
return P(name, "Number", "", "A", "D", v)
end
local function Pint(name: string, v: number): WNode
return P(name, "int", "Integer", "", "I", v)
end
local function Penum(name: string, v: number): WNode
return P(name, "enum", "", "", "I", v)
end
local function Pdouble(name: string, v: number): WNode
return P(name, "double", "Number", "", "D", v)
end
local function Ptime(name: string, v: number): WNode
return P(name, "KTime", "Time", "", "L", v)
end
local function cls(name: string?, class: string): string
return (name or "") .. "\0\1" .. class
end
local function accessorReader(acc: Types.Accessor?): ((i: number, c: number) -> number)?
if not acc then
return nil
end
return Types.Scene.reader(acc)
end
-- primitive -> triangles / polygons as a list of corner lists (vertex indices, 0-based)
local function faces(prim: Types.Primitive): { { number } }?
local pos = prim.attributes.POSITION
if not pos then
return nil
end
local n = pos.count
local idx = accessorReader(prim.indices)
local count = if prim.indices then prim.indices.count else n
local function I(k: number): number
return if idx then idx(k, 0) else k
end
local out: { { number } } = {}
local mode = prim.mode or "triangles"
if mode == "triangles" then
for k = 0, count // 3 - 1 do
table.insert(out, { I(k * 3), I(k * 3 + 1), I(k * 3 + 2) })
end
elseif mode == "polygons" and prim.faces then
local f = accessorReader(prim.faces)
local p = 0
if f then
for k = 0, prim.faces.count - 1 do
local sz = f(k, 0)
if p + sz > count then
break
end
local poly = table.create(sz)
for q = 0, sz - 1 do
poly[q + 1] = I(p + q)
end
p += sz
table.insert(out, poly)
end
end
elseif mode == "triangle_strip" then
for k = 0, count - 3 do
local a, b, c = I(k), I(k + 1), I(k + 2)
if k % 2 == 1 then
a, b = b, a
end
table.insert(out, { a, b, c })
end
elseif mode == "triangle_fan" then
for k = 1, count - 2 do
table.insert(out, { I(0), I(k), I(k + 1) })
end
else
return nil -- points / lines: not written
end
for _, f in out do
for q, v in f do
if v < 0 or v >= n then
f[q] = 0
end
end
end
return out
end
function Write.tree(scene: Types.Scene, opts: any?): (WNode?, Err.Err?)
local flipV = not (opts and opts.flipV == false)
local embed = not (opts and opts.embedTextures == false)
local nextId = 1000000
local function id(): number
nextId += 1
return nextId
end
local objects: { WNode } = {}
local conns: { WNode } = {}
local counts: { [string]: number } = {}
local function add(class: string, node: WNode)
table.insert(objects, node)
counts[class] = (counts[class] or 0) + 1
end
local function OO(child: number, parent: number)
table.insert(conns, N("C", "SLL", { "OO", child, parent }))
end
local function OP(child: number, parent: number, prop: string)
table.insert(conns, N("C", "SLLS", { "OP", child, parent, prop }))
end
local nodes = scene.nodes or {}
-- ------------------------------------------------------------------------------------------ textures
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/bmp"] = "bmp", ["image/webp"] = "webp", ["image/x-tga"] = "tga", ["image/vnd-ms.dds"] = "dds", ["image/tiff"] = "tif" }
local texIds: { [number]: number } = {}
local base = opts and opts.name and string.gsub(string.match(opts.name, "([^/\\]+)$") or opts.name, "%.[^.]*$", "") or "model"
for ti, tex in scene.textures or {} do
local file = tex.uri or (base .. "_" .. (tex.name or tostring(ti)) .. "." .. (EXT[tex.mime or ""] or "png"))
local tname = tex.name or ("Texture" .. ti)
local vid, tid = id(), id()
local vchildren = {
N("Type", "S", { "Clip" }),
N("Properties70", "", {}, { P("Path", "KString", "XRefUrl", "", "S", file) }),
N("UseMipMap", "I", { 0 }),
N("Filename", "S", { file }),
N("RelativeFilename", "S", { file }),
}
if embed and tex.data then
table.insert(vchildren, N("Content", "R", { tex.data }))
end
add("Video", N("Video", "LSS", { vid, cls(tname, "Video"), "Clip" }, vchildren))
local tp = { P("UseMaterial", "bool", "", "", "I", 1) }
local smp = tex.sampler
if smp and smp.wrapS == "clamp" then
table.insert(tp, Penum("WrapModeU", 1))
end
if smp and smp.wrapT == "clamp" then
table.insert(tp, Penum("WrapModeV", 1))
end
add("Texture", N("Texture", "LSS", { tid, cls(tname, "Texture"), "" }, {
N("Type", "S", { "TextureVideoClip" }),
N("Version", "I", { 202 }),
N("TextureName", "S", { cls(tname, "Texture") }),
N("Properties70", "", {}, tp),
N("Media", "S", { cls(tname, "Video") }),
N("FileName", "S", { file }),
N("RelativeFilename", "S", { file }),
N("ModelUVTranslation", "DD", { 0, 0 }),
N("ModelUVScaling", "DD", { 1, 1 }),
N("Texture_Alpha_Source", "S", { "None" }),
N("Cropping", "IIII", { 0, 0, 0, 0 }),
}))
OO(vid, tid)
texIds[ti] = tid
end
-- ------------------------------------------------------------------------------------------ materials
local matIds: { [number]: number } = {}
for mi, m in scene.materials or {} do
local x = m.extras and (m.extras :: any).fbx or {}
local bc = m.baseColor or { 1, 1, 1, 1 }
local alpha = bc[4] or 1
local rough = math.clamp(m.roughness or 1, 0.02, 1)
local shin = if type(x.shininess) == "number" then x.shininess else 2 / (rough * rough) - 2
local em = m.emissive or { 0, 0, 0 }
local spec = if type(x.specular) == "table" then x.specular else { 0.2, 0.2, 0.2 }
local pid = id()
local props = {
Pcolor("AmbientColor", if type(x.ambient) == "table" then x.ambient else { 0, 0, 0 }),
Pnum("AmbientFactor", if type(x.ambientFactor) == "number" then x.ambientFactor else 1),
Pcolor("DiffuseColor", { bc[1], bc[2], bc[3] }),
Pnum("DiffuseFactor", 1),
Pcolor("EmissiveColor", em),
Pnum("EmissiveFactor", 1),
Pcolor("SpecularColor", spec),
Pnum("SpecularFactor", if type(x.specularFactor) == "number" then x.specularFactor else 1),
Pnum("Shininess", shin),
Pnum("ShininessExponent", shin),
Pcolor("TransparentColor", { 1, 1, 1 }),
Pnum("TransparencyFactor", 1 - alpha),
Pnum("Opacity", alpha),
Pcolor("ReflectionColor", if type(x.reflection) == "table" then x.reflection else { 0, 0, 0 }),
Pnum("ReflectionFactor", if type(x.reflectionFactor) == "number" then x.reflectionFactor else 0),
}
add("Material", N("Material", "LSS", { pid, cls(m.name or ("Material" .. mi), "Material"), "" }, {
N("Version", "I", { 102 }),
N("ShadingModel", "S", { if type(x.shadingModel) == "string" and x.shadingModel ~= "unknown" then x.shadingModel else "phong" }),
N("MultiLayer", "I", { 0 }),
N("Properties70", "", {}, props),
}))
matIds[mi] = pid
local function link(ref: Types.TextureRef?, prop: string)
local t = ref and texIds[ref.texture]
if t then
OP(t, pid, prop)
end
end
link(m.baseColorTexture, "DiffuseColor")
link(m.normalTexture, "NormalMap")
link(m.emissiveTexture, "EmissiveColor")
-- the other textures the FBX material had (specular, metalness, ... maps), under their property names
local linked = {
[m.baseColorTexture and m.baseColorTexture.texture or -1] = true,
[m.normalTexture and m.normalTexture.texture or -1] = true,
[m.emissiveTexture and m.emissiveTexture.texture or -1] = true,
}
if type(x.textures) == "table" then
local props = {}
for prop in x.textures do
table.insert(props, prop)
end
table.sort(props)
for _, prop in props do
local ti = x.textures[prop]
if type(ti) == "number" and not linked[ti] and texIds[ti] then
linked[ti] = true
OP(texIds[ti], pid, prop)
end
end
end
end
-- ------------------------------------------------------------------------------------------ models
local modelIds: { [number]: number } = {}
local skip: { [number]: boolean } = {}
local attrHost: { [number]: number } = {} -- orientation node -> its parent node (the attribute moves there)
local parentOf: { [number]: number } = {}
for i, nd in nodes do
for _, c in nd.children or {} do
if parentOf[c] == nil and c ~= i then
parentOf[c] = i
end
end
end
local jointSet: { [number]: boolean } = {}
for _, s in scene.skins or {} do
for _, j in s.joints do
jointSet[j] = true
end
end
for i, nd in nodes do
local o = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.orientation
local p = parentOf[i]
if o and p and (nd.camera or nd.light) and #(nd.children or {}) == 0 and not nd.mesh and not nodes[p].camera and not nodes[p].light then
skip[i] = true
attrHost[i] = p
end
end
-- world matrices (rest pose) for clusters and the bind pose
local worldM: { [number]: Xform.M4 } = {}
local visiting: { [number]: boolean } = {}
local function world(i: number): Xform.M4
if worldM[i] then
return worldM[i]
end
if visiting[i] then
return Xform.identity()
end
visiting[i] = true
local nd = nodes[i]
local l = if nd.matrix and #nd.matrix == 16 then nd.matrix else Xform.compose(nd.translation, nd.rotation, nd.scale)
local p = parentOf[i]
local w = if p then Xform.mul(world(p), l) else l
worldM[i] = w
return w
end
local function trs(nd: Types.Node): ({ number }, { number }, { number })
if nd.matrix and #nd.matrix == 16 then
return Xform.decompose(nd.matrix)
end
return nd.translation or { 0, 0, 0 }, nd.rotation or { 0, 0, 0, 1 }, nd.scale or { 1, 1, 1 }
end
local function model(name: string, sub: string, t: { number }, r: { number }, s: { number }): number
local mid = id()
add("Model", N("Model", "LSS", { mid, cls(name, "Model"), sub }, {
N("Version", "I", { 232 }),
N("Properties70", "", {}, {
Penum("RotationOrder", 0),
Penum("InheritType", 1),
Pint("DefaultAttributeIndex", 0),
Pvec("Lcl Translation", "Lcl Translation", "", t),
Pvec("Lcl Rotation", "Lcl Rotation", "", r),
Pvec("Lcl Scaling", "Lcl Scaling", "", s),
}),
N("Shading", "C", { true }),
N("Culling", "S", { "CullingOff" }),
}))
return mid
end
local function attribute(nd: Types.Node, mid: number, nodeName: string)
if nd.camera and scene.cameras[nd.camera] then
local c = scene.cameras[nd.camera]
local aid = id()
local aspect = c.aspect or 4 / 3
local fh = 0.612
local fw = fh * aspect
local props
if c.type == "orthographic" then
props = { Penum("CameraProjectionType", 1), Pdouble("OrthoZoom", c.ymag or 1), Pdouble("AspectWidth", aspect * 100), Pdouble("AspectHeight", 100), Pdouble("NearPlane", c.znear or 0.1), Pdouble("FarPlane", c.zfar or 1000), Pdouble("FilmWidth", fw), Pdouble("FilmHeight", fh) }
else
local yfov = c.yfov or 0.8
local hfov = 2 * math.atan(math.tan(yfov / 2) * aspect)
local focal = fw * 25.4 / (2 * math.tan(hfov / 2))
props = {
Penum("CameraProjectionType", 0),
Penum("ApertureMode", 1),
P("FieldOfView", "FieldOfView", "", "A", "D", hfov * 180 / math.pi),
P("FocalLength", "Number", "", "A", "D", focal),
Pdouble("FilmWidth", fw),
Pdouble("FilmHeight", fh),
Penum("AspectRatioMode", 0),
Pdouble("AspectWidth", aspect * 100),
Pdouble("AspectHeight", 100),
Pdouble("NearPlane", c.znear or 0.1),
Pdouble("FarPlane", c.zfar or 1000),
}
end
add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(c.name or nodeName, "NodeAttribute"), "Camera" }, {
N("Properties70", "", {}, props),
N("TypeFlags", "S", { "Camera" }),
N("GeometryVersion", "I", { 124 }),
}))
OO(aid, mid)
elseif nd.light and scene.lights[nd.light] then
local l = scene.lights[nd.light]
local aid = id()
local lt = if l.type == "directional" then 1 elseif l.type == "spot" then 2 else 0
local props = {
Penum("LightType", lt),
Pcolor("Color", l.color or { 1, 1, 1 }),
Pnum("Intensity", (l.intensity or 1) * 100),
P("CastLight", "bool", "", "", "I", 1),
}
if lt == 2 then
table.insert(props, Pnum("InnerAngle", (l.innerCone or 0) * 360 / math.pi))
table.insert(props, Pnum("OuterAngle", (l.outerCone or math.pi / 4) * 360 / math.pi))
end
if l.range then
table.insert(props, P("EnableFarAttenuation", "bool", "", "", "I", 1))
table.insert(props, Pnum("FarAttenuationEnd", l.range))
end
add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(l.name or nodeName, "NodeAttribute"), "Light" }, {
N("Properties70", "", {}, props),
N("TypeFlags", "S", { "Light" }),
N("GeometryVersion", "I", { 124 }),
}))
OO(aid, mid)
end
end
for i, nd in nodes do
if not skip[i] then
local t, r, s = trs(nd)
local euler = Xform.eulerXYZ(r)
local ftype = nd.extras and (nd.extras :: any).fbx and (nd.extras :: any).fbx.type
local sub = if nd.mesh then "Mesh" elseif jointSet[i] or ftype == "LimbNode" then "LimbNode" else "Null"
-- an orientation child folded into this node gives it its attribute
local folded: number? = nil
for c, host in pairs(attrHost) do -- pairs: a sparse integer map (compat __iter takes it for an array)
if host == i then
folded = c
end
end
if not nd.mesh and folded then
sub = if nodes[folded].camera then "Camera" else "Light"
end
local mid = model(nd.name or ("Node" .. i), sub, t, euler, s)
modelIds[i] = mid
if sub == "LimbNode" then
local aid = id()
add("NodeAttribute", N("NodeAttribute", "LSS", { aid, cls(nd.name, "NodeAttribute"), "LimbNode" }, { N("TypeFlags", "S", { "Skeleton" }) }))
OO(aid, mid)
end
if folded then
attribute(nodes[folded], mid, nd.name or "")
end
if nd.camera or nd.light then
-- a glTF-oriented camera / light: an FBX-oriented child model carries it
local kind = if nd.camera then "camera" else "light"
local cmid = model((nd.name or "") .. "_" .. kind, if nd.camera then "Camera" else "Light", { 0, 0, 0 }, ORIENT_INV[kind], { 1, 1, 1 })
OO(cmid, mid)
attribute(nd, cmid, nd.name or "")
end
end
end
for i in nodes do
local mid = modelIds[i]
if mid then
local p = parentOf[i]
local pm = p and modelIds[p]
OO(mid, pm or 0)
end
end
-- ------------------------------------------------------------------------------------------ geometry
local geoIds: { [number]: number } = {}
local geoSlots: { [number]: { number } } = {} -- mesh -> material indices by slot
local geoVerts: { [number]: { { prim: Types.Primitive, offset: number } } } = {}
local geoChannels: any = {} -- mesh index -> blend shape channel ids (for weights animation)
local geoCount: { [number]: number } = {}
local function geometry(mi: number): number?
if geoIds[mi] then
return geoIds[mi]
end
local mesh = scene.meshes[mi]
if not mesh then
return nil
end
local V, PVI, NRM, MATS = {}, {}, {}, {}
local UV: { [number]: { number } } = {}
local UVI: { [number]: { number } } = {}
local COL: { [number]: { number } } = {}
local COLI: { [number]: { number } } = {}
local slots: { number } = {}
local slotOf: { [number]: number } = {}
local hasN = false
local nuv, ncol = 0, 0
for _, prim in mesh.primitives do
for k = 0, 7 do
if prim.attributes["TEXCOORD_" .. k] then
nuv = math.max(nuv, k + 1)
end
if prim.attributes["COLOR_" .. k] then
ncol = math.max(ncol, k + 1)
end
end
if prim.attributes.NORMAL then
hasN = true
end
end
for k = 1, nuv do
UV[k], UVI[k] = {}, {}
end
for k = 1, ncol do
COL[k], COLI[k] = {}, {}
end
local layout = {}
local offset = 0
for _, prim in mesh.primitives do
local fs = faces(prim)
local pos = prim.attributes.POSITION
local R = accessorReader(pos)
if fs and R and pos then
table.insert(layout, { prim = prim, offset = offset })
local n = pos.count
for v = 0, n - 1 do
table.insert(V, R(v, 0))
table.insert(V, R(v, 1))
table.insert(V, R(v, 2))
end
local NR = accessorReader(prim.attributes.NORMAL)
if hasN then
for v = 0, n - 1 do
if NR then
table.insert(NRM, NR(v, 0))
table.insert(NRM, NR(v, 1))
table.insert(NRM, NR(v, 2))
else
table.insert(NRM, 0)
table.insert(NRM, 0)
table.insert(NRM, 1)
end
end
end
local uvBase: { number } = {}
for k = 1, nuv do
uvBase[k] = #UV[k] // 2
local T = accessorReader(prim.attributes["TEXCOORD_" .. (k - 1)])
for v = 0, n - 1 do
local u, w = 0, 0
if T then
u, w = T(v, 0), T(v, 1)
end
table.insert(UV[k], u)
table.insert(UV[k], if flipV then 1 - w else w)
end
end
local colBase: { number } = {}
for k = 1, ncol do
colBase[k] = #COL[k] // 4
local acc = prim.attributes["COLOR_" .. (k - 1)]
local C = accessorReader(acc)
local comps = acc and acc.components or 4
for v = 0, n - 1 do
table.insert(COL[k], if C then C(v, 0) else 1)
table.insert(COL[k], if C then C(v, 1) else 1)
table.insert(COL[k], if C then C(v, 2) else 1)
table.insert(COL[k], if C and comps >= 4 then C(v, 3) else 1)
end
end
local mat = prim.material or 0
local slot = slotOf[mat]
if slot == nil then
table.insert(slots, mat)
slot = #slots - 1
slotOf[mat] = slot
end
for _, f in fs do
for q, v in f do
local cp = v + offset
table.insert(PVI, if q == #f then -cp - 1 else cp)
for k = 1, nuv do
table.insert(UVI[k], uvBase[k] + v)
end
for k = 1, ncol do
table.insert(COLI[k], colBase[k] + v)
end
end
table.insert(MATS, slot)
end
offset += n
end
end
if #PVI == 0 then
return nil
end
local gid = id()
local ch: { WNode } = {
N("Properties70", "", {}, {}),
N("GeometryVersion", "I", { 124 }),
N("Vertices", "", { arr("d", V) }),
N("PolygonVertexIndex", "", { arr("i", PVI) }),
}
local layer0: { WNode } = { N("Version", "I", { 100 }) }
if hasN then
table.insert(ch, N("LayerElementNormal", "I", { 0 }, {
N("Version", "I", { 101 }),
N("Name", "S", { "" }),
N("MappingInformationType", "S", { "ByVertice" }),
N("ReferenceInformationType", "S", { "Direct" }),
N("Normals", "", { arr("d", NRM) }),
}))
table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementNormal" }), N("TypedIndex", "I", { 0 }) }))
end
local extraLayers: { WNode } = {}
local uvNames = mesh.extras and (mesh.extras :: any).fbx and (mesh.extras :: any).fbx.uvSets or {}
for k = 1, nuv do
table.insert(ch, N("LayerElementUV", "I", { k - 1 }, {
N("Version", "I", { 101 }),
N("Name", "S", { if type(uvNames[k]) == "string" then uvNames[k] else (if k == 1 then "UVMap" else "UVMap" .. k) }),
N("MappingInformationType", "S", { "ByPolygonVertex" }),
N("ReferenceInformationType", "S", { "IndexToDirect" }),
N("UV", "", { arr("d", UV[k]) }),
N("UVIndex", "", { arr("i", UVI[k]) }),
}))
local le = N("LayerElement", "", {}, { N("Type", "S", { "LayerElementUV" }), N("TypedIndex", "I", { k - 1 }) })
if k == 1 then
table.insert(layer0, le)
else
table.insert(extraLayers, N("Layer", "I", { k - 1 }, { N("Version", "I", { 100 }), le }))
end
end
for k = 1, ncol do
table.insert(ch, N("LayerElementColor", "I", { k - 1 }, {
N("Version", "I", { 101 }),
N("Name", "S", { "Col" .. (if k > 1 then tostring(k) else "") }),
N("MappingInformationType", "S", { "ByPolygonVertex" }),
N("ReferenceInformationType", "S", { "IndexToDirect" }),
N("Colors", "", { arr("d", COL[k]) }),
N("ColorIndex", "", { arr("i", COLI[k]) }),
}))
if k == 1 then
table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementColor" }), N("TypedIndex", "I", { 0 }) }))
end
end
local anyMat = false
for _, m in slots do
if m ~= 0 and matIds[m] then
anyMat = true
end
end
if anyMat then
local allSame = #slots == 1
table.insert(ch, N("LayerElementMaterial", "I", { 0 }, {
N("Version", "I", { 101 }),
N("Name", "S", { "" }),
N("MappingInformationType", "S", { if allSame then "AllSame" else "ByPolygon" }),
N("ReferenceInformationType", "S", { "IndexToDirect" }),
N("Materials", "", { arr("i", if allSame then { 0 } else MATS) }),
}))
table.insert(layer0, N("LayerElement", "", {}, { N("Type", "S", { "LayerElementMaterial" }), N("TypedIndex", "I", { 0 }) }))
end
table.insert(ch, N("Layer", "I", { 0 }, layer0))
for _, l in extraLayers do
table.insert(ch, l)
end
add("Geometry", N("Geometry", "LSS", { gid, cls(mesh.name or ("Mesh" .. mi), "Geometry"), "Mesh" }, ch))
geoIds[mi] = gid
geoSlots[mi] = if anyMat then slots else {}
geoVerts[mi] = layout
geoCount[mi] = offset
-- morph targets
local prims = mesh.primitives
local ntargets = 0
for _, l in layout do
ntargets = math.max(ntargets, if l.prim.targets then #(l.prim.targets :: any) else 0)
end
if ntargets > 0 then
local bsid = id()
add("Deformer", N("Deformer", "LSS", { bsid, cls(mesh.name, "Deformer"), "BlendShape" }, { N("Version", "I", { 100 }) }))
OO(bsid, gid)
local names = mesh.extras and (mesh.extras :: any).targetNames or {}
for t = 1, ntargets do
local IDX, DV, DN = {}, {}, {}
local anyN = false
for _, l in layout do
local tg = l.prim.targets and (l.prim.targets :: any)[t]
if tg and tg.NORMAL then
anyN = true
end
end
for _, l in layout do
local tg = l.prim.targets and (l.prim.targets :: any)[t]
local TP = tg and accessorReader(tg.POSITION)
local TN = tg and accessorReader(tg.NORMAL)
if TP then
for v = 0, l.prim.attributes.POSITION.count - 1 do
local x, y, z = TP(v, 0), TP(v, 1), TP(v, 2)
local nx, ny, nz = 0, 0, 0
if TN then
nx, ny, nz = TN(v, 0), TN(v, 1), TN(v, 2)
end
if x ~= 0 or y ~= 0 or z ~= 0 or nx ~= 0 or ny ~= 0 or nz ~= 0 then
table.insert(IDX, l.offset + v)
table.insert(DV, x)
table.insert(DV, y)
table.insert(DV, z)
if anyN then
table.insert(DN, nx)
table.insert(DN, ny)
table.insert(DN, nz)
end
end
end
end
end
local tname = if type(names[t]) == "string" then names[t] else ("Target" .. t)
local chid, shid = id(), id()
local w = mesh.weights and mesh.weights[t] or 0
add("Deformer", N("Deformer", "LSS", { chid, cls(tname, "SubDeformer"), "BlendShapeChannel" }, {
N("Version", "I", { 100 }),
N("DeformPercent", "D", { w * 100 }),
N("FullWeights", "", { arr("d", { 100 }) }),
N("Properties70", "", {}, { Pnum("DeformPercent", w * 100) }),
}))
local shch = { N("Version", "I", { 100 }), N("Indexes", "", { arr("i", IDX) }), N("Vertices", "", { arr("d", DV) }) }
if anyN then
table.insert(shch, N("Normals", "", { arr("d", DN) }))
end
add("Geometry", N("Geometry", "LSS", { shid, cls(tname, "Geometry"), "Shape" }, shch))
OO(chid, bsid)
OO(shid, chid)
local gc: any = geoChannels
gc[mi] = gc[mi] or {}
gc[mi][t] = chid
end
end
local _ = prims
return gid
end
local poseNodes: { WNode } = {}
local posed: { [number]: boolean } = {}
local function pose(mid: number, m: Xform.M4)
if posed[mid] then
return
end
posed[mid] = true
table.insert(poseNodes, N("PoseNode", "", {}, { N("Node", "L", { mid }), N("Matrix", "", { arr("d", m) }) }))
end
local skinned: { [string]: boolean } = {}
for i, nd in nodes do
local mid = modelIds[i]
if nd.mesh and mid then
local gid = geometry(nd.mesh)
if gid then
OO(gid, mid)
for _, m in geoSlots[nd.mesh] do
local pm = matIds[m]
if pm then
OO(pm, mid)
end
end
-- skin: one Skin per (geometry, skin)
local skin = nd.skin and scene.skins[nd.skin]
local key = tostring(gid) .. ":" .. tostring(nd.skin)
if skin and not skinned[key] then
skinned[key] = true
local sid = id()
add("Deformer", N("Deformer", "LSS", { sid, cls(nd.name, "Deformer"), "Skin" }, { N("Version", "I", { 101 }), N("Link_DeformAcuracy", "D", { 50 }) }))
OO(sid, gid)
local meshWorld = world(i)
pose(mid, meshWorld)
local ibm = accessorReader(skin.inverseBindMatrices)
-- per joint: control points and weights
local perJoint: { { idx: { number }, w: { number } } } = {}
for j in skin.joints do
perJoint[j] = { idx = {}, w = {} }
end
for _, l in geoVerts[nd.mesh] do
local J = accessorReader(l.prim.attributes.JOINTS_0)
local W = accessorReader(l.prim.attributes.WEIGHTS_0)
if J and W then
for v = 0, l.prim.attributes.POSITION.count - 1 do
for q = 0, 3 do
local j, w = J(v, q), W(v, q)
local pj = perJoint[j + 1]
if w > 0 and pj then
table.insert(pj.idx, l.offset + v)
table.insert(pj.w, w)
end
end
end
end
end
for j, ji in skin.joints do
local jm = modelIds[ji]
if jm then
local IB = Xform.identity()
if ibm and skin.inverseBindMatrices and j <= skin.inverseBindMatrices.count then
for k = 1, 16 do
IB[k] = ibm(j - 1, k - 1)
end
end
local inv = Xform.inverse(IB) or Xform.identity()
local link = Xform.mul(meshWorld, inv)
local cid = id()
add("Deformer", N("Deformer", "LSS", { cid, cls(nodes[ji].name, "SubDeformer"), "Cluster" }, {
N("Version", "I", { 100 }),
N("UserData", "SS", { "", "" }),
N("Indexes", "", { arr("i", perJoint[j].idx) }),
N("Weights", "", { arr("d", perJoint[j].w) }),
N("Transform", "", { arr("d", meshWorld) }),
N("TransformLink", "", { arr("d", link) }),
}))
OO(cid, sid)
OO(jm, cid)
pose(jm, link)
end
end
end
end
end
end
if #poseNodes > 0 then
local pch = { N("Type", "S", { "BindPose" }), N("Version", "I", { 100 }), N("NbPoseNodes", "I", { #poseNodes }) }
for _, pn in poseNodes do
table.insert(pch, pn)
end
add("Pose", N("Pose", "LSS", { id(), cls("BindPose", "Pose"), "BindPose" }, pch))
end
-- ------------------------------------------------------------------------------------------ animations
local tmin, tmax = math.huge, -math.huge
local function curveNode(name: string, layer: number, target: number, prop: string, comps: { { number } }, times: { number }, labels: { string }, step: boolean)
local cnid = id()
local p = {}
for k, lab in labels do
table.insert(p, Pnum("d|" .. lab, comps[k][1] or 0))
end
add("AnimationCurveNode", N("AnimationCurveNode", "LSS", { cnid, cls(name, "AnimCurveNode"), "" }, { N("Properties70", "", {}, p) }))
OO(cnid, layer)
OP(cnid, target, prop)
local ticks = table.create(#times, 0)
for k, t in times do
ticks[k] = math.floor(t * TICKS + 0.5)
end
for k, lab in labels do
local cid = id()
local df = buffer.create(32)
buffer.writeu32(df, 8, 218434821)
local dfa = { array = true, type = "f", count = 4, data = buffer.create(32) }
buffer.writef64(dfa.data, 16, buffer.readf32(df, 8))
add("AnimationCurve", N("AnimationCurve", "LSS", { cid, cls("", "AnimCurve"), "" }, {
N("Default", "D", { comps[k][1] or 0 }),
N("KeyVer", "I", { 4009 }),
N("KeyTime", "", { arr("l", ticks) }),
N("KeyValueFloat", "", { arr("f", comps[k]) }),
N("KeyAttrFlags", "", { arr("i", { if step then 0x00000002 else 0x00000104 }) }),
N("KeyAttrDataFloat", "", { dfa }),
N("KeyAttrRefCount", "", { arr("i", { #times }) }),
}))
OP(cid, cnid, "d|" .. lab)
end
end
local PATH = { translation = { "T", "Lcl Translation", 3 }, rotation = { "R", "Lcl Rotation", 4 }, scale = { "S", "Lcl Scaling", 3 } }
for ai, anim in scene.animations or {} do
local stid, lid = id(), id()
local astart, astop = math.huge, -math.huge
local layerNodes = {}
for _, ch in anim.channels do
local mid = modelIds[ch.node]
local IN = accessorReader(ch.input)
local OUT = accessorReader(ch.output)
local spec = PATH[ch.path]
if IN and OUT and ch.input.count > 0 and mid and (spec or ch.path == "weights") then
local n = ch.input.count
local times = table.create(n, 0)
for k = 0, n - 1 do
times[k + 1] = IN(k, 0)
astart, astop = math.min(astart, times[k + 1]), math.max(astop, times[k + 1])
end
local cubic = ch.interpolation == "CUBICSPLINE"
local step = ch.interpolation == "STEP"
if spec then
local comps = spec[3]
local function val(k: number, c: number): number
local e = if cubic then k * 3 + 1 else k
if e >= ch.output.count then
return 0
end
return OUT(e, c)
end
local X, Y, Z = table.create(n, 0), table.create(n, 0), table.create(n, 0)
local prev: { number }? = nil
for k = 0, n - 1 do
local v
if comps == 4 then
local q = { val(k, 0), val(k, 1), val(k, 2), val(k, 3) }
local ql = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3] + q[4] * q[4])
if ql > 0 then
q = { q[1] / ql, q[2] / ql, q[3] / ql, q[4] / ql }
else
q = { 0, 0, 0, 1 }
end
v = Xform.eulerXYZ(q)
if prev then
for a = 1, 3 do
while v[a] - prev[a] > 180 do
v[a] -= 360
end
while v[a] - prev[a] < -180 do
v[a] += 360
end
end
end
prev = v
else
v = { val(k, 0), val(k, 1), val(k, 2) }
end
X[k + 1], Y[k + 1], Z[k + 1] = v[1], v[2], v[3]
end
table.insert(layerNodes, { spec[1], lid, mid, spec[2], { X, Y, Z }, times, { "X", "Y", "Z" }, step })
else
-- weights: one DeformPercent curve per blend shape channel of the node's mesh
local nd = nodes[ch.node]
local gc: any = geoChannels
local chans = nd.mesh and gc[nd.mesh]
if chans then
local nt = #chans
for t = 1, nt do
local vals = table.create(n, 0)
for k = 0, n - 1 do
local e = if cubic then (k * 3 + 1) * nt + (t - 1) else k * nt + (t - 1)
vals[k + 1] = if e < ch.output.count then OUT(e, 0) * 100 else 0
end
table.insert(layerNodes, { "DeformPercent", lid, chans[t], "DeformPercent", { vals }, times, { "DeformPercent" }, step })
end
end
end
end
end
if astart > astop then
astart, astop = 0, 0
end
tmin, tmax = math.min(tmin, astart), math.max(tmax, astop)
add("AnimationStack", N("AnimationStack", "LSS", { stid, cls(if anim.name and anim.name ~= "" then anim.name else ("Animation" .. ai), "AnimStack"), "" }, {
N("Properties70", "", {}, {
Ptime("LocalStart", math.floor(astart * TICKS + 0.5)),
Ptime("LocalStop", math.floor(astop * TICKS + 0.5)),
Ptime("ReferenceStart", math.floor(astart * TICKS + 0.5)),
Ptime("ReferenceStop", math.floor(astop * TICKS + 0.5)),
}),
}))
add("AnimationLayer", N("AnimationLayer", "LSS", { lid, cls("BaseLayer", "AnimLayer"), "" }, { N("Properties70", "", {}, {}) }))
OO(lid, stid)
for _, ln in layerNodes do
curveNode(ln[1], ln[2], ln[3], ln[4], ln[5], ln[6], ln[7], ln[8])
end
end
if tmin > tmax then
tmin, tmax = 0, 0
end
-- ------------------------------------------------------------------------------------------ document
local meta = scene.meta or {}
local src = type(meta.source) == "table" and meta.source or {}
local up = if meta.up == "z" then 2 else 1
local upSign, front, frontSign, coord, coordSign = 1, 2, 1, 0, 1
if up == 2 then
front, frontSign = 1, -1
end
if src.format == "fbx" and src.upAxis == up then
upSign = src.upAxisSign or upSign
front, frontSign = src.frontAxis or front, src.frontAxisSign or frontSign
coord, coordSign = src.coordAxis or coord, src.coordAxisSign or coordSign
end
local unitScale = if type(meta.unit) == "number" and meta.unit > 0 then meta.unit * 100 else 1
local creator = opts and opts.creator or "formats-luau"
local defs: { WNode } = { N("Version", "I", { 100 }) }
local total = 1
local CLASSES = { "Model", "Geometry", "Material", "Texture", "Video", "Deformer", "Pose", "NodeAttribute", "AnimationStack", "AnimationLayer", "AnimationCurveNode", "AnimationCurve" }
for _, c in CLASSES do
total += counts[c] or 0
end
table.insert(defs, N("Count", "I", { total }))
table.insert(defs, N("ObjectType", "S", { "GlobalSettings" }, { N("Count", "I", { 1 }) }))
for _, c in CLASSES do
if counts[c] then
table.insert(defs, N("ObjectType", "S", { c }, { N("Count", "I", { counts[c] }) }))
end
end
local docId = id()
local root: WNode = { name = "", props = {}, children = {
N("FBXHeaderExtension", "", {}, {
N("FBXHeaderVersion", "I", { 1003 }),
N("FBXVersion", "I", { opts and opts.version or 7400 }),
N("CreationTimeStamp", "", {}, {
N("Version", "I", { 1000 }), N("Year", "I", { 1970 }), N("Month", "I", { 1 }), N("Day", "I", { 1 }),
N("Hour", "I", { 0 }), N("Minute", "I", { 0 }), N("Second", "I", { 0 }), N("Millisecond", "I", { 0 }),
}),
N("Creator", "S", { creator }),
}),
N("FileId", "R", { buffer.fromstring("(\179*\235\182$\204\194\191\200\176*\169+\252\241") }),
N("CreationTime", "S", { "1970-01-01 10:00:00:000" }),
N("Creator", "S", { creator }),
N("GlobalSettings", "", {}, {
N("Version", "I", { 1000 }),
N("Properties70", "", {}, {
Pint("UpAxis", up), Pint("UpAxisSign", upSign), Pint("FrontAxis", front), Pint("FrontAxisSign", frontSign),
Pint("CoordAxis", coord), Pint("CoordAxisSign", coordSign), Pint("OriginalUpAxis", up), Pint("OriginalUpAxisSign", upSign),
Pdouble("UnitScaleFactor", unitScale), Pdouble("OriginalUnitScaleFactor", unitScale),
P("AmbientColor", "ColorRGB", "Color", "", "DDD", 0, 0, 0),
P("DefaultCamera", "KString", "", "", "S", "Producer Perspective"),
Penum("TimeMode", 6),
Penum("TimeProtocol", 2),
Penum("SnapOnFrameMode", 0),
Ptime("TimeSpanStart", math.floor(tmin * TICKS + 0.5)),
Ptime("TimeSpanStop", math.floor(tmax * TICKS + 0.5)),
Pdouble("CustomFrameRate", -1),
}),
}),
N("Documents", "", {}, {
N("Count", "I", { 1 }),
N("Document", "LSS", { docId, "Scene", "Scene" }, {
N("Properties70", "", {}, { P("SourceObject", "object", "", "", ""), P("ActiveAnimStackName", "KString", "", "", "S", "") }),
N("RootNode", "L", { 0 }),
}),
}),
N("References", "", {}, {}),
N("Definitions", "", {}, defs),
N("Objects", "", {}, objects),
N("Connections", "", {}, conns),
N("Takes", "", {}, { N("Current", "S", { "" }) }),
} }
local _ = Err
return root, nil
end
return Write
+200
View File
@@ -0,0 +1,200 @@
--!strict
-- model/fbx/Xform: the FBX transform model (FBX SDK "Computing transformation matrix"): the local matrix of a Model
-- node T * Roff * Rp * Rpre * R * Rpost^-1 * Rp^-1 * Soff * Sp * S * Sp^-1, Euler rotations in degrees in the six
-- orders, column-major 4x4 matrices (flat arrays of 16, translation at 13..15 as glTF and FBX store them), inverse,
-- TRS decomposition (quaternion x, y, z, w) and Euler XYZ from a quaternion (the writer).
local Xform = {}
export type M4 = { number }
local rad = math.pi / 180
function Xform.identity(): M4
return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
end
function Xform.mul(a: M4, b: M4): M4
local m = table.create(16, 0)
for col = 0, 3 do
for row = 0, 3 do
m[col * 4 + row + 1] = a[row + 1] * b[col * 4 + 1] + a[4 + row + 1] * b[col * 4 + 2] + a[8 + row + 1] * b[col * 4 + 3] + a[12 + row + 1] * b[col * 4 + 4]
end
end
return m
end
function Xform.translate(x: number, y: number, z: number): M4
return { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 }
end
function Xform.scale(x: number, y: number, z: number): M4
return { x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1 }
end
local function rx(a: number): M4
local c, s = math.cos(a), math.sin(a)
return { 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 }
end
local function ry(a: number): M4
local c, s = math.cos(a), math.sin(a)
return { c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 }
end
local function rz(a: number): M4
local c, s = math.cos(a), math.sin(a)
return { c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }
end
-- FBX RotationOrder: 0 XYZ (R = Rz * Ry * Rx: X applied first), 1 XZY, 2 YZX, 3 YXZ, 4 ZXY, 5 ZYX, 6 spheric (= XYZ)
local ORDERS = { [0] = "xyz", "xzy", "yzx", "yxz", "zxy", "zyx", "xyz" }
function Xform.euler(x: number, y: number, z: number, order: number?): M4
local o = ORDERS[order or 0] or "xyz"
local R = { x = rx(x * rad), y = ry(y * rad), z = rz(z * rad) }
local a, b, c = string.sub(o, 1, 1), string.sub(o, 2, 2), string.sub(o, 3, 3)
return Xform.mul(R[c], Xform.mul(R[b], R[a]))
end
-- inverse of an affine matrix (general 3x3 part) | nil when singular
function Xform.inverse(m: M4): M4?
local a, b, c = m[1], m[5], m[9]
local d, e, f = m[2], m[6], m[10]
local g, h, i = m[3], m[7], m[11]
local A, B, C = e * i - f * h, -(d * i - f * g), d * h - e * g
local det = a * A + b * B + c * C
if det == 0 or det ~= det then
return nil
end
local k = 1 / det
local r = {
A * k, B * k, C * k, 0,
-(b * i - c * h) * k, (a * i - c * g) * k, -(a * h - b * g) * k, 0,
(b * f - c * e) * k, -(a * f - c * d) * k, (a * e - b * d) * k, 0,
0, 0, 0, 1,
}
local tx, ty, tz = m[13], m[14], m[15]
r[13] = -(r[1] * tx + r[5] * ty + r[9] * tz)
r[14] = -(r[2] * tx + r[6] * ty + r[10] * tz)
r[15] = -(r[3] * tx + r[7] * ty + r[11] * tz)
return r
end
-- the local matrix of a node from its (already defaulted) FBX properties p: vectors of 3 numbers
export type Props = {
T: { number }, R: { number }, S: { number },
Rpre: { number }, Rpost: { number }, Roff: { number }, Rp: { number }, Soff: { number }, Sp: { number },
order: number,
}
local function isZero(v: { number }): boolean
return v[1] == 0 and v[2] == 0 and v[3] == 0
end
function Xform.localMatrix(p: Props): M4
local m = Xform.translate(p.T[1] + p.Roff[1] + p.Rp[1], p.T[2] + p.Roff[2] + p.Rp[2], p.T[3] + p.Roff[3] + p.Rp[3])
if not isZero(p.Rpre) then
m = Xform.mul(m, Xform.euler(p.Rpre[1], p.Rpre[2], p.Rpre[3], 0))
end
m = Xform.mul(m, Xform.euler(p.R[1], p.R[2], p.R[3], p.order))
if not isZero(p.Rpost) then
local post = Xform.euler(p.Rpost[1], p.Rpost[2], p.Rpost[3], 0)
-- the inverse of a rotation is its transpose
local tr = { post[1], post[5], post[9], 0, post[2], post[6], post[10], 0, post[3], post[7], post[11], 0, 0, 0, 0, 1 }
m = Xform.mul(m, tr)
end
m = Xform.mul(m, Xform.translate(-p.Rp[1] + p.Soff[1] + p.Sp[1], -p.Rp[2] + p.Soff[2] + p.Sp[2], -p.Rp[3] + p.Soff[3] + p.Sp[3]))
m = Xform.mul(m, Xform.scale(p.S[1], p.S[2], p.S[3]))
if not isZero(p.Sp) then
m = Xform.mul(m, Xform.translate(-p.Sp[1], -p.Sp[2], -p.Sp[3]))
end
return m
end
-- quaternion (x, y, z, w) of a pure rotation matrix
local function quat(m: M4): { number }
local m00, m01, m02 = m[1], m[5], m[9]
local m10, m11, m12 = m[2], m[6], m[10]
local m20, m21, m22 = m[3], m[7], m[11]
local tr = m00 + m11 + m22
local x, y, z, w
if tr > 0 then
local s = math.sqrt(tr + 1) * 2
w, x, y, z = s / 4, (m21 - m12) / s, (m02 - m20) / s, (m10 - m01) / s
elseif m00 > m11 and m00 > m22 then
local s = math.sqrt(math.max(1 + m00 - m11 - m22, 1e-30)) * 2
w, x, y, z = (m21 - m12) / s, s / 4, (m01 + m10) / s, (m02 + m20) / s
elseif m11 > m22 then
local s = math.sqrt(math.max(1 + m11 - m00 - m22, 1e-30)) * 2
w, x, y, z = (m02 - m20) / s, (m01 + m10) / s, s / 4, (m12 + m21) / s
else
local s = math.sqrt(math.max(1 + m22 - m00 - m11, 1e-30)) * 2
w, x, y, z = (m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, s / 4
end
local n = math.sqrt(x * x + y * y + z * z + w * w)
if n == 0 or n ~= n then
return { 0, 0, 0, 1 }
end
return { x / n, y / n, z / n, w / n }
end
Xform.quat = quat
-- decompose(m) -> translation, rotation (quaternion), scale (a negative determinant flips the x scale)
function Xform.decompose(m: M4): ({ number }, { number }, { number })
local t = { m[13], m[14], m[15] }
local sx = math.sqrt(m[1] * m[1] + m[2] * m[2] + m[3] * m[3])
local sy = math.sqrt(m[5] * m[5] + m[6] * m[6] + m[7] * m[7])
local sz = math.sqrt(m[9] * m[9] + m[10] * m[10] + m[11] * m[11])
local det = m[1] * (m[6] * m[11] - m[10] * m[7]) - m[5] * (m[2] * m[11] - m[10] * m[3]) + m[9] * (m[2] * m[7] - m[6] * m[3])
if det < 0 then
sx = -sx
end
local ix = if sx ~= 0 then 1 / sx else 0
local iy = if sy ~= 0 then 1 / sy else 0
local iz = if sz ~= 0 then 1 / sz else 0
local r = { m[1] * ix, m[2] * ix, m[3] * ix, 0, m[5] * iy, m[6] * iy, m[7] * iy, 0, m[9] * iz, m[10] * iz, m[11] * iz, 0, 0, 0, 0, 1 }
return t, quat(r), { sx, sy, sz }
end
-- the rotation matrix of a quaternion
function Xform.fromQuat(q: { number }): M4
local x, y, z, w = q[1], q[2], q[3], q[4]
local xx, yy, zz, xy, xz, yz, wx, wy, wz = x * x, y * y, z * z, x * y, x * z, y * z, w * x, w * y, w * z
return {
1 - 2 * (yy + zz), 2 * (xy + wz), 2 * (xz - wy), 0,
2 * (xy - wz), 1 - 2 * (xx + zz), 2 * (yz + wx), 0,
2 * (xz + wy), 2 * (yz - wx), 1 - 2 * (xx + yy), 0,
0, 0, 0, 1,
}
end
-- Euler XYZ degrees (R = Rz * Ry * Rx) of a quaternion
function Xform.eulerXYZ(q: { number }): { number }
local m = Xform.fromQuat(q)
-- m[3] = r20 = -sin(y)
local sy = -m[3]
sy = math.clamp(sy, -1, 1)
local y = math.asin(sy)
local x, z
if math.abs(sy) < 0.9999999 then
x = math.atan2(m[7], m[11])
z = math.atan2(m[2], m[1])
else
x = math.atan2(-m[10], m[6])
z = 0
end
return { x / rad, y / rad, z / rad }
end
-- TRS -> matrix (glTF semantics)
function Xform.compose(t: { number }?, r: { number }?, s: { number }?): M4
local m = if r then Xform.fromQuat(r) else Xform.identity()
if s then
for k = 0, 2 do
m[k * 4 + 1] *= s[k + 1]
m[k * 4 + 2] *= s[k + 1]
m[k * 4 + 3] *= s[k + 1]
end
end
if t then
m[13], m[14], m[15] = t[1], t[2], t[3]
end
return m
end
return Xform
+177
View File
@@ -0,0 +1,177 @@
--!strict
-- model/fbx: Autodesk FBX 7.x, binary (7.0 - 7.7: 32-bit records before 7500, 64-bit after; zlib-compressed arrays
-- through codecs/Deflate) and ASCII. New code, from the format as reverse engineered by Blender's io_scene_fbx and
-- assimp's FBX importer, and the FBX SDK's documentation of the transform model.
-- Reads: the node tree (Fbx.tree), then Objects / Connections -> Scene: Model nodes with the full transform (Lcl
-- T / R / S, pre / post rotation, rotation / scaling pivots and offsets, the six rotation orders; geometric transforms
-- baked into the mesh), meshes (polygons fan-triangulated by default or kept as "polygons"; layer elements for normals,
-- tangents, uvs (TEXCOORD_n, flipped to glTF's top-left origin), colours and materials in every mapping and reference
-- mode), Phong / Lambert materials (-> PBR approximations + the Phong values in extras.fbx) and 3ds Max Physical PBR
-- materials, textures (embedded Video content kept encoded, or the file through opts.resolve / opts.files), skins
-- (clusters -> JOINTS_0 / WEIGHTS_0, the 4 strongest influences, inverse bind matrices), blend shapes (morph targets
-- + weights), animation stacks (curves on T / R / S and DeformPercent sampled at their keys, or opts.sampleRate, and
-- turned into glTF translation / rotation / scale / weights channels), cameras and lights (on child nodes oriented for
-- glTF's -Z forward axis), the axis system and unit (meta.up, meta.unit = UnitScaleFactor / 100; nothing is rotated).
-- Writes binary FBX 7.4 (or ASCII with opts.ascii): the node hierarchy, meshes (one Geometry per mesh, its primitives
-- as material slots; normals, uvs, colours), Phong materials (extras.fbx when present, else from the PBR fields),
-- textures (embedded as Video content when texture.data is set, else a file reference), skins (Skin / Cluster +
-- BindPose), morph targets (BlendShape channels) and animations (one stack per animation; rotation channels as Euler
-- XYZ curves; arrays zlib-compressed unless opts.compress = false). Checked with assimp and Blender (not the FBX SDK).
-- Not supported: FBX 6.x and older (UNSUPPORTED), NURBS / patch / line geometry (skipped), constraints, layered
-- animation blending (the first layer that animates a property wins), cubic curve tangents on write (keys are linear).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Binary = require("@formats/model/fbx/Binary")
local Ascii = require("@formats/model/fbx/Ascii")
local Read = require("@formats/model/fbx/Read")
local Write = require("@formats/model/fbx/Write")
-- ------------------------------------------------------------------------------------------------ contract
local Fbx = {
name = "fbx",
category = "model",
extensions = { "fbx" },
mime = { "application/vnd.autodesk.fbx", "model/fbx" },
deps = { "core/Err", "core/Bytes", "Types", "codecs/Deflate", "core/Base64" },
caps = { decode = true, encode = true, binary = true, ascii = true, materials = true, animation = true, skins = true, morphTargets = true, cameras = true, lights = true, polygons = true },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
triangulate: boolean?, -- fan-triangulate polygons (default true); false keeps "polygons" primitives
flipV: boolean?, -- TEXCOORD_n.v = 1 - v (default true: glTF's convention)
sampleRate: number?, -- also sample animation curves at this many samples per second (default: their keys only)
resolve: ((uri: string) -> any)?, -- external texture files (the api sets it for paths)
files: { [string]: any }?, -- or: the files by name
maxBytes: number?, -- refuse arrays over this many bytes in total (default 2^30)
maxVertices: number?, -- refuse more polygon corners (default 2^25)
}
export type EncodeOptions = {
ascii: boolean?, -- write ASCII FBX (default binary)
version: number?, -- 7400 (default) or 7500 (64-bit records)
flipV: boolean?, -- default true (the inverse of decode)
embedTextures: boolean?, -- embed texture.data as Video content (default true)
compress: boolean?, -- zlib-compress arrays over 32 elements (default true; false writes ~3x faster, ~2x bigger)
name: string?, -- the destination's file name (names textures without a uri)
creator: string?,
}
-- ------------------------------------------------------------------------------------------------ constants
local MAGIC = Binary.MAGIC
-- ------------------------------------------------------------------------------------------------ sniff
function Fbx.sniff(r: Bytes.Reader): number
if r:peek(21) == MAGIC then
return 1
end
local head = r:peek(2048)
if string.find(head, "FBXHeaderExtension:", 1, true) then
return 0.95
end
if string.find(head, "^; FBX %d") then
return 0.8
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 v: any = nil
if type(opts.files) == "table" then
v = opts.files[uri]
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 toErr(msg: any, offset: number?): Err.Err
local s = tostring(msg)
local code = Err.CORRUPT
if string.sub(s, 1, 12) == "unsupported:" then
code, s = Err.UNSUPPORTED, string.sub(s, 13)
elseif string.sub(s, 1, 6) == "limit:" then
code, s = Err.LIMIT, string.sub(s, 7)
elseif string.find(s, "truncated", 1, true) or string.find(s, "runs past", 1, true) then
code = Err.TRUNCATED
end
return Err.new(code, s, offset)
end
-- tree(r, opts?) -> the node tree { name = "", children = { { name, props, children } } }, version, binary | nil, Err.
-- Property values: numbers, booleans, strings, buffers (raw), Arrays { array = true, type, count, data = f64 buffer }.
function Fbx.tree(r: Bytes.Reader, opts: DecodeOptions?): (any, any, boolean?)
if r:peek(21) == MAGIC then
local root, version, off = Binary.parse(r.buf, r.base, r.limit, opts)
if not root then
return nil, toErr(version, off)
end
return root, version, true
end
local text = buffer.readstring(r.buf, r.base, r.limit - r.base)
local root, version, off = Ascii.parse(text, opts)
if not root then
return nil, toErr(version, off and r.base + off)
end
if type(version) ~= "number" then
return nil, Err.new(Err.CORRUPT, "no FBXHeaderExtension / FBXVersion")
end
if version < 7000 then
return nil, Err.new(Err.UNSUPPORTED, "FBX version " .. version .. " (only 7.x)")
end
return root, version, false
end
function Fbx.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local root, version, binary = Fbx.tree(r, opts)
if not root then
return nil, version
end
-- the scene builder is plain (not native) code: a bug there must not escape as an error
local ok, scene, err = pcall(Read.scene, root, version, fetcher(opts), opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "bad object graph: " .. tostring(scene))
end
if not scene then
return nil, err
end
scene.meta.source.binary = binary
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Fbx.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 version = opts and opts.version or 7400
if version ~= 7400 and version ~= 7500 then
return nil, Err.new(Err.ARG, "version must be 7400 or 7500")
end
local ok, root, err = pcall(Write.tree, scene, opts)
if not ok then
return nil, Err.new(Err.ARG, "bad scene: " .. tostring(root))
end
if not root then
return nil, err
end
if opts and opts.ascii then
return buffer.fromstring(Ascii.write(root, version)), nil
end
return Binary.write(root, version, not (opts and opts.compress == false)), nil
end
return Fbx
File diff suppressed because it is too large. Load diff
+820
View File
@@ -0,0 +1,820 @@
--!strict
-- model/usda/Parse: USD ASCII (Sdf text format, "#usda 1.0") -> a layer of prim specs. New code, from the Sdf text
-- grammar as Pixar's USD writes and reads it: layer metadata, def / over / class prims with metadata, attributes
-- (custom / uniform / varying / config, scalar and array types, defaults, .timeSamples, .connect, metadata), relationships,
-- list ops (prepend / append / add / delete / reorder), variant sets, dictionaries, strings ("", '', triple quoted),
-- asset paths (@...@, @@@...@@@), paths (<...>), comments (#, //, /* */). Numeric arrays (points, indices) take a fast
-- path into flat number arrays. .spline blocks and unknown constructs are skipped by bracket matching.
-- Errors raise a table { usda = message, at = byte offset } inside this module; Parse.layer catches them (pcall) and
-- returns nil, message, offset - nothing escapes.
local Parse = {}
-- values: numbers, booleans, strings, and these tagged tables
export type Arr = { t: "arr", w: number, v: { number } } -- numeric array, w numbers per element (tuples flattened)
export type Value = any
export type Prop = {
name: string,
rel: boolean, -- a relationship
typeName: string?, -- "point3f", "token", ... (attributes)
array: boolean?,
uniform: boolean?,
custom: boolean?,
value: Value?, -- the default value (attributes) or the targets (relationships: { path strings })
hasValue: boolean?,
samples: { times: { number }, values: { Value } }?,
connect: { string }?, -- connection target paths (attributes)
meta: { [string]: Value }?,
}
export type Prim = {
specifier: string, -- "def" | "over" | "class"
typeName: string?,
name: string,
meta: { [string]: Value },
props: { [string]: Prop },
order: { string }, -- property names in file order
children: { Prim },
variantSets: { [string]: { [string]: Prim } }?, -- set -> variant -> a prim body (props / children)
}
export type Layer = { meta: { [string]: Value }, prims: { Prim } }
local NONE = table.freeze({ t = "none" })
Parse.NONE = NONE
local sfind, ssub, sbyte, smatch, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch
local LISTOPS = { prepend = true, append = true, add = true, delete = true, reorder = true }
local VARIABILITY = { uniform = true, varying = true, config = true }
local MAX_DEPTH = 200
local function fail(msg: string, at: number): never
error({ usda = msg, at = at }, 0)
end
-- the parser over one text; positions are 1-based string indices
local function parser(s: string, maxBytes: number)
local n = #s
local depth = 0
-- whitespace and comments (newlines included)
local function ws(i: number): number
while true do
local _, e = sfind(s, "^[ \t\r\n]+", i)
if e then
i = e + 1
end
local c = sbyte(s, i)
if c == 35 then -- #
local nl = sfind(s, "\n", i, true)
i = if nl then nl + 1 else n + 1
elseif c == 47 and sbyte(s, i + 1) == 47 then -- //
local nl = sfind(s, "\n", i, true)
i = if nl then nl + 1 else n + 1
elseif c == 47 and sbyte(s, i + 1) == 42 then -- /* */
local _, ce = sfind(s, "*/", i + 2, true)
if not ce then
fail("unterminated comment", i)
end
i = (ce :: number) + 1
else
return i
end
end
end
local function expect(i: number, ch: string): number
i = ws(i)
if ssub(s, i, i) ~= ch then
fail("expected '" .. ch .. "'", i)
end
return i + 1
end
local function ident(i: number): (string?, number)
local a, e = sfind(s, "^[%a_][%w_:]*", i)
if not a then
return nil, i
end
return ssub(s, a, e), (e :: number) + 1
end
local ESC = { n = "\n", t = "\t", r = "\r", ["\\"] = "\\", ['"'] = '"', ["'"] = "'", ["0"] = "\0", a = "\a", b = "\b", f = "\f", v = "\v" }
local function unescape(str: string): string
if not sfind(str, "\\", 1, true) then
return str
end
return (string.gsub(str, "\\(x?)(.)", function(x: string, c: string): string
if x == "x" then
return "\\x" .. c -- left alone (rare)
end
return ESC[c] or c
end))
end
local function str(i: number): (string, number)
local q = ssub(s, i, i)
if ssub(s, i, i + 2) == q .. q .. q then
local e = sfind(s, q .. q .. q, i + 3, true)
if not e then
fail("unterminated string", i)
end
return unescape(ssub(s, i + 3, (e :: number) - 1)), (e :: number) + 3
end
local j = i + 1
while true do
local a = sfind(s, "[\\\n" .. q .. "]", j)
if not a then
fail("unterminated string", i)
end
local c = sbyte(s, a :: number)
if c == 92 then
j = (a :: number) + 2
elseif c == 10 then
fail("newline in string", a :: number)
else
return unescape(ssub(s, i + 1, (a :: number) - 1)), (a :: number) + 1
end
end
end
local function number(i: number): (number?, number)
local a, e = sfind(s, "^[-+]?%d*%.?%d*[eE][-+]?%d+", i)
if not a then
a, e = sfind(s, "^[-+]?%d*%.?%d*", i)
end
if a and (e :: number) >= (a :: number) then
local v = tonumber(ssub(s, a, e))
if v then
return v, (e :: number) + 1
end
end
-- inf / -inf / nan
local w, e2 = sfind(s, "^[-+]?%a+", i)
if w then
local word = string.lower(ssub(s, w, e2))
if word == "inf" or word == "+inf" then
return math.huge, (e2 :: number) + 1
elseif word == "-inf" then
return -math.huge, (e2 :: number) + 1
elseif word == "nan" or word == "-nan" or word == "+nan" then
return 0 / 0, (e2 :: number) + 1
end
end
return nil, i
end
-- skip a balanced (), [], {} block starting at i (strings and comments respected)
local function skipBalanced(i: number): number
local open = sbyte(s, i)
local level = 0
while i <= n do
i = ws(i)
local c = sbyte(s, i)
if c == nil then
break
end
if c == 40 or c == 91 or c == 123 then
level += 1
i += 1
elseif c == 41 or c == 93 or c == 125 then
level -= 1
i += 1
if level == 0 then
return i
end
elseif c == 34 or c == 39 then
local _, j = str(i)
i = j
elseif c == 64 then
local e = sfind(s, "@", i + 1, true)
i = if e then e + 1 else n + 1
elseif c == 60 then
local e = sfind(s, ">", i + 1, true)
i = if e then e + 1 else n + 1
else
local _, e = sfind(s, "^[^%(%)%[%]{}\"'@<#/ \t\r\n]+", i)
i = if e then e + 1 else i + 1
end
end
fail("unbalanced " .. string.char(open or 63), i)
end
local value: (i: number) -> (Value, number)
local metadata: (i: number) -> ({ [string]: Value }, number)
-- [ ... ]: the fast path for numeric arrays (flat numbers + tuple width), else a generic list
local function list(i: number): (Value, number)
local close = sfind(s, "]", i + 1, true)
if close then
local body = ssub(s, i + 1, close - 1)
if not sfind(body, "[^%d%s%.,eE%-%+%(%)]") then
local first = smatch(body, "^%s*%(([^%)]*)%)")
local w = 1
if first then
w = 0
for _ in gmatch(first, "[^%s,]+") do
w += 1
end
elseif sfind(body, "[%(%)]") then
w = -1 -- nested tuples: the generic path
end
if w > 0 then
local out: { number } = {}
local k = 0
local ok = true
for tok in gmatch(body, "[^%s,%(%)]+") do
local v = tonumber(tok)
if not v then
ok = false
break
end
k += 1
out[k] = v
end
if ok and k % w == 0 then
if k * 8 > maxBytes then
fail("array over the size limit", i)
end
return { t = "arr", w = w, v = out } :: Arr, close + 1
end
end
end
end
-- generic
local items = {}
i += 1
while true do
i = ws(i)
local c = ssub(s, i, i)
if c == "]" then
i += 1
break
elseif c == "" then
fail("unterminated list", i)
end
local v
v, i = value(i)
table.insert(items, v)
i = ws(i)
if ssub(s, i, i) == "(" then -- per-item metadata (subLayers offsets, ...)
local _
_, i = metadata(i)
i = ws(i)
end
c = ssub(s, i, i)
if c == "," then
i += 1
elseif c ~= "]" then
fail("expected ',' or ']' in a list", i)
end
end
-- all numbers, or all equal-width numeric tuples -> arr
local w: number? = nil
local flat: { number } = {}
for _, it in items do
if type(it) == "number" then
if w and w ~= 1 then
return { t = "list", v = items }, i
end
w = 1
table.insert(flat, it)
elseif type(it) == "table" and it.t == "tuple" then
local tw = #it.v
if (w and w ~= tw) or tw == 0 then
return { t = "list", v = items }, i
end
w = tw
for _, x in it.v do
if type(x) ~= "number" then
return { t = "list", v = items }, i
end
table.insert(flat, x)
end
else
return { t = "list", v = items }, i
end
end
if w == nil then
return { t = "list", v = items }, i
end
return { t = "arr", w = w, v = flat } :: Arr, i
end
local function tuple(i: number): (Value, number)
local items = {}
i += 1
while true do
i = ws(i)
local c = ssub(s, i, i)
if c == ")" then
i += 1
break
elseif c == "" then
fail("unterminated tuple", i)
end
local v
v, i = value(i)
table.insert(items, v)
i = ws(i)
c = ssub(s, i, i)
if c == "," then
i += 1
elseif c ~= ")" then
fail("expected ',' or ')' in a tuple", i)
end
end
return { t = "tuple", v = items }, i
end
-- { type key = value ... } (metadata dictionaries)
local function dict(i: number): (Value, number)
local out: { [string]: Value } = {}
i += 1
while true do
i = ws(i)
local c = ssub(s, i, i)
if c == "}" then
i += 1
break
elseif c == "" then
fail("unterminated dictionary", i)
elseif c == ";" or c == "," then
i += 1
continue
end
local ty
ty, i = ident(i)
if not ty then
fail("expected a type in a dictionary", i)
end
i = ws(i)
if ssub(s, i, i + 1) == "[]" then
i += 2
end
i = ws(i)
local key: string?
c = ssub(s, i, i)
if c == '"' or c == "'" then
key, i = str(i)
else
key, i = ident(i)
end
if not key then
fail("expected a key in a dictionary", i)
end
i = expect(i, "=")
local v
v, i = value(i)
out[key :: string] = v
end
return { t = "dict", v = out }, i
end
function value(i: number): (Value, number)
depth += 1
if depth > MAX_DEPTH then
fail("nesting too deep", i)
end
i = ws(i)
local c = ssub(s, i, i)
local v: Value
if c == "[" then
v, i = list(i)
elseif c == "(" then
v, i = tuple(i)
elseif c == "{" then
v, i = dict(i)
elseif c == '"' or c == "'" then
v, i = str(i)
elseif c == "@" then
local path
if ssub(s, i, i + 2) == "@@@" then
local e = sfind(s, "@@@", i + 3, true)
if not e then
fail("unterminated asset path", i)
end
path, i = ssub(s, i + 3, (e :: number) - 1), (e :: number) + 3
else
local e = sfind(s, "@", i + 1, true)
if not e then
fail("unterminated asset path", i)
end
path, i = ssub(s, i + 1, (e :: number) - 1), (e :: number) + 1
end
local a: { [string]: any } = { t = "asset", v = path }
local j = ws(i)
if ssub(s, j, j) == "<" then -- references = @file@</prim>
local e = sfind(s, ">", j + 1, true)
if not e then
fail("unterminated path", j)
end
a.path = ssub(s, j + 1, (e :: number) - 1)
i = (e :: number) + 1
end
v = a
elseif c == "<" then
local e = sfind(s, ">", i + 1, true)
if not e then
fail("unterminated path", i)
end
v, i = { t = "path", v = ssub(s, i + 1, (e :: number) - 1) }, (e :: number) + 1
else
local num, j = number(i)
if num ~= nil then
v, i = num, j
else
local id
id, j = ident(i)
if not id then
fail("expected a value", i)
end
i = j
if id == "None" then
v = NONE
elseif id == "true" then
v = true
elseif id == "false" then
v = false
else
v = { t = "id", v = id }
end
end
end
depth -= 1
return v, i
end
-- ( key = value ; "doc" ; prepend key = value ... )
function metadata(i: number): ({ [string]: Value }, number)
local out: { [string]: Value } = {}
i = expect(i, "(")
while true do
i = ws(i)
local c = ssub(s, i, i)
if c == ")" then
return out, i + 1
elseif c == "" then
fail("unterminated metadata", i)
elseif c == ";" or c == "," then
i += 1
continue
elseif c == '"' or c == "'" then
out.doc, i = str(i)
continue
end
local key
key, i = ident(i)
if not key then
fail("expected a metadata key", i)
end
local op: string? = nil
if LISTOPS[key] then
op = key
i = ws(i)
key, i = ident(i)
if not key then
fail("expected a metadata key", i)
end
end
i = ws(i)
if ssub(s, i, i) == "=" then
local v
v, i = value(i + 1)
if op == "delete" then
-- deletions only matter for composition
elseif op and op ~= "reorder" then
-- prepend / append / add: merge into one list
local prev = out[key :: string]
if type(prev) == "table" and prev.t == "list" and type(v) == "table" and v.t == "list" then
for _, x in v.v do
table.insert(prev.v, x)
end
else
out[key :: string] = v
end
else
out[key :: string] = v
end
end
end
end
-- time samples: { time: value, ... }
local function samples(i: number): ({ times: { number }, values: { Value } }, number)
local times, values = {}, {}
i = expect(i, "{")
while true do
i = ws(i)
local c = ssub(s, i, i)
if c == "}" then
i += 1
break
elseif c == "" then
fail("unterminated time samples", i)
elseif c == "," then
i += 1
continue
end
local t
t, i = number(i)
if t == nil then
fail("expected a time code", i)
end
i = expect(i, ":")
local v
v, i = value(i)
table.insert(times, t)
table.insert(values, v)
end
return { times = times, values = values }, i
end
local function targets(v: Value): { string }
local out = {}
if type(v) == "table" then
if v.t == "path" then
table.insert(out, v.v)
elseif v.t == "list" then
for _, x in v.v do
if type(x) == "table" and x.t == "path" then
table.insert(out, x.v)
end
end
end
end
return out
end
local primBody: (i: number, prim: Prim) -> number
local function newPrim(specifier: string, typeName: string?, name: string): Prim
return { specifier = specifier, typeName = typeName, name = name, meta = {}, props = {}, order = {}, children = {} }
end
-- def Type "name" ( meta ) { body }
local function prim(i: number, specifier: string): (Prim, number)
i = ws(i)
local typeName: string? = nil
local c = ssub(s, i, i)
if c ~= '"' and c ~= "'" then
typeName, i = ident(i)
if not typeName then
fail("expected a prim type or name", i)
end
i = ws(i)
-- dotted schema names (rare)
while ssub(s, i, i) == "." do
local more
more, i = ident(i + 1)
typeName = (typeName :: string) .. "." .. (more or "")
end
i = ws(i)
end
c = ssub(s, i, i)
if c ~= '"' and c ~= "'" then
fail("expected a prim name", i)
end
local name
name, i = str(i)
local p = newPrim(specifier, typeName, name)
i = ws(i)
if ssub(s, i, i) == "(" then
p.meta, i = metadata(i)
end
i = expect(i, "{")
i = primBody(i, p)
return p, i
end
-- variantSet "name" = { "variant" ( meta ) { body } ... }
local function variantSet(i: number, p: Prim): number
i = ws(i)
local setName
setName, i = str(i)
i = expect(i, "=")
i = expect(i, "{")
local sets = p.variantSets or {}
p.variantSets = sets
local set = sets[setName] or {}
sets[setName] = set
while true do
i = ws(i)
local c = ssub(s, i, i)
if c == "}" then
return i + 1
elseif c ~= '"' and c ~= "'" then
fail("expected a variant name", i)
end
local vname
vname, i = str(i)
local body = newPrim("def", nil, vname)
i = ws(i)
if ssub(s, i, i) == "(" then
body.meta, i = metadata(i)
end
i = expect(i, "{")
i = primBody(i, body)
set[vname] = body
end
end
-- one property: [listop] [custom] [uniform|varying|config] (rel name | type[] name)[.connect|.timeSamples|...]
local function property(i: number, first: string, p: Prim): number
local word: string? = first
local op: string? = nil
if LISTOPS[word :: string] then
op = word
i = ws(i)
word, i = ident(i)
end
local custom, uniform = false, false
if word == "custom" then
custom = true
i = ws(i)
word, i = ident(i)
end
if word and VARIABILITY[word] then
uniform = word == "uniform"
i = ws(i)
word, i = ident(i)
end
if not word then
fail("expected a property", i)
end
local isRel = word == "rel"
local typeName: string? = nil
local array = false
if not isRel then
typeName = word
i = ws(i)
if ssub(s, i, i + 1) == "[]" then
array = true
i += 2
end
end
i = ws(i)
local name
name, i = ident(i)
if not name then
fail("expected a property name", i)
end
local suffix: string? = nil
if ssub(s, i, i) == "." then
suffix, i = ident(i + 1)
end
local prop = p.props[name :: string]
if not prop then
prop = { name = name :: string, rel = isRel }
p.props[name :: string] = prop
table.insert(p.order, name :: string)
end
local pr = prop :: Prop
if typeName then
pr.typeName, pr.array = typeName, array
end
pr.uniform = pr.uniform or uniform or nil
pr.custom = pr.custom or custom or nil
i = ws(i)
if ssub(s, i, i) == "=" then
i = ws(i + 1)
if suffix == "timeSamples" then
pr.samples, i = samples(i)
elseif suffix == "spline" or (suffix ~= nil and suffix ~= "connect" and suffix ~= "default" and ssub(s, i, i) == "{") then
i = skipBalanced(i)
else
local v
v, i = value(i)
if op == "delete" then
-- composition only
elseif suffix == "connect" then
pr.connect = targets(v)
elseif isRel then
pr.value = targets(v)
pr.hasValue = true
else
pr.value = v
pr.hasValue = true
end
end
end
i = ws(i)
if ssub(s, i, i) == "(" then
local m
m, i = metadata(i)
if pr.meta then
for k, v in m do
(pr.meta :: any)[k] = v
end
else
pr.meta = m
end
end
return i
end
function primBody(i: number, p: Prim): number
depth += 1
if depth > MAX_DEPTH then
fail("nesting too deep", i)
end
while true do
i = ws(i)
local c = ssub(s, i, i)
if c == "}" then
depth -= 1
return i + 1
elseif c == "" then
fail("unterminated prim", i)
elseif c == ";" then
i += 1
continue
end
local word, j = ident(i)
if not word then
fail("unexpected character in a prim", i)
end
if word == "def" or word == "over" or word == "class" then
local child
child, i = prim(j, word)
table.insert(p.children, child)
elseif word == "variantSet" then
i = variantSet(j, p)
elseif word == "reorder" then
local k = ws(j)
local w2, k2 = ident(k)
if w2 == "nameChildren" or w2 == "properties" or w2 == "rootPrims" then
k2 = expect(k2, "=")
local _
_, i = value(k2)
else
i = property(j, word, p)
end
else
i = property(j, word, p)
end
end
end
-- the whole layer
local function layer(): Layer
local i = 1
if ssub(s, 1, 3) == "\239\187\191" then
i = 4
end
if ssub(s, i, i + 4) ~= "#usda" then
fail("not a USDA file (no #usda header)", i)
end
local nl = sfind(s, "\n", i, true)
i = if nl then nl + 1 else n + 1
local out: Layer = { meta = {}, prims = {} }
i = ws(i)
if ssub(s, i, i) == "(" then
out.meta, i = metadata(i)
end
while true do
i = ws(i)
if i > n then
break
end
local word, j = ident(i)
if word == "def" or word == "over" or word == "class" then
local p
p, i = prim(j, word)
table.insert(out.prims, p)
elseif word == "reorder" then
j = ws(j)
local _
_, j = ident(j)
j = expect(j, "=")
_, i = value(j)
elseif ssub(s, i, i) == ";" then
i += 1
else
fail("expected def / over / class", i)
end
end
return out
end
return layer
end
-- layer(text, opts?) -> Layer | nil, message, offset (0-based)
function Parse.layer(text: string, maxBytes: number?): (Layer?, string?, number?)
local run = parser(text, maxBytes or 2 ^ 30)
local ok, res = pcall(run)
if ok then
return res, nil, nil
end
if type(res) == "table" and res.usda then
return nil, res.usda, math.max((res.at or 1) - 1, 0)
end
return nil, "parse error: " .. tostring(res), nil
end
-- version(text) -> the "#usda <version>" string
function Parse.version(text: string): string?
return smatch(text, "^\239?\187?\191?#usda%s+([%d%.]+)")
end
return Parse
+840
View File
@@ -0,0 +1,840 @@
--!strict
-- model/usda/Write: Scene -> USD ASCII text (UsdGeom / UsdShade / UsdLux). New code.
-- Layout: one root prim (the scene's single root node, else an Xform "root" holding every root) as the defaultPrim,
-- a "Looks" scope under it with the materials (UsdPreviewSurface + UsdUVTexture + UsdPrimvarReader_float2, texture
-- transforms as UsdTransform2d), and one prim per node: a node with a mesh is a Mesh prim (its primitives merged, a
-- GeomSubset per primitive when there are several), a node with only a camera / light is that Camera / light prim,
-- other nodes are Xforms (meshes / cameras / lights that cannot share the node's prim become children). Transforms are
-- translate / orient / scale ops (or a transform op for matrices); animation channels (translation / rotation / scale)
-- become time samples on those ops (timeCodesPerSecond 24). TEXCOORD_n -> primvars:st, st1, ... (v flipped back),
-- COLOR_0 -> displayColor (+ displayOpacity), NORMAL -> normals, all "vertex" interpolated. Textures: their uri, or the
-- embedded bytes written into opts.files as <name>_<n>.<ext>. Not written: skins, morph targets, weights animation,
-- lines / points primitives (counted in the returned notes).
local Types = require("@formats/Types")
local Write = {}
local EXT = { ["image/png"] = "png", ["image/jpeg"] = "jpg", ["image/webp"] = "webp", ["image/ktx2"] = "ktx2", ["image/avif"] = "avif", ["image/bmp"] = "bmp", ["image/x-tga"] = "tga", ["image/gif"] = "gif", ["image/tiff"] = "tiff" }
local RAD = 180 / math.pi
export type Options = { files: { [string]: any }?, name: string?, upAxis: string?, metersPerUnit: number? }
-- ------------------------------------------------------------------------------------------------ text helpers
local function fmt(x: number): string
if x ~= x then
return "nan"
elseif x == math.huge then
return "inf"
elseif x == -math.huge then
return "-inf"
elseif x == math.floor(x) and math.abs(x) < 1e15 then
return string.format("%d", x)
end
return string.format("%.9g", x)
end
local function tuple(t: { number }): string
local parts = table.create(#t)
for k, v in t do
parts[k] = fmt(v)
end
return "(" .. table.concat(parts, ", ") .. ")"
end
local function quote(s: string): string
return '"' .. string.gsub(s, '[\\"\n]', { ["\\"] = "\\\\", ['"'] = '\\"', ["\n"] = "\\n" }) .. '"'
end
local function asset(s: string): string
if string.find(s, "@", 1, true) then
return "@@@" .. s .. "@@@"
end
return "@" .. s .. "@"
end
-- a valid, sibling-unique prim name
local function namer(): (string?, string) -> string
local used: { [string]: boolean } = {}
return function(name: string?, fallback: string): string
local n = string.gsub(name or "", "[^%w_]", "_")
if n == "" then
n = fallback
end
if string.find(n, "^%d") then
n = "_" .. n
end
local base, k = n, 1
while used[n] do
k += 1
n = base .. "_" .. k
end
used[n] = true
return n
end
end
-- an accessor's elements as numbers (normalized types to floats)
local function values(acc: Types.Accessor?): ({ number }?, number)
if not acc then
return nil, 0
end
local get = Types.Scene.reader(acc)
if not get then
return nil, 0
end
local n, c = acc.count, acc.components
local out = table.create(n * c)
for i = 0, n - 1 do
for k = 0, c - 1 do
out[i * c + k + 1] = get(i, k)
end
end
return out, c
end
-- array literal of tuples ("[(x, y, z), ...]") or scalars
local function arrayText(vals: { number }, width: number, stride: number?, count: number?, map: ((i: number, k: number, v: number) -> number)?): string
local st = stride or width
local n = count or (#vals // st)
local parts = table.create(n)
local buf = table.create(width)
for i = 0, n - 1 do
for k = 1, width do
local v = vals[i * st + k] or 0
if map then
v = map(i, k, v)
end
buf[k] = fmt(v)
end
parts[i + 1] = if width == 1 then buf[1] else "(" .. table.concat(buf, ", ", 1, width) .. ")"
end
return "[" .. table.concat(parts, ", ") .. "]"
end
-- ------------------------------------------------------------------------------------------------ primitives
type Merged = {
points: { number },
counts: { number },
indices: { number },
normals: { number }?,
uvs: { [number]: { number } },
colors: { number }?, -- rgba
hasAlpha: boolean,
subsets: { { faces: { number }, material: number? } },
}
-- the triangles / polygons of a primitive as (counts, corner indices into its vertices); nil for lines / points
local function faces(p: Types.Primitive, nverts: number): ({ number }?, { number }?)
local idx: { number }
if p.indices then
idx = (values(p.indices)) or {}
else
idx = table.create(nverts)
for i = 1, nverts do
idx[i] = i - 1
end
end
local counts, out = {}, {}
local mode = p.mode
if mode == "triangles" or mode == nil then
for k = 1, #idx - 2, 3 do
table.insert(counts, 3)
table.insert(out, idx[k])
table.insert(out, idx[k + 1])
table.insert(out, idx[k + 2])
end
elseif mode == "polygons" then
local fs = (values(p.faces)) or {}
local at = 1
for _, n in fs do
if at + n - 1 > #idx then
break
end
table.insert(counts, n)
for k = at, at + n - 1 do
table.insert(out, idx[k])
end
at += n
end
elseif mode == "triangle_strip" then
for k = 1, #idx - 2 do
local a, b, c = idx[k], idx[k + 1], idx[k + 2]
if k % 2 == 0 then
a, b = b, a
end
table.insert(counts, 3)
table.insert(out, a)
table.insert(out, b)
table.insert(out, c)
end
elseif mode == "triangle_fan" then
for k = 2, #idx - 1 do
table.insert(counts, 3)
table.insert(out, idx[1])
table.insert(out, idx[k])
table.insert(out, idx[k + 1])
end
else
return nil, nil
end
return counts, out
end
-- the primitives of a mesh merged into one USD mesh (GeomSubsets per primitive); nil when nothing is writable
local function merge(mesh: Types.Mesh, notes: { [string]: number }): Merged?
local prims: { Types.Primitive } = {}
for _, p in mesh.primitives do
if p.attributes and p.attributes.POSITION and p.attributes.POSITION.components == 3 and p.mode ~= "lines" and p.mode ~= "line_strip" and p.mode ~= "line_loop" and p.mode ~= "points" then
table.insert(prims, p)
else
notes["lines / points primitives"] = (notes["lines / points primitives"] or 0) + 1
end
if p.targets and #p.targets > 0 then
notes["morph targets"] = (notes["morph targets"] or 0) + 1
end
end
if #prims == 0 then
return nil
end
-- attributes every primitive has
local all = { NORMAL = true }
local uvSets: { number } = {}
for k = 0, 7 do
local every = true
for _, p in prims do
if not p.attributes["TEXCOORD_" .. k] then
every = false
end
end
if every then
table.insert(uvSets, k)
end
end
local anyColor = false
for _, p in prims do
if not p.attributes.NORMAL or p.attributes.NORMAL.components ~= 3 then
all.NORMAL = false
end
if p.attributes.COLOR_0 then
anyColor = true
end
end
local m: Merged = { points = {}, counts = {}, indices = {}, normals = if all.NORMAL then {} else nil, uvs = {}, colors = if anyColor then {} else nil, hasAlpha = false, subsets = {} }
for _, k in uvSets do
m.uvs[k] = {}
end
local face = 0
for _, p in prims do
local base = #m.points // 3
local pos = (values(p.attributes.POSITION)) or {}
local nv = p.attributes.POSITION.count
table.move(pos, 1, nv * 3, #m.points + 1, m.points)
if m.normals then
local nrm = (values(p.attributes.NORMAL)) or {}
table.move(nrm, 1, nv * 3, #m.normals + 1, m.normals)
end
for _, k in uvSets do
local uv, c = values(p.attributes["TEXCOORD_" .. k])
local dst = m.uvs[k]
for i = 0, nv - 1 do
table.insert(dst, (uv :: { number })[i * c + 1] or 0)
table.insert(dst, (uv :: { number })[i * c + 2] or 0)
end
end
if m.colors then
local col, c = values(p.attributes.COLOR_0)
local dst = m.colors :: { number }
for i = 0, nv - 1 do
if col then
table.insert(dst, col[i * c + 1] or 1)
table.insert(dst, col[i * c + 2] or 1)
table.insert(dst, col[i * c + 3] or 1)
local a = if c >= 4 then col[i * c + 4] or 1 else 1
if a ~= 1 then
m.hasAlpha = true
end
table.insert(dst, a)
else
table.insert(dst, 1)
table.insert(dst, 1)
table.insert(dst, 1)
table.insert(dst, 1)
end
end
end
local counts, idx = faces(p, nv)
local sub = { faces = {}, material = p.material }
if counts and idx then
local ok = true
for _, v in idx do
if v < 0 or v >= nv then
ok = false
break
end
end
if ok then
for _, c in counts do
table.insert(m.counts, c)
table.insert(sub.faces, face)
face += 1
end
for _, v in idx do
table.insert(m.indices, v + base)
end
else
notes["out-of-range indices"] = (notes["out-of-range indices"] or 0) + 1
end
end
table.insert(m.subsets, sub)
end
return m
end
-- ------------------------------------------------------------------------------------------------ write
function Write.text(scene: Types.Scene, opts: Options?): (string, { [string]: number })
local o: Options = opts or {}
local notes: { [string]: number } = {}
local out: { string } = {}
local function line(depth: number, s: string)
table.insert(out, string.rep(" ", depth) .. s)
end
local nodes = scene.nodes or {}
local roots = scene.roots
if not roots or #roots == 0 then
local child = {}
for _, n in nodes do
for _, c in n.children or {} do
child[c] = true
end
end
roots = {}
for i in nodes do
if not child[i] then
table.insert(roots, i)
end
end
end
if #(scene.skins or {}) > 0 then
notes.skins = #scene.skins
end
local wrap = #roots ~= 1 or (nodes[roots[1]] == nil)
local rootNames = namer()
local rootName = if wrap then "root" else rootNames(nodes[roots[1]].name, "root")
-- texture files
local base = o.name and string.gsub(string.match(o.name, "([^/\\]+)$") or o.name, "%.[^.]*$", "") or "model"
local texFile: { [number]: string } = {}
for i, tex in scene.textures or {} do
local uri: string? = if tex.uri then (string.gsub(tex.uri, "\\", "/")) else nil
if tex.data and type(o.files) == "table" then
uri = uri or (base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png"))
if string.find(uri :: string, "^data:") or string.find(uri :: string, "^%a+://") then
uri = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png")
end
local files: any = o.files
if files[uri] == nil then
files[uri] = tex.data
end
elseif not uri then
uri = base .. "_" .. i .. "." .. (EXT[tex.mime or ""] or "png")
notes["textures without a file (not written)"] = (notes["textures without a file (not written)"] or 0) + 1
end
texFile[i] = uri :: string
end
-- animation: per node, per path -> { times, values (components) }
type Track = { times: { number }, vals: { number }, comps: number }
local tracks: { [number]: { [string]: Track } } = {}
local tcps = 24
local tMin, tMax = math.huge, -math.huge
for _, anim in scene.animations or {} do
for _, ch in anim.channels or {} do
if ch.path == "weights" then
notes["weights animation"] = (notes["weights animation"] or 0) + 1
elseif nodes[ch.node] and ch.input and ch.output then
local times = (values(ch.input)) or {}
local vals, comps = values(ch.output)
if vals and #times > 0 then
local stride = comps
local per = #vals // (comps * #times)
-- CUBICSPLINE: in-tangent, value, out-tangent per key: keep the value
local off = if ch.interpolation == "CUBICSPLINE" and per == 3 then comps else 0
local mult = if ch.interpolation == "CUBICSPLINE" and per == 3 then 3 else 1
local tv = {}
for k = 0, #times - 1 do
for c = 1, stride do
table.insert(tv, vals[k * comps * mult + off + c] or 0)
end
end
tracks[ch.node] = tracks[ch.node] or {}
tracks[ch.node][ch.path] = { times = times, vals = tv, comps = comps }
for _, t in times do
tMin = math.min(tMin, t * tcps)
tMax = math.max(tMax, t * tcps)
end
end
end
end
end
-- header
table.insert(out, "#usda 1.0")
table.insert(out, "(")
line(1, "defaultPrim = " .. quote(rootName))
line(1, 'doc = "formats-luau"')
if tMin <= tMax then
line(1, "endTimeCode = " .. fmt(tMax))
end
line(1, "metersPerUnit = " .. fmt(o.metersPerUnit or scene.meta.unit or 1))
if tMin <= tMax then
line(1, "startTimeCode = " .. fmt(tMin))
line(1, "timeCodesPerSecond = " .. fmt(tcps))
end
line(1, "upAxis = " .. quote(o.upAxis or (if scene.meta.up == "z" then "Z" else "Y")))
table.insert(out, ")")
table.insert(out, "")
local looksPath = "/" .. rootName .. "/Looks"
local matNames = namer()
local matPath: { [number]: string } = {}
for i, mat in scene.materials or {} do
matPath[i] = looksPath .. "/" .. matNames(mat.name, "material_" .. i)
end
-- xform ops of a node (+ its animation)
local function xform(depth: number, ni: number, n: Types.Node)
local tr = tracks[ni]
local order: { string } = {}
local function samples(track: Track, f: (vals: { number }, at: number) -> string): string
local parts = {}
for k, t in track.times do
table.insert(parts, fmt(t * tcps) .. ": " .. f(track.vals, (k - 1) * track.comps))
end
return "{ " .. table.concat(parts, ", ") .. " }"
end
local function quat(v: { number }, at: number): string
-- USD writes (real, i, j, k)
return tuple({ v[at + 4] or 1, v[at + 1] or 0, v[at + 2] or 0, v[at + 3] or 0 })
end
local function vec3(v: { number }, at: number): string
return tuple({ v[at + 1] or 0, v[at + 2] or 0, v[at + 3] or 0 })
end
local t, r, s = n.translation, n.rotation, n.scale
if n.matrix and #n.matrix == 16 then
if tr then
-- animated: start from the matrix's TRS
local m = n.matrix
local sx = math.sqrt(m[1] ^ 2 + m[2] ^ 2 + m[3] ^ 2)
local sy = math.sqrt(m[5] ^ 2 + m[6] ^ 2 + m[7] ^ 2)
local sz = math.sqrt(m[9] ^ 2 + m[10] ^ 2 + m[11] ^ 2)
t, s = { m[13], m[14], m[15] }, { sx, sy, sz }
r = nil
notes["matrix nodes with animation (rotation reset)"] = (notes["matrix nodes with animation (rotation reset)"] or 0) + 1
else
local m = n.matrix
line(depth, string.format("matrix4d xformOp:transform = ( %s, %s, %s, %s )", tuple({ m[1], m[2], m[3], m[4] }), tuple({ m[5], m[6], m[7], m[8] }), tuple({ m[9], m[10], m[11], m[12] }), tuple({ m[13], m[14], m[15], m[16] })))
line(depth, 'uniform token[] xformOpOrder = ["xformOp:transform"]')
return
end
end
if t or (tr and tr.translation) then
if t then
line(depth, "double3 xformOp:translate = " .. tuple({ t[1] or 0, t[2] or 0, t[3] or 0 }))
end
if tr and tr.translation then
line(depth, "double3 xformOp:translate.timeSamples = " .. samples(tr.translation, vec3))
end
table.insert(order, '"xformOp:translate"')
end
if r or (tr and tr.rotation) then
if r then
line(depth, "quatf xformOp:orient = " .. quat(r, 0))
end
if tr and tr.rotation then
line(depth, "quatf xformOp:orient.timeSamples = " .. samples(tr.rotation, quat))
end
table.insert(order, '"xformOp:orient"')
end
if s or (tr and tr.scale) then
if s then
line(depth, "float3 xformOp:scale = " .. tuple({ s[1] or 1, s[2] or 1, s[3] or 1 }))
end
if tr and tr.scale then
line(depth, "float3 xformOp:scale.timeSamples = " .. samples(tr.scale, vec3))
end
table.insert(order, '"xformOp:scale"')
end
if #order > 0 then
line(depth, "uniform token[] xformOpOrder = [" .. table.concat(order, ", ") .. "]")
end
end
local function meshBody(depth: number, m: Merged, path: string)
local doubleSided = false
for _, sub in m.subsets do
local mat = sub.material and scene.materials[sub.material]
if mat and mat.doubleSided then
doubleSided = true
end
end
if doubleSided then
line(depth, "uniform bool doubleSided = 1")
end
-- extent
local mn, mx = { math.huge, math.huge, math.huge }, { -math.huge, -math.huge, -math.huge }
for i = 0, #m.points // 3 - 1 do
for c = 1, 3 do
local v = m.points[i * 3 + c]
if v < mn[c] then
mn[c] = v
end
if v > mx[c] then
mx[c] = v
end
end
end
if #m.points > 0 then
line(depth, "float3[] extent = [" .. tuple(mn) .. ", " .. tuple(mx) .. "]")
end
line(depth, "int[] faceVertexCounts = " .. arrayText(m.counts, 1))
line(depth, "int[] faceVertexIndices = " .. arrayText(m.indices, 1))
local single = #m.subsets == 1
if single and m.subsets[1].material and matPath[m.subsets[1].material :: number] then
line(depth, "rel material:binding = <" .. matPath[m.subsets[1].material :: number] .. ">")
end
if m.normals then
line(depth, "normal3f[] normals = " .. arrayText(m.normals, 3) .. " (")
line(depth + 1, 'interpolation = "vertex"')
line(depth, ")")
end
line(depth, "point3f[] points = " .. arrayText(m.points, 3))
if m.colors then
line(depth, "color3f[] primvars:displayColor = " .. arrayText(m.colors, 3, 4) .. " (")
line(depth + 1, 'interpolation = "vertex"')
line(depth, ")")
if m.hasAlpha then
local alpha = {}
for i = 0, #m.colors // 4 - 1 do
alpha[i + 1] = m.colors[i * 4 + 4]
end
line(depth, "float[] primvars:displayOpacity = " .. arrayText(alpha, 1) .. " (")
line(depth + 1, 'interpolation = "vertex"')
line(depth, ")")
end
end
local uvKeys = {}
for k in m.uvs do
table.insert(uvKeys, k)
end
table.sort(uvKeys)
for _, k in uvKeys do
local name = if k == 0 then "st" else "st" .. k
line(depth, "texCoord2f[] primvars:" .. name .. " = " .. arrayText(m.uvs[k], 2, nil, nil, function(_i: number, c: number, v: number): number
return if c == 2 then 1 - v else v
end) .. " (")
line(depth + 1, 'interpolation = "vertex"')
line(depth, ")")
end
line(depth, 'uniform token subdivisionScheme = "none"')
if not single then
local names = namer()
for k, sub in m.subsets do
if #sub.faces > 0 then
local mp = sub.material and matPath[sub.material :: number]
table.insert(out, "")
line(depth, 'def GeomSubset "' .. names("subset_" .. k, "subset") .. '"' .. (if mp then ' (\n' .. string.rep(" ", depth + 1) .. 'prepend apiSchemas = ["MaterialBindingAPI"]\n' .. string.rep(" ", depth) .. ")" else ""))
line(depth, "{")
line(depth + 1, 'uniform token elementType = "face"')
line(depth + 1, 'uniform token familyName = "materialBind"')
line(depth + 1, "int[] indices = " .. arrayText(sub.faces, 1))
if mp then
line(depth + 1, "rel material:binding = <" .. mp .. ">")
end
line(depth, "}")
end
end
end
end
local function cameraBody(depth: number, c: Types.Camera)
if c.type == "orthographic" then
line(depth, "float2 clippingRange = " .. tuple({ c.znear or 0.01, c.zfar or 1000000 }))
line(depth, "float horizontalAperture = " .. fmt((c.xmag or 1) * 20))
line(depth, 'token projection = "orthographic"')
line(depth, "float verticalAperture = " .. fmt((c.ymag or 1) * 20))
return
end
local vap = 24
local yfov = c.yfov or 0.8
local focal = vap / (2 * math.tan(yfov / 2))
line(depth, "float2 clippingRange = " .. tuple({ c.znear or 0.01, c.zfar or 1000000 }))
line(depth, "float focalLength = " .. fmt(focal))
line(depth, "float horizontalAperture = " .. fmt(vap * (c.aspect or 1)))
line(depth, 'token projection = "perspective"')
line(depth, "float verticalAperture = " .. fmt(vap))
end
local LIGHT_TYPE = { directional = "DistantLight", point = "SphereLight", spot = "SphereLight" }
local function lightBody(depth: number, l: Types.Light)
local c = l.color or { 1, 1, 1 }
line(depth, "color3f inputs:color = " .. tuple({ c[1] or 1, c[2] or 1, c[3] or 1 }))
line(depth, "float inputs:intensity = " .. fmt(l.intensity or 1))
if l.type ~= "directional" then
line(depth, "float inputs:radius = 0")
end
if l.type == "spot" then
local outer = l.outerCone or math.pi / 4
line(depth, "float inputs:shaping:cone:angle = " .. fmt(outer * RAD))
line(depth, "float inputs:shaping:cone:softness = " .. fmt(if outer > 0 then 1 - (l.innerCone or 0) / outer else 0))
end
if l.type ~= "directional" then
line(depth, "bool treatAsPoint = 1")
end
end
local function lightHead(l: Types.Light): string
return if l.type == "spot" then ' (\n%s prepend apiSchemas = ["ShapingAPI"]\n%s)' else ""
end
local visited: { [number]: boolean } = {}
local function writeNode(depth: number, ni: number, path: string, names: (string?, string) -> string, isRoot: boolean)
local n = nodes[ni]
if not n or visited[ni] then
return
end
visited[ni] = true
local name = if isRoot and not wrap then rootName else names(n.name, "node_" .. ni)
local myPath = path .. "/" .. name
local mesh = n.mesh and scene.meshes[n.mesh]
local merged = mesh and merge(mesh, notes)
local cam = n.camera and scene.cameras[n.camera]
local lig = n.light and scene.lights[n.light]
local kind = "Xform"
local head = ""
local pad = string.rep(" ", depth)
if merged then
kind = "Mesh"
if #merged.subsets == 1 and merged.subsets[1].material and matPath[merged.subsets[1].material :: number] then
head = ' (\n' .. pad .. ' prepend apiSchemas = ["MaterialBindingAPI"]\n' .. pad .. ")"
end
elseif cam and not lig then
kind = "Camera"
elseif lig and not cam then
kind = LIGHT_TYPE[lig.type] or "SphereLight"
local h = lightHead(lig)
head = if h ~= "" then string.format(h, pad, pad) else ""
end
if n.skin then
notes.skins = (notes.skins or 0) + 0
end
table.insert(out, "")
line(depth, "def " .. kind .. " " .. quote(name) .. head)
line(depth, "{")
xform(depth + 1, ni, n)
if kind == "Mesh" then
meshBody(depth + 1, merged :: Merged, myPath)
elseif kind == "Camera" then
cameraBody(depth + 1, cam :: Types.Camera)
elseif kind ~= "Xform" then
lightBody(depth + 1, lig :: Types.Light)
end
local childNames = namer()
-- a camera / light that did not take the node's prim
if cam and kind ~= "Camera" then
table.insert(out, "")
line(depth + 1, "def Camera " .. quote(childNames(cam.name, "camera")))
line(depth + 1, "{")
cameraBody(depth + 2, cam)
line(depth + 1, "}")
end
if lig and kind == "Xform" or (lig and kind == "Mesh") or (lig and kind == "Camera") then
local l = lig :: Types.Light
local h = lightHead(l)
local pad2 = string.rep(" ", depth + 1)
table.insert(out, "")
line(depth + 1, "def " .. (LIGHT_TYPE[l.type] or "SphereLight") .. " " .. quote(childNames(l.name, "light")) .. (if h ~= "" then string.format(h, pad2, pad2) else ""))
line(depth + 1, "{")
lightBody(depth + 2, l)
line(depth + 1, "}")
end
if isRoot and not wrap then
Write._looks(out, depth + 1, scene, matPath, texFile, line)
end
for _, c in n.children or {} do
writeNode(depth + 1, c, myPath, childNames, false)
end
line(depth, "}")
end
if wrap then
line(0, "def Xform " .. quote(rootName))
line(0, "{")
Write._looks(out, 1, scene, matPath, texFile, line)
local names = namer()
names("Looks", "Looks")
for _, r in roots do
writeNode(1, r, "/" .. rootName, names, false)
end
line(0, "}")
else
writeNode(0, roots[1], "", rootNames, true)
end
table.insert(out, "")
return table.concat(out, "\n"), notes
end
-- the Looks scope: materials as UsdPreviewSurface networks
function Write._looks(out: { string }, depth: number, scene: Types.Scene, matPath: { [number]: string }, texFile: { [number]: string }, line: (number, string) -> ())
local mats = scene.materials or {}
if #mats == 0 then
return
end
table.insert(out, "")
line(depth, 'def Scope "Looks"')
line(depth, "{")
for i, mat in mats do
local path = matPath[i]
local mname = string.match(path, "([^/]+)$") :: string
table.insert(out, "")
line(depth + 1, "def Material " .. quote(mname))
line(depth + 1, "{")
local d = depth + 2
line(d, "token outputs:surface.connect = <" .. path .. "/PreviewSurface.outputs:surface>")
-- texture nodes (one per distinct ref)
type TexNode = { name: string, ref: Types.TextureRef, color: boolean }
local texNodes: { TexNode } = {}
local function texNode(ref: Types.TextureRef?, color: boolean): string?
if not ref or not texFile[ref.texture] then
return nil
end
for _, tn in texNodes do
if tn.ref == ref or (tn.ref.texture == ref.texture and (tn.ref.texCoord or 0) == (ref.texCoord or 0) and tn.ref.transform == nil and ref.transform == nil and tn.color == color) then
return tn.name
end
end
local name = "Texture_" .. (#texNodes + 1)
table.insert(texNodes, { name = name, ref = ref, color = color })
return name
end
local bc = mat.baseColor or { 1, 1, 1, 1 }
local blend = mat.alphaMode == "blend" or mat.alphaMode == "mask"
local diffuseTex = texNode(mat.baseColorTexture, true)
local mrTex = texNode(mat.metallicRoughnessTexture, false)
local emTex = texNode(mat.emissiveTexture, true)
local nTex = texNode(mat.normalTexture, false)
local oTex = texNode(mat.occlusionTexture, false)
table.insert(out, "")
line(d, 'def Shader "PreviewSurface"')
line(d, "{")
local e = d + 1
line(e, 'uniform token info:id = "UsdPreviewSurface"')
if diffuseTex then
line(e, "color3f inputs:diffuseColor.connect = <" .. path .. "/" .. diffuseTex .. ".outputs:rgb>")
else
line(e, "color3f inputs:diffuseColor = " .. tuple({ bc[1] or 1, bc[2] or 1, bc[3] or 1 }))
end
local em = mat.emissive or { 0, 0, 0 }
if emTex then
line(e, "color3f inputs:emissiveColor.connect = <" .. path .. "/" .. emTex .. ".outputs:rgb>")
elseif (em[1] or 0) ~= 0 or (em[2] or 0) ~= 0 or (em[3] or 0) ~= 0 then
line(e, "color3f inputs:emissiveColor = " .. tuple({ em[1] or 0, em[2] or 0, em[3] or 0 }))
end
local ext = mat.extensions or {}
if ext.KHR_materials_clearcoat and type(ext.KHR_materials_clearcoat.clearcoatFactor) == "number" then
line(e, "float inputs:clearcoat = " .. fmt(ext.KHR_materials_clearcoat.clearcoatFactor))
line(e, "float inputs:clearcoatRoughness = " .. fmt(tonumber(ext.KHR_materials_clearcoat.clearcoatRoughnessFactor) or 0))
end
if ext.KHR_materials_ior and type(ext.KHR_materials_ior.ior) == "number" then
line(e, "float inputs:ior = " .. fmt(ext.KHR_materials_ior.ior))
end
if mrTex then
line(e, "float inputs:metallic.connect = <" .. path .. "/" .. mrTex .. ".outputs:b>")
else
line(e, "float inputs:metallic = " .. fmt(mat.metallic or 0))
end
if nTex then
line(e, "normal3f inputs:normal.connect = <" .. path .. "/" .. nTex .. ".outputs:rgb>")
end
if oTex then
line(e, "float inputs:occlusion.connect = <" .. path .. "/" .. oTex .. ".outputs:r>")
end
if blend and diffuseTex then
line(e, "float inputs:opacity.connect = <" .. path .. "/" .. diffuseTex .. ".outputs:a>")
elseif blend then
line(e, "float inputs:opacity = " .. fmt(bc[4] or 1))
end
if mat.alphaMode == "mask" then
line(e, "float inputs:opacityThreshold = " .. fmt(mat.alphaCutoff or 0.5))
end
if mrTex then
line(e, "float inputs:roughness.connect = <" .. path .. "/" .. mrTex .. ".outputs:g>")
else
line(e, "float inputs:roughness = " .. fmt(mat.roughness or 1))
end
line(e, "token outputs:surface")
line(d, "}")
-- primvar readers per texCoord set, transforms, textures
local readers: { [number]: boolean } = {}
for _, tn in texNodes do
local tc = (tn.ref.transform and tn.ref.transform.texCoord) or tn.ref.texCoord or 0
if not readers[tc] then
readers[tc] = true
table.insert(out, "")
line(d, 'def Shader "PrimvarReader_' .. tc .. '"')
line(d, "{")
line(d + 1, 'uniform token info:id = "UsdPrimvarReader_float2"')
line(d + 1, "string inputs:varname = " .. quote(if tc == 0 then "st" else "st" .. tc))
line(d + 1, "float2 outputs:result")
line(d, "}")
end
end
for _, tn in texNodes do
local ref = tn.ref
local tc = (ref.transform and ref.transform.texCoord) or ref.texCoord or 0
local stSource = path .. "/PrimvarReader_" .. tc .. ".outputs:result"
if ref.transform then
local tr = ref.transform :: any
table.insert(out, "")
line(d, 'def Shader "' .. tn.name .. '_Transform"')
line(d, "{")
line(d + 1, 'uniform token info:id = "UsdTransform2d"')
line(d + 1, "float2 inputs:in.connect = <" .. stSource .. ">")
if tr.rotation then
line(d + 1, "float inputs:rotation = " .. fmt(tr.rotation * RAD))
end
if tr.scale then
line(d + 1, "float2 inputs:scale = " .. tuple({ tr.scale[1] or 1, tr.scale[2] or 1 }))
end
if tr.offset then
line(d + 1, "float2 inputs:translation = " .. tuple({ tr.offset[1] or 0, tr.offset[2] or 0 }))
end
line(d + 1, "float2 outputs:result")
line(d, "}")
stSource = path .. "/" .. tn.name .. "_Transform.outputs:result"
end
local tex = scene.textures[ref.texture]
local sampler = tex and tex.sampler or {}
table.insert(out, "")
line(d, 'def Shader "' .. tn.name .. '"')
line(d, "{")
line(d + 1, 'uniform token info:id = "UsdUVTexture"')
line(d + 1, "asset inputs:file = " .. asset(texFile[ref.texture]))
if tn.ref == mat.baseColorTexture and ((bc[1] or 1) ~= 1 or (bc[2] or 1) ~= 1 or (bc[3] or 1) ~= 1 or (bc[4] or 1) ~= 1) then
line(d + 1, "float4 inputs:scale = " .. tuple({ bc[1] or 1, bc[2] or 1, bc[3] or 1, bc[4] or 1 }))
end
if tn.ref == mat.normalTexture then
line(d + 1, "float4 inputs:bias = (-1, -1, -1, 0)")
line(d + 1, "float4 inputs:scale = (2, 2, 2, 1)")
end
line(d + 1, 'token inputs:sourceColorSpace = "' .. (if tn.color then "sRGB" else "raw") .. '"')
line(d + 1, "float2 inputs:st.connect = <" .. stSource .. ">")
line(d + 1, 'token inputs:wrapS = "' .. (sampler.wrapS or "repeat") .. '"')
line(d + 1, 'token inputs:wrapT = "' .. (sampler.wrapT or "repeat") .. '"')
line(d + 1, "float outputs:a")
line(d + 1, "float outputs:b")
line(d + 1, "float outputs:g")
line(d + 1, "float outputs:r")
line(d + 1, "float3 outputs:rgb")
line(d, "}")
end
line(depth + 1, "}")
end
line(depth, "}")
end
return Write
+221
View File
@@ -0,0 +1,221 @@
--!strict
-- model/usda: USD ASCII layers (.usda, .usd in text form) and USDZ packages holding them. New code, from the Sdf text
-- format and the UsdGeom / UsdShade / UsdLux schema documentation (OpenUSD 26.x); checked against OpenUSD's own
-- reader / writer (pxr) and Blender's USD exporter.
-- Reads: stage metadata (upAxis -> meta.up, metersPerUnit -> meta.unit, defaultPrim, timeCodesPerSecond, start /
-- endTimeCode), the prim tree (def / over; class skipped; selected variants merged), xform op stacks (translate, scale,
-- rotateX/Y/Z, rotateXYZ ... rotateZYX, orient, transform, !invert!, !resetXformStack!) with time samples -> one
-- animation of TRS channels, Mesh (faceVertexCounts / Indices, holes, leftHanded orientation, normals, every
-- texCoord2f primvar -> TEXCOORD_n with st first, displayColor / displayOpacity, all interpolations, :indices,
-- GeomSubsets -> one primitive each), UsdPreviewSurface materials with UsdUVTexture / UsdPrimvarReader_float2 /
-- UsdTransform2d, material:binding (inherited, per subset), Camera, DistantLight / SphereLight (+ ShapingAPI cone ->
-- spot) / RectLight / DiskLight (-> spot lights over a hemisphere). Textures stay encoded: bytes from opts.files /
-- opts.resolve (or the USDZ package) + mime, else just the uri (F.model.loadTextures decodes them).
-- Writes .usda (see model/usda/Write): Xform / Mesh / GeomSubset / Material / Shader / Camera / lights, time samples.
-- Not supported: USDC binary crate files (.usdc, and .usd / USDZ holding one: UNSUPPORTED), composition arcs
-- (references, payloads, inherits, specializes, subLayers: ignored and listed in meta.source.unsupported), UsdSkel
-- skinning, blend shapes, curves / points / NURBS prims, point instancers, MaterialX shading networks, writing USDZ.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Zip = require("@formats/containers/Zip")
local Parse = require("@formats/model/usda/Parse")
local Build = require("@formats/model/usda/Build")
local Write = require("@formats/model/usda/Write")
-- ------------------------------------------------------------------------------------------------ contract
local Usda = {
name = "usda",
category = "model",
extensions = { "usda", "usd", "usdz" },
mime = { "model/vnd.usda", "model/vnd.usdz+zip" },
deps = { "core/Err", "core/Bytes", "Types", "containers/Zip" },
caps = { decode = true, encode = true, materials = true, animation = true, cameras = true, lights = true, polygons = true, vertexColors = true, usdz = "read", usdc = false },
}
-- ------------------------------------------------------------------------------------------------ types
export type DecodeOptions = {
triangulate: boolean?, -- fan-triangulate faces (default true); false keeps "polygons" primitives
flipV: boolean?, -- TEXCOORD_n.v = 1 - v (default true: glTF's top-left origin)
resolve: ((uri: string) -> any)?, -- texture files next to the layer (the api sets it for paths)
files: { [string]: any }?, -- or: the files by asset path
maxVertices: number?, -- refuse meshes with more points / face corners (default 2^25)
maxBytes: number?, -- refuse numeric arrays over this many bytes (default 2^30)
}
export type EncodeOptions = {
files: { [string]: any }?, -- receives embedded texture bytes as <name>_<n>.<ext>
name: string?, -- the destination's file name (names the texture files)
format: string?, -- "usdz" -> UNSUPPORTED (set by the api from the destination's extension)
upAxis: string?, -- "Y" / "Z" (default: from scene.meta.up)
metersPerUnit: number?, -- default scene.meta.unit or 1
}
-- ------------------------------------------------------------------------------------------------ sniff
local function isUsdz(r: Bytes.Reader): boolean
if r:peek(4) ~= "PK\3\4" then
return false
end
-- the first entry is the root layer
local lo, hi = r:peekU8(26), r:peekU8(27)
if lo < 0 or hi < 0 then
return false
end
local nameLen = lo + hi * 256
local name = string.lower(r:peek(30 + nameLen))
name = string.sub(name, 31)
return string.find(name, "%.usd[ac]?$") ~= nil
end
function Usda.sniff(r: Bytes.Reader): number
local head = r:peek(8)
if string.sub(head, 1, 5) == "#usda" or string.sub(head, 1, 8) == "\239\187\191#usda" then
return 1
end
if head == "PXR-USDC" then
return 0.9 -- recognised so the error says USDC is not supported
end
if isUsdz(r) then
return 0.95
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function fetcher(opts: DecodeOptions?, package: any): (uri: string) -> buffer?
return function(uri: string): buffer?
local candidates = { uri }
local slashed = string.gsub(uri, "\\", "/")
local stripped = string.gsub(slashed, "^%./", "")
if slashed ~= uri then
table.insert(candidates, slashed)
end
if stripped ~= slashed then
table.insert(candidates, stripped)
end
-- packaged assets: "model.usdz[textures/a.png]"
local inner = string.match(uri, "%[(.+)%]$")
if inner then
table.insert(candidates, inner)
end
for _, u in candidates do
if package then
local data = package:read(u)
if data then
return data
end
end
local v: any = nil
if opts and type(opts.files) == "table" then
v = opts.files[u]
end
if v == nil and opts and type(opts.resolve) == "function" then
local ok, res = pcall(opts.resolve, u)
v = if ok then res else nil
end
if type(v) == "string" then
return buffer.fromstring(v)
elseif type(v) == "buffer" then
return v
end
end
return nil
end
end
function Usda.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Scene?, Err.Err?)
local head = r:peek(8)
if head == "PXR-USDC" then
return nil, Err.new(Err.UNSUPPORTED, "USDC binary crate files (convert with usdcat to .usda)")
end
local text: string
local package: any = nil
local usdz = false
if string.sub(head, 1, 4) == "PK\3\4" then
local archive, zerr = Zip.open(r)
if not archive then
return nil, zerr or Err.new(Err.CORRUPT, "bad USDZ package")
end
local entries = archive:list()
local root = nil
for _, e in entries do
if not e.dir and string.find(string.lower(e.name), "%.usd[ac]?$") then
root = e
break
end
end
if not root then
return nil, Err.new(Err.CORRUPT, "the USDZ package holds no USD layer")
end
local data, rerr = archive:read(root)
if not data then
return nil, rerr
end
if buffer.len(data) >= 8 and buffer.readstring(data, 0, 8) == "PXR-USDC" then
return nil, Err.new(Err.UNSUPPORTED, "USDZ holding a USDC binary crate layer")
end
text = buffer.tostring(data)
package = archive
usdz = true
else
text = buffer.readstring(r.buf, r.base, r.limit - r.base)
end
if not Parse.version(text) then
return nil, Err.new(Err.CORRUPT, "no #usda header")
end
local layer, msg, at = Parse.layer(text, opts and opts.maxBytes)
if not layer then
if msg == "array over the size limit" then
return nil, Err.new(Err.LIMIT, msg :: string, at)
end
local code = if at and at >= #text - 1 then Err.TRUNCATED else Err.CORRUPT
if msg and string.find(msg, "^unterminated") then
code = Err.TRUNCATED
end
return nil, Err.new(code, msg or "parse error", if usdz then nil else at)
end
local scene, err = Build.scene(layer, {
triangulate = opts and opts.triangulate,
flipV = opts and opts.flipV,
maxVertices = opts and opts.maxVertices,
fetch = fetcher(opts, package),
})
if not scene then
if err == "LIMIT" then
return nil, Err.new(Err.LIMIT, "a mesh over maxVertices")
end
return nil, Err.new(Err.CORRUPT, err or "bad scene")
end
local src: any = scene.meta.source
src.version = Parse.version(text)
src.usdz = usdz or nil
return scene, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Usda.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
if opts and opts.format == "usdz" then
return nil, Err.new(Err.UNSUPPORTED, "writing USDZ; write .usda")
end
local ok, text = pcall(Write.text, scene, opts)
if not ok then
return nil, Err.new(Err.ARG, "bad scene: " .. tostring(text))
end
return buffer.fromstring(text :: any), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- parse(text) -> the raw layer (prim specs, properties, metadata) | nil, Err: for prims the Scene does not cover
function Usda.parse(text: string): (Parse.Layer?, Err.Err?)
local layer, msg, at = Parse.layer(text)
if not layer then
return nil, Err.new(Err.CORRUPT, msg or "parse error", at)
end
return layer, nil
end
return Usda